PostgreSQL Source Code  git master
json.h File Reference
#include "lib/stringinfo.h"
Include dependency graph for json.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void escape_json (StringInfo buf, const char *str)
 
char * JsonEncodeDateTime (char *buf, Datum value, Oid typid, const int *tzp)
 
bool to_json_is_immutable (Oid typoid)
 
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_array_worker (int nargs, const Datum *args, const bool *nulls, const Oid *types, bool absent_on_null)
 
bool json_validate (text *json, bool check_unique_keys, bool throw_error)
 

Function Documentation

◆ escape_json()

void escape_json ( StringInfo  buf,
const char *  str 
)

Definition at line 1549 of file json.c.

1550 {
1551  const char *p;
1552 
1554  for (p = str; *p; p++)
1555  {
1556  switch (*p)
1557  {
1558  case '\b':
1559  appendStringInfoString(buf, "\\b");
1560  break;
1561  case '\f':
1562  appendStringInfoString(buf, "\\f");
1563  break;
1564  case '\n':
1565  appendStringInfoString(buf, "\\n");
1566  break;
1567  case '\r':
1568  appendStringInfoString(buf, "\\r");
1569  break;
1570  case '\t':
1571  appendStringInfoString(buf, "\\t");
1572  break;
1573  case '"':
1574  appendStringInfoString(buf, "\\\"");
1575  break;
1576  case '\\':
1577  appendStringInfoString(buf, "\\\\");
1578  break;
1579  default:
1580  if ((unsigned char) *p < ' ')
1581  appendStringInfo(buf, "\\u%04x", (int) *p);
1582  else
1584  break;
1585  }
1586  }
1588 }
const char * str
static char * buf
Definition: pg_test_fsync.c:73
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:204

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

Referenced by AddFileToBackupManifest(), appendJSONKeyValue(), composite_to_json(), datum_to_json_internal(), escape_yaml(), ExplainDummyGroup(), ExplainOpenGroup(), ExplainProperty(), ExplainPropertyList(), ExplainPropertyListNested(), hstore_to_json(), hstore_to_json_loose(), json_object(), json_object_two_arg(), jsonb_put_escaped_value(), populate_scalar(), printJsonPathItem(), sn_object_field_start(), sn_scalar(), transform_string_values_object_field_start(), transform_string_values_scalar(), transformJsonTableColumn(), and write_jsonlog().

◆ 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 1321 of file json.c.

1323 {
1324  int i;
1325  const char *sep = "";
1326  StringInfo result;
1327 
1328  result = makeStringInfo();
1329 
1330  appendStringInfoChar(result, '[');
1331 
1332  for (i = 0; i < nargs; i++)
1333  {
1334  if (absent_on_null && nulls[i])
1335  continue;
1336 
1337  appendStringInfoString(result, sep);
1338  sep = ", ";
1339  add_json(args[i], nulls[i], result, types[i], false);
1340  }
1341 
1342  appendStringInfoChar(result, ']');
1343 
1344  return PointerGetDatum(cstring_to_text_with_len(result->data, result->len));
1345 }
struct typedefs * types
Definition: ecpg.c:29
int i
Definition: isn.c:73
static void add_json(Datum val, bool is_null, StringInfo result, Oid val_type, bool key_scalar)
Definition: json.c:593
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:196

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

Referenced by ExecEvalJsonConstructor(), and json_build_array().

◆ 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 1208 of file json.c.

1210 {
1211  int i;
1212  const char *sep = "";
1213  StringInfo result;
1214  JsonUniqueBuilderState unique_check;
1215 
1216  if (nargs % 2 != 0)
1217  ereport(ERROR,
1218  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1219  errmsg("argument list must have even number of elements"),
1220  /* translator: %s is a SQL function name */
1221  errhint("The arguments of %s must consist of alternating keys and values.",
1222  "json_build_object()")));
1223 
1224  result = makeStringInfo();
1225 
1226  appendStringInfoChar(result, '{');
1227 
1228  if (unique_keys)
1229  json_unique_builder_init(&unique_check);
1230 
1231  for (i = 0; i < nargs; i += 2)
1232  {
1233  StringInfo out;
1234  bool skip;
1235  int key_offset;
1236 
1237  /* Skip null values if absent_on_null */
1238  skip = absent_on_null && nulls[i + 1];
1239 
1240  if (skip)
1241  {
1242  /* If key uniqueness check is needed we must save skipped keys */
1243  if (!unique_keys)
1244  continue;
1245 
1246  out = json_unique_builder_get_throwawaybuf(&unique_check);
1247  }
1248  else
1249  {
1250  appendStringInfoString(result, sep);
1251  sep = ", ";
1252  out = result;
1253  }
1254 
1255  /* process key */
1256  if (nulls[i])
1257  ereport(ERROR,
1258  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1259  errmsg("null value not allowed for object key")));
1260 
1261  /* save key offset before appending it */
1262  key_offset = out->len;
1263 
1264  add_json(args[i], false, out, types[i], true);
1265 
1266  if (unique_keys)
1267  {
1268  /* check key uniqueness after key appending */
1269  const char *key = &out->data[key_offset];
1270 
1271  if (!json_unique_check_key(&unique_check.check, key, 0))
1272  ereport(ERROR,
1273  errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
1274  errmsg("duplicate JSON object key value: %s", key));
1275 
1276  if (skip)
1277  continue;
1278  }
1279 
1280  appendStringInfoString(result, " : ");
1281 
1282  /* process value */
1283  add_json(args[i + 1], nulls[i + 1], result, types[i + 1], false);
1284  }
1285 
1286  appendStringInfoChar(result, '}');
1287 
1288  return PointerGetDatum(cstring_to_text_with_len(result->data, result->len));
1289 }
int errhint(const char *fmt,...)
Definition: elog.c:1315
int errcode(int sqlerrcode)
Definition: elog.c:855
int errmsg(const char *fmt,...)
Definition: elog.c:1068
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
static StringInfo json_unique_builder_get_throwawaybuf(JsonUniqueBuilderState *cxt)
Definition: json.c:969
static bool json_unique_check_key(JsonUniqueCheckState *cxt, const char *key, int object_id)
Definition: json.c:949
static void json_unique_builder_init(JsonUniqueBuilderState *cxt)
Definition: json.c:941
static const struct exclude_list_item skip[]
Definition: pg_checksums.c:108
JsonUniqueCheckState check
Definition: json.c:69

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(), skip, and types.

Referenced by ExecEvalJsonConstructor(), and json_build_object().

◆ json_validate()

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

Definition at line 1650 of file json.c.

1651 {
1652  JsonLexContext lex;
1653  JsonSemAction uniqueSemAction = {0};
1655  JsonParseErrorType result;
1656 
1657  makeJsonLexContext(&lex, json, check_unique_keys);
1658 
1659  if (check_unique_keys)
1660  {
1661  state.lex = &lex;
1662  state.stack = NULL;
1663  state.id_counter = 0;
1664  state.unique = true;
1665  json_unique_check_init(&state.check);
1666 
1667  uniqueSemAction.semstate = &state;
1668  uniqueSemAction.object_start = json_unique_object_start;
1670  uniqueSemAction.object_end = json_unique_object_end;
1671  }
1672 
1673  result = pg_parse_json(&lex, check_unique_keys ? &uniqueSemAction : &nullSemAction);
1674 
1675  if (result != JSON_SUCCESS)
1676  {
1677  if (throw_error)
1678  json_errsave_error(result, &lex, NULL);
1679 
1680  return false; /* invalid json */
1681  }
1682 
1683  if (check_unique_keys && !state.unique)
1684  {
1685  if (throw_error)
1686  ereport(ERROR,
1687  (errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
1688  errmsg("duplicate JSON object key value")));
1689 
1690  return false; /* not unique keys */
1691  }
1692 
1693  if (check_unique_keys)
1694  freeJsonLexContext(&lex);
1695 
1696  return true; /* ok */
1697 }
static JsonParseErrorType json_unique_object_start(void *_state)
Definition: json.c:1592
static void json_unique_check_init(JsonUniqueCheckState *cxt)
Definition: json.c:923
static JsonParseErrorType json_unique_object_field_start(void *_state, char *field, bool isnull)
Definition: json.c:1625
static JsonParseErrorType json_unique_object_end(void *_state)
Definition: json.c:1610
JsonSemAction nullSemAction
Definition: jsonapi.c:224
JsonParseErrorType pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
Definition: jsonapi.c:521
void freeJsonLexContext(JsonLexContext *lex)
Definition: jsonapi.c:482
JsonParseErrorType
Definition: jsonapi.h:37
@ JSON_SUCCESS
Definition: jsonapi.h:38
JsonLexContext * makeJsonLexContext(JsonLexContext *lex, text *json, bool need_escapes)
Definition: jsonfuncs.c:538
void json_errsave_error(JsonParseErrorType error, JsonLexContext *lex, Node *escontext)
Definition: jsonfuncs.c:639
json_struct_action object_start
Definition: jsonapi.h:135
json_ofield_action object_field_start
Definition: jsonapi.h:139
void * semstate
Definition: jsonapi.h:134
json_struct_action object_end
Definition: jsonapi.h:136
Definition: regguts.h:323

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 301 of file json.c.

302 {
303  if (!buf)
304  buf = palloc(MAXDATELEN + 1);
305 
306  switch (typid)
307  {
308  case DATEOID:
309  {
310  DateADT date;
311  struct pg_tm tm;
312 
314 
315  /* Same as date_out(), but forcing DateStyle */
316  if (DATE_NOT_FINITE(date))
318  else
319  {
321  &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
323  }
324  }
325  break;
326  case TIMEOID:
327  {
328  TimeADT time = DatumGetTimeADT(value);
329  struct pg_tm tt,
330  *tm = &tt;
331  fsec_t fsec;
332 
333  /* Same as time_out(), but forcing DateStyle */
334  time2tm(time, tm, &fsec);
335  EncodeTimeOnly(tm, fsec, false, 0, USE_XSD_DATES, buf);
336  }
337  break;
338  case TIMETZOID:
339  {
341  struct pg_tm tt,
342  *tm = &tt;
343  fsec_t fsec;
344  int tz;
345 
346  /* Same as timetz_out(), but forcing DateStyle */
347  timetz2tm(time, tm, &fsec, &tz);
348  EncodeTimeOnly(tm, fsec, true, tz, USE_XSD_DATES, buf);
349  }
350  break;
351  case TIMESTAMPOID:
352  {
354  struct pg_tm tm;
355  fsec_t fsec;
356 
358  /* Same as timestamp_out(), but forcing DateStyle */
361  else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
362  EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
363  else
364  ereport(ERROR,
365  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
366  errmsg("timestamp out of range")));
367  }
368  break;
369  case TIMESTAMPTZOID:
370  {
372  struct pg_tm tm;
373  int tz;
374  fsec_t fsec;
375  const char *tzn = NULL;
376 
378 
379  /*
380  * If a time zone is specified, we apply the time-zone shift,
381  * convert timestamptz to pg_tm as if it were without a time
382  * zone, and then use the specified time zone for converting
383  * the timestamp into a string.
384  */
385  if (tzp)
386  {
387  tz = *tzp;
389  }
390 
391  /* Same as timestamptz_out(), but forcing DateStyle */
394  else if (timestamp2tm(timestamp, tzp ? NULL : &tz, &tm, &fsec,
395  tzp ? NULL : &tzn, NULL) == 0)
396  {
397  if (tzp)
398  tm.tm_isdst = 1; /* set time-zone presence flag */
399 
400  EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
401  }
402  else
403  ereport(ERROR,
404  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
405  errmsg("timestamp out of range")));
406  }
407  break;
408  default:
409  elog(ERROR, "unknown jsonb value datetime type oid %u", typid);
410  return NULL;
411  }
412 
413  return buf;
414 }
void EncodeTimeOnly(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
Definition: datetime.c:4312
void j2date(int jd, int *year, int *month, int *day)
Definition: datetime.c:311
void EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
Definition: datetime.c:4342
void EncodeDateOnly(struct pg_tm *tm, int style, char *str)
Definition: datetime.c:4227
void EncodeSpecialTimestamp(Timestamp dt, char *str)
Definition: timestamp.c:1597
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1902
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:2403
int time2tm(TimeADT time, struct pg_tm *tm, fsec_t *fsec)
Definition: date.c:1488
void EncodeSpecialDate(DateADT dt, char *str)
Definition: date.c:294
#define DATE_NOT_FINITE(j)
Definition: date.h:43
int32 DateADT
Definition: date.h:23
static DateADT DatumGetDateADT(Datum X)
Definition: date.h:54
static TimeADT DatumGetTimeADT(Datum X)
Definition: date.h:60
static TimeTzADT * DatumGetTimeTzADTP(Datum X)
Definition: date.h:66
int64 TimeADT
Definition: date.h:25
#define elog(elevel,...)
Definition: elog.h:224
#define MAXDATELEN
Definition: datetime.h:200
static struct @155 value
static struct pg_tm tm
Definition: localtime.c:104
void * palloc(Size size)
Definition: mcxt.c:1317
#define USE_XSD_DATES
Definition: miscadmin.h:238
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(), and datum_to_jsonb_internal().

◆ to_json_is_immutable()

bool to_json_is_immutable ( Oid  typoid)

Definition at line 691 of file json.c.

692 {
693  JsonTypeCategory tcategory;
694  Oid outfuncoid;
695 
696  json_categorize_type(typoid, false, &tcategory, &outfuncoid);
697 
698  switch (tcategory)
699  {
700  case JSONTYPE_BOOL:
701  case JSONTYPE_JSON:
702  case JSONTYPE_JSONB:
703  case JSONTYPE_NULL:
704  return true;
705 
706  case JSONTYPE_DATE:
707  case JSONTYPE_TIMESTAMP:
709  return false;
710 
711  case JSONTYPE_ARRAY:
712  return false; /* TODO recurse into elements */
713 
714  case JSONTYPE_COMPOSITE:
715  return false; /* TODO recurse into fields */
716 
717  case JSONTYPE_NUMERIC:
718  case JSONTYPE_CAST:
719  case JSONTYPE_OTHER:
720  return func_volatile(outfuncoid) == PROVOLATILE_IMMUTABLE;
721  }
722 
723  return false; /* not reached */
724 }
void json_categorize_type(Oid typoid, bool is_jsonb, JsonTypeCategory *tcategory, Oid *outfuncoid)
Definition: jsonfuncs.c:5974
JsonTypeCategory
Definition: jsonfuncs.h:69
@ JSONTYPE_JSON
Definition: jsonfuncs.h:76
@ JSONTYPE_NULL
Definition: jsonfuncs.h:70
@ 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_OTHER
Definition: jsonfuncs.h:81
@ JSONTYPE_CAST
Definition: jsonfuncs.h:80
@ JSONTYPE_COMPOSITE
Definition: jsonfuncs.h:79
@ JSONTYPE_ARRAY
Definition: jsonfuncs.h:78
@ JSONTYPE_TIMESTAMPTZ
Definition: jsonfuncs.h:75
@ JSONTYPE_JSONB
Definition: jsonfuncs.h:77
char func_volatile(Oid funcid)
Definition: lsyscache.c:1780
unsigned int Oid
Definition: postgres_ext.h:31

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().