1 /*-------------------------------------------------------------------------
4 * JSON data type support.
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/utils/adt/json.c
12 *-------------------------------------------------------------------------
16 #include "access/htup_details.h"
17 #include "access/transam.h"
18 #include "catalog/pg_type.h"
19 #include "executor/spi.h"
21 #include "lib/stringinfo.h"
22 #include "libpq/pqformat.h"
23 #include "mb/pg_wchar.h"
24 #include "miscadmin.h"
25 #include "parser/parse_coerce.h"
26 #include "utils/array.h"
27 #include "utils/builtins.h"
28 #include "utils/date.h"
29 #include "utils/datetime.h"
30 #include "utils/lsyscache.h"
31 #include "utils/json.h"
32 #include "utils/jsonapi.h"
33 #include "utils/typcache.h"
34 #include "utils/syscache.h"
37 * The context of the parser is maintained by the recursive descent
38 * mechanism, but is passed explicitly to the error reporting routine
39 * for better diagnostics.
41 typedef enum /* contexts of JSON parser */
43 JSON_PARSE_VALUE, /* expecting a value */
44 JSON_PARSE_STRING, /* expecting a string (for a field name) */
45 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
46 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
47 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
48 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
49 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
50 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
51 JSON_PARSE_END /* saw the end of a document, expect nothing */
54 typedef enum /* type categories for datum_to_json */
56 JSONTYPE_NULL, /* null, so we didn't bother to identify */
57 JSONTYPE_BOOL, /* boolean (built-in types only) */
58 JSONTYPE_NUMERIC, /* numeric (ditto) */
59 JSONTYPE_DATE, /* we use special formatting for datetimes */
62 JSONTYPE_JSON, /* JSON itself (and JSONB) */
63 JSONTYPE_ARRAY, /* array */
64 JSONTYPE_COMPOSITE, /* composite */
65 JSONTYPE_CAST, /* something with an explicit cast to JSON */
66 JSONTYPE_OTHER /* all else */
69 typedef struct JsonAggState
72 JsonTypeCategory key_category;
74 JsonTypeCategory val_category;
78 static inline void json_lex(JsonLexContext *lex);
79 static inline void json_lex_string(JsonLexContext *lex);
80 static inline void json_lex_number(JsonLexContext *lex, char *s,
81 bool *num_err, int *total_len);
82 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
83 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
84 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
85 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
86 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
87 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex) pg_attribute_noreturn();
88 static void report_invalid_token(JsonLexContext *lex) pg_attribute_noreturn();
89 static int report_json_context(JsonLexContext *lex);
90 static char *extract_mb_char(char *s);
91 static void composite_to_json(Datum composite, StringInfo result,
93 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
94 Datum *vals, bool *nulls, int *valcount,
95 JsonTypeCategory tcategory, Oid outfuncoid,
97 static void array_to_json_internal(Datum array, StringInfo result,
99 static void json_categorize_type(Oid typoid,
100 JsonTypeCategory *tcategory,
102 static void datum_to_json(Datum val, bool is_null, StringInfo result,
103 JsonTypeCategory tcategory, Oid outfuncoid,
105 static void add_json(Datum val, bool is_null, StringInfo result,
106 Oid val_type, bool key_scalar);
107 static text *catenate_stringinfo_string(StringInfo buffer, const char *addon);
109 /* the null action object used for pure validation */
110 static JsonSemAction nullSemAction =
112 NULL, NULL, NULL, NULL, NULL,
113 NULL, NULL, NULL, NULL, NULL
116 /* Recursive Descent parser support routines */
121 * what is the current look_ahead token?
123 static inline JsonTokenType
124 lex_peek(JsonLexContext *lex)
126 return lex->token_type;
132 * accept the look_ahead token and move the lexer to the next token if the
133 * look_ahead token matches the token parameter. In that case, and if required,
134 * also hand back the de-escaped lexeme.
136 * returns true if the token matched, false otherwise.
139 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
141 if (lex->token_type == token)
145 if (lex->token_type == JSON_TOKEN_STRING)
147 if (lex->strval != NULL)
148 *lexeme = pstrdup(lex->strval->data);
152 int len = (lex->token_terminator - lex->token_start);
153 char *tokstr = palloc(len + 1);
155 memcpy(tokstr, lex->token_start, len);
169 * move the lexer to the next token if the current look_ahead token matches
170 * the parameter token. Otherwise, report an error.
173 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
175 if (!lex_accept(lex, token, NULL))
176 report_parse_error(ctx, lex);
179 /* chars to consider as part of an alphanumeric token */
180 #define JSON_ALPHANUMERIC_CHAR(c) \
181 (((c) >= 'a' && (c) <= 'z') || \
182 ((c) >= 'A' && (c) <= 'Z') || \
183 ((c) >= '0' && (c) <= '9') || \
188 * Utility function to check if a string is a valid JSON number.
190 * str is of length len, and need not be null-terminated.
193 IsValidJsonNumber(const char *str, int len)
197 JsonLexContext dummy_lex;
203 * json_lex_number expects a leading '-' to have been eaten already.
205 * having to cast away the constness of str is ugly, but there's not much
210 dummy_lex.input = unconstify(char *, str) +1;
211 dummy_lex.input_length = len - 1;
215 dummy_lex.input = unconstify(char *, str);
216 dummy_lex.input_length = len;
219 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error, &total_len);
221 return (!numeric_error) && (total_len == dummy_lex.input_length);
228 json_in(PG_FUNCTION_ARGS)
230 char *json = PG_GETARG_CSTRING(0);
231 text *result = cstring_to_text(json);
235 lex = makeJsonLexContext(result, false);
236 pg_parse_json(lex, &nullSemAction);
238 /* Internal representation is the same as text, for now */
239 PG_RETURN_TEXT_P(result);
246 json_out(PG_FUNCTION_ARGS)
248 /* we needn't detoast because text_to_cstring will handle that */
249 Datum txt = PG_GETARG_DATUM(0);
251 PG_RETURN_CSTRING(TextDatumGetCString(txt));
258 json_send(PG_FUNCTION_ARGS)
260 text *t = PG_GETARG_TEXT_PP(0);
263 pq_begintypsend(&buf);
264 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
265 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
272 json_recv(PG_FUNCTION_ARGS)
274 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
279 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
282 lex = makeJsonLexContextCstringLen(str, nbytes, false);
283 pg_parse_json(lex, &nullSemAction);
285 PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
291 * lex constructor, with or without StringInfo object
292 * for de-escaped lexemes.
294 * Without is better as it makes the processing faster, so only make one
295 * if really required.
297 * If you already have the json as a text* value, use the first of these
298 * functions, otherwise use makeJsonLexContextCstringLen().
301 makeJsonLexContext(text *json, bool need_escapes)
303 return makeJsonLexContextCstringLen(VARDATA_ANY(json),
304 VARSIZE_ANY_EXHDR(json),
309 makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
311 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
313 lex->input = lex->token_terminator = lex->line_start = json;
314 lex->line_number = 1;
315 lex->input_length = len;
317 lex->strval = makeStringInfo();
324 * Publicly visible entry point for the JSON parser.
326 * lex is a lexing context, set up for the json to be processed by calling
327 * makeJsonLexContext(). sem is a structure of function pointers to semantic
328 * action routines to be called at appropriate spots during parsing, and a
329 * pointer to a state object to be passed to those routines.
332 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
336 /* get the initial token */
341 /* parse by recursive descent */
344 case JSON_TOKEN_OBJECT_START:
345 parse_object(lex, sem);
347 case JSON_TOKEN_ARRAY_START:
348 parse_array(lex, sem);
351 parse_scalar(lex, sem); /* json can be a bare scalar */
354 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
359 * json_count_array_elements
361 * Returns number of array elements in lex context at start of array token
362 * until end of array token at same nesting level.
364 * Designed to be called from array_start routines.
367 json_count_array_elements(JsonLexContext *lex)
369 JsonLexContext copylex;
373 * It's safe to do this with a shallow copy because the lexical routines
374 * don't scribble on the input. They do scribble on the other pointers
375 * etc, so doing this with a copy makes that safe.
377 memcpy(©lex, lex, sizeof(JsonLexContext));
378 copylex.strval = NULL; /* not interested in values here */
382 lex_expect(JSON_PARSE_ARRAY_START, ©lex, JSON_TOKEN_ARRAY_START);
383 if (lex_peek(©lex) != JSON_TOKEN_ARRAY_END)
388 parse_array_element(©lex, &nullSemAction);
390 while (lex_accept(©lex, JSON_TOKEN_COMMA, NULL));
392 lex_expect(JSON_PARSE_ARRAY_NEXT, ©lex, JSON_TOKEN_ARRAY_END);
398 * Recursive Descent parse routines. There is one for each structural
399 * element in a json document:
400 * - scalar (string, number, true, false, null)
407 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
410 json_scalar_action sfunc = sem->scalar;
412 JsonTokenType tok = lex_peek(lex);
414 valaddr = sfunc == NULL ? NULL : &val;
416 /* a scalar must be a string, a number, true, false, or null */
419 case JSON_TOKEN_TRUE:
420 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
422 case JSON_TOKEN_FALSE:
423 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
425 case JSON_TOKEN_NULL:
426 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
428 case JSON_TOKEN_NUMBER:
429 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
431 case JSON_TOKEN_STRING:
432 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
435 report_parse_error(JSON_PARSE_VALUE, lex);
439 (*sfunc) (sem->semstate, val, tok);
443 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
446 * An object field is "fieldname" : value where value can be a scalar,
447 * object or array. Note: in user-facing docs and error messages, we
448 * generally call a field name a "key".
451 char *fname = NULL; /* keep compiler quiet */
452 json_ofield_action ostart = sem->object_field_start;
453 json_ofield_action oend = sem->object_field_end;
455 char **fnameaddr = NULL;
458 if (ostart != NULL || oend != NULL)
461 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
462 report_parse_error(JSON_PARSE_STRING, lex);
464 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
467 isnull = tok == JSON_TOKEN_NULL;
470 (*ostart) (sem->semstate, fname, isnull);
474 case JSON_TOKEN_OBJECT_START:
475 parse_object(lex, sem);
477 case JSON_TOKEN_ARRAY_START:
478 parse_array(lex, sem);
481 parse_scalar(lex, sem);
485 (*oend) (sem->semstate, fname, isnull);
489 parse_object(JsonLexContext *lex, JsonSemAction *sem)
492 * an object is a possibly empty sequence of object fields, separated by
493 * commas and surrounded by curly braces.
495 json_struct_action ostart = sem->object_start;
496 json_struct_action oend = sem->object_end;
502 (*ostart) (sem->semstate);
505 * Data inside an object is at a higher nesting level than the object
506 * itself. Note that we increment this after we call the semantic routine
507 * for the object start and restore it before we call the routine for the
512 /* we know this will succeed, just clearing the token */
513 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
518 case JSON_TOKEN_STRING:
519 parse_object_field(lex, sem);
520 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
521 parse_object_field(lex, sem);
523 case JSON_TOKEN_OBJECT_END:
526 /* case of an invalid initial token inside the object */
527 report_parse_error(JSON_PARSE_OBJECT_START, lex);
530 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
535 (*oend) (sem->semstate);
539 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
541 json_aelem_action astart = sem->array_element_start;
542 json_aelem_action aend = sem->array_element_end;
543 JsonTokenType tok = lex_peek(lex);
547 isnull = tok == JSON_TOKEN_NULL;
550 (*astart) (sem->semstate, isnull);
552 /* an array element is any object, array or scalar */
555 case JSON_TOKEN_OBJECT_START:
556 parse_object(lex, sem);
558 case JSON_TOKEN_ARRAY_START:
559 parse_array(lex, sem);
562 parse_scalar(lex, sem);
566 (*aend) (sem->semstate, isnull);
570 parse_array(JsonLexContext *lex, JsonSemAction *sem)
573 * an array is a possibly empty sequence of array elements, separated by
574 * commas and surrounded by square brackets.
576 json_struct_action astart = sem->array_start;
577 json_struct_action aend = sem->array_end;
582 (*astart) (sem->semstate);
585 * Data inside an array is at a higher nesting level than the array
586 * itself. Note that we increment this after we call the semantic routine
587 * for the array start and restore it before we call the routine for the
592 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
593 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
596 parse_array_element(lex, sem);
598 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
599 parse_array_element(lex, sem);
602 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
607 (*aend) (sem->semstate);
611 * Lex one token from the input stream.
614 json_lex(JsonLexContext *lex)
619 /* Skip leading whitespace. */
620 s = lex->token_terminator;
621 len = s - lex->input;
622 while (len < lex->input_length &&
623 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
630 lex->token_start = s;
632 /* Determine token type. */
633 if (len >= lex->input_length)
635 lex->token_start = NULL;
636 lex->prev_token_terminator = lex->token_terminator;
637 lex->token_terminator = s;
638 lex->token_type = JSON_TOKEN_END;
643 /* Single-character token, some kind of punctuation mark. */
645 lex->prev_token_terminator = lex->token_terminator;
646 lex->token_terminator = s + 1;
647 lex->token_type = JSON_TOKEN_OBJECT_START;
650 lex->prev_token_terminator = lex->token_terminator;
651 lex->token_terminator = s + 1;
652 lex->token_type = JSON_TOKEN_OBJECT_END;
655 lex->prev_token_terminator = lex->token_terminator;
656 lex->token_terminator = s + 1;
657 lex->token_type = JSON_TOKEN_ARRAY_START;
660 lex->prev_token_terminator = lex->token_terminator;
661 lex->token_terminator = s + 1;
662 lex->token_type = JSON_TOKEN_ARRAY_END;
665 lex->prev_token_terminator = lex->token_terminator;
666 lex->token_terminator = s + 1;
667 lex->token_type = JSON_TOKEN_COMMA;
670 lex->prev_token_terminator = lex->token_terminator;
671 lex->token_terminator = s + 1;
672 lex->token_type = JSON_TOKEN_COLON;
676 json_lex_string(lex);
677 lex->token_type = JSON_TOKEN_STRING;
680 /* Negative number. */
681 json_lex_number(lex, s + 1, NULL, NULL);
682 lex->token_type = JSON_TOKEN_NUMBER;
694 /* Positive number. */
695 json_lex_number(lex, s, NULL, NULL);
696 lex->token_type = JSON_TOKEN_NUMBER;
703 * We're not dealing with a string, number, legal
704 * punctuation mark, or end of string. The only legal
705 * tokens we might find here are true, false, and null,
706 * but for error reporting purposes we scan until we see a
707 * non-alphanumeric character. That way, we can report
708 * the whole word as an unexpected token, rather than just
709 * some unintuitive prefix thereof.
711 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
715 * We got some sort of unexpected punctuation or an
716 * otherwise unexpected character, so just complain about
717 * that one character.
721 lex->prev_token_terminator = lex->token_terminator;
722 lex->token_terminator = s + 1;
723 report_invalid_token(lex);
727 * We've got a real alphanumeric token here. If it
728 * happens to be true, false, or null, all is well. If
731 lex->prev_token_terminator = lex->token_terminator;
732 lex->token_terminator = p;
735 if (memcmp(s, "true", 4) == 0)
736 lex->token_type = JSON_TOKEN_TRUE;
737 else if (memcmp(s, "null", 4) == 0)
738 lex->token_type = JSON_TOKEN_NULL;
740 report_invalid_token(lex);
742 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
743 lex->token_type = JSON_TOKEN_FALSE;
745 report_invalid_token(lex);
748 } /* end of switch */
752 * The next token in the input stream is known to be a string; lex it.
755 json_lex_string(JsonLexContext *lex)
759 int hi_surrogate = -1;
761 if (lex->strval != NULL)
762 resetStringInfo(lex->strval);
764 Assert(lex->input_length > 0);
765 s = lex->token_start;
766 len = lex->token_start - lex->input;
771 /* Premature end of the string. */
772 if (len >= lex->input_length)
774 lex->token_terminator = s;
775 report_invalid_token(lex);
779 else if ((unsigned char) *s < 32)
781 /* Per RFC4627, these characters MUST be escaped. */
782 /* Since *s isn't printable, exclude it from the context string */
783 lex->token_terminator = s;
785 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
786 errmsg("invalid input syntax for type %s", "json"),
787 errdetail("Character with value 0x%02x must be escaped.",
789 report_json_context(lex)));
793 /* OK, we have an escape character. */
796 if (len >= lex->input_length)
798 lex->token_terminator = s;
799 report_invalid_token(lex);
806 for (i = 1; i <= 4; i++)
810 if (len >= lex->input_length)
812 lex->token_terminator = s;
813 report_invalid_token(lex);
815 else if (*s >= '0' && *s <= '9')
816 ch = (ch * 16) + (*s - '0');
817 else if (*s >= 'a' && *s <= 'f')
818 ch = (ch * 16) + (*s - 'a') + 10;
819 else if (*s >= 'A' && *s <= 'F')
820 ch = (ch * 16) + (*s - 'A') + 10;
823 lex->token_terminator = s + pg_mblen(s);
825 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
826 errmsg("invalid input syntax for type %s",
828 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
829 report_json_context(lex)));
832 if (lex->strval != NULL)
837 if (ch >= 0xd800 && ch <= 0xdbff)
839 if (hi_surrogate != -1)
841 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
842 errmsg("invalid input syntax for type %s",
844 errdetail("Unicode high surrogate must not follow a high surrogate."),
845 report_json_context(lex)));
846 hi_surrogate = (ch & 0x3ff) << 10;
849 else if (ch >= 0xdc00 && ch <= 0xdfff)
851 if (hi_surrogate == -1)
853 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
854 errmsg("invalid input syntax for type %s", "json"),
855 errdetail("Unicode low surrogate must follow a high surrogate."),
856 report_json_context(lex)));
857 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
861 if (hi_surrogate != -1)
863 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
864 errmsg("invalid input syntax for type %s", "json"),
865 errdetail("Unicode low surrogate must follow a high surrogate."),
866 report_json_context(lex)));
869 * For UTF8, replace the escape sequence by the actual
870 * utf8 character in lex->strval. Do this also for other
871 * encodings if the escape designates an ASCII character,
872 * otherwise raise an error.
877 /* We can't allow this, since our TEXT type doesn't */
879 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
880 errmsg("unsupported Unicode escape sequence"),
881 errdetail("\\u0000 cannot be converted to text."),
882 report_json_context(lex)));
884 else if (GetDatabaseEncoding() == PG_UTF8)
886 unicode_to_utf8(ch, (unsigned char *) utf8str);
887 utf8len = pg_utf_mblen((unsigned char *) utf8str);
888 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
890 else if (ch <= 0x007f)
893 * This is the only way to designate things like a
894 * form feed character in JSON, so it's useful in all
897 appendStringInfoChar(lex->strval, (char) ch);
902 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
903 errmsg("unsupported Unicode escape sequence"),
904 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
905 report_json_context(lex)));
910 else if (lex->strval != NULL)
912 if (hi_surrogate != -1)
914 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
915 errmsg("invalid input syntax for type %s",
917 errdetail("Unicode low surrogate must follow a high surrogate."),
918 report_json_context(lex)));
925 appendStringInfoChar(lex->strval, *s);
928 appendStringInfoChar(lex->strval, '\b');
931 appendStringInfoChar(lex->strval, '\f');
934 appendStringInfoChar(lex->strval, '\n');
937 appendStringInfoChar(lex->strval, '\r');
940 appendStringInfoChar(lex->strval, '\t');
943 /* Not a valid string escape, so error out. */
944 lex->token_terminator = s + pg_mblen(s);
946 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
947 errmsg("invalid input syntax for type %s",
949 errdetail("Escape sequence \"\\%s\" is invalid.",
951 report_json_context(lex)));
954 else if (strchr("\"\\/bfnrt", *s) == NULL)
957 * Simpler processing if we're not bothered about de-escaping
959 * It's very tempting to remove the strchr() call here and
960 * replace it with a switch statement, but testing so far has
961 * shown it's not a performance win.
963 lex->token_terminator = s + pg_mblen(s);
965 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
966 errmsg("invalid input syntax for type %s", "json"),
967 errdetail("Escape sequence \"\\%s\" is invalid.",
969 report_json_context(lex)));
973 else if (lex->strval != NULL)
975 if (hi_surrogate != -1)
977 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
978 errmsg("invalid input syntax for type %s", "json"),
979 errdetail("Unicode low surrogate must follow a high surrogate."),
980 report_json_context(lex)));
982 appendStringInfoChar(lex->strval, *s);
987 if (hi_surrogate != -1)
989 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
990 errmsg("invalid input syntax for type %s", "json"),
991 errdetail("Unicode low surrogate must follow a high surrogate."),
992 report_json_context(lex)));
994 /* Hooray, we found the end of the string! */
995 lex->prev_token_terminator = lex->token_terminator;
996 lex->token_terminator = s + 1;
1000 * The next token in the input stream is known to be a number; lex it.
1002 * In JSON, a number consists of four parts:
1004 * (1) An optional minus sign ('-').
1006 * (2) Either a single '0', or a string of one or more digits that does not
1009 * (3) An optional decimal part, consisting of a period ('.') followed by
1010 * one or more digits. (Note: While this part can be omitted
1011 * completely, it's not OK to have only the decimal point without
1012 * any digits afterwards.)
1014 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
1015 * followed by '+' or '-', followed by one or more digits. (Note:
1016 * As with the decimal part, if 'e' or 'E' is present, it must be
1017 * followed by at least one digit.)
1019 * The 's' argument to this function points to the ostensible beginning
1020 * of part 2 - i.e. the character after any optional minus sign, or the
1021 * first character of the string if there is none.
1023 * If num_err is not NULL, we return an error flag to *num_err rather than
1024 * raising an error for a badly-formed number. Also, if total_len is not NULL
1025 * the distance from lex->input to the token end+1 is returned to *total_len.
1028 json_lex_number(JsonLexContext *lex, char *s,
1029 bool *num_err, int *total_len)
1032 int len = s - lex->input;
1034 /* Part (1): leading sign indicator. */
1035 /* Caller already did this for us; so do nothing. */
1037 /* Part (2): parse main digit string. */
1038 if (len < lex->input_length && *s == '0')
1043 else if (len < lex->input_length && *s >= '1' && *s <= '9')
1049 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1054 /* Part (3): parse optional decimal portion. */
1055 if (len < lex->input_length && *s == '.')
1059 if (len == lex->input_length || *s < '0' || *s > '9')
1067 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1071 /* Part (4): parse optional exponent. */
1072 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
1076 if (len < lex->input_length && (*s == '+' || *s == '-'))
1081 if (len == lex->input_length || *s < '0' || *s > '9')
1089 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1094 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
1095 * here should be considered part of the token for error-reporting
1098 for (; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*s); s++, len++)
1101 if (total_len != NULL)
1104 if (num_err != NULL)
1106 /* let the caller handle any error */
1111 /* return token endpoint */
1112 lex->prev_token_terminator = lex->token_terminator;
1113 lex->token_terminator = s;
1114 /* handle error if any */
1116 report_invalid_token(lex);
1121 * Report a parse error.
1123 * lex->token_start and lex->token_terminator must identify the current token.
1126 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1131 /* Handle case where the input ended prematurely. */
1132 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1134 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1135 errmsg("invalid input syntax for type %s", "json"),
1136 errdetail("The input string ended unexpectedly."),
1137 report_json_context(lex)));
1139 /* Separate out the current token. */
1140 toklen = lex->token_terminator - lex->token_start;
1141 token = palloc(toklen + 1);
1142 memcpy(token, lex->token_start, toklen);
1143 token[toklen] = '\0';
1145 /* Complain, with the appropriate detail message. */
1146 if (ctx == JSON_PARSE_END)
1148 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1149 errmsg("invalid input syntax for type %s", "json"),
1150 errdetail("Expected end of input, but found \"%s\".",
1152 report_json_context(lex)));
1157 case JSON_PARSE_VALUE:
1159 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1160 errmsg("invalid input syntax for type %s", "json"),
1161 errdetail("Expected JSON value, but found \"%s\".",
1163 report_json_context(lex)));
1165 case JSON_PARSE_STRING:
1167 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1168 errmsg("invalid input syntax for type %s", "json"),
1169 errdetail("Expected string, but found \"%s\".",
1171 report_json_context(lex)));
1173 case JSON_PARSE_ARRAY_START:
1175 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1176 errmsg("invalid input syntax for type %s", "json"),
1177 errdetail("Expected array element or \"]\", but found \"%s\".",
1179 report_json_context(lex)));
1181 case JSON_PARSE_ARRAY_NEXT:
1183 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1184 errmsg("invalid input syntax for type %s", "json"),
1185 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1187 report_json_context(lex)));
1189 case JSON_PARSE_OBJECT_START:
1191 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1192 errmsg("invalid input syntax for type %s", "json"),
1193 errdetail("Expected string or \"}\", but found \"%s\".",
1195 report_json_context(lex)));
1197 case JSON_PARSE_OBJECT_LABEL:
1199 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1200 errmsg("invalid input syntax for type %s", "json"),
1201 errdetail("Expected \":\", but found \"%s\".",
1203 report_json_context(lex)));
1205 case JSON_PARSE_OBJECT_NEXT:
1207 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1208 errmsg("invalid input syntax for type %s", "json"),
1209 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1211 report_json_context(lex)));
1213 case JSON_PARSE_OBJECT_COMMA:
1215 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1216 errmsg("invalid input syntax for type %s", "json"),
1217 errdetail("Expected string, but found \"%s\".",
1219 report_json_context(lex)));
1222 elog(ERROR, "unexpected json parse state: %d", ctx);
1228 * Report an invalid input token.
1230 * lex->token_start and lex->token_terminator must identify the token.
1233 report_invalid_token(JsonLexContext *lex)
1238 /* Separate out the offending token. */
1239 toklen = lex->token_terminator - lex->token_start;
1240 token = palloc(toklen + 1);
1241 memcpy(token, lex->token_start, toklen);
1242 token[toklen] = '\0';
1245 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1246 errmsg("invalid input syntax for type %s", "json"),
1247 errdetail("Token \"%s\" is invalid.", token),
1248 report_json_context(lex)));
1252 * Report a CONTEXT line for bogus JSON input.
1254 * lex->token_terminator must be set to identify the spot where we detected
1255 * the error. Note that lex->token_start might be NULL, in case we recognized
1258 * The return value isn't meaningful, but we make it non-void so that this
1259 * can be invoked inside ereport().
1262 report_json_context(JsonLexContext *lex)
1264 const char *context_start;
1265 const char *context_end;
1266 const char *line_start;
1273 /* Choose boundaries for the part of the input we will display */
1274 context_start = lex->input;
1275 context_end = lex->token_terminator;
1276 line_start = context_start;
1280 /* Always advance over newlines */
1281 if (context_start < context_end && *context_start == '\n')
1284 line_start = context_start;
1288 /* Otherwise, done as soon as we are close enough to context_end */
1289 if (context_end - context_start < 50)
1291 /* Advance to next multibyte character */
1292 if (IS_HIGHBIT_SET(*context_start))
1293 context_start += pg_mblen(context_start);
1299 * We add "..." to indicate that the excerpt doesn't start at the
1300 * beginning of the line ... but if we're within 3 characters of the
1301 * beginning of the line, we might as well just show the whole line.
1303 if (context_start - line_start <= 3)
1304 context_start = line_start;
1306 /* Get a null-terminated copy of the data to present */
1307 ctxtlen = context_end - context_start;
1308 ctxt = palloc(ctxtlen + 1);
1309 memcpy(ctxt, context_start, ctxtlen);
1310 ctxt[ctxtlen] = '\0';
1313 * Show the context, prefixing "..." if not starting at start of line, and
1314 * suffixing "..." if not ending at end of line.
1316 prefix = (context_start > line_start) ? "..." : "";
1317 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1319 return errcontext("JSON data, line %d: %s%s%s",
1320 line_number, prefix, ctxt, suffix);
1324 * Extract a single, possibly multi-byte char from the input string.
1327 extract_mb_char(char *s)
1333 res = palloc(len + 1);
1334 memcpy(res, s, len);
1341 * Determine how we want to print values of a given type in datum_to_json.
1343 * Given the datatype OID, return its JsonTypeCategory, as well as the type's
1344 * output function OID. If the returned category is JSONTYPE_CAST, we
1345 * return the OID of the type->JSON cast function instead.
1348 json_categorize_type(Oid typoid,
1349 JsonTypeCategory *tcategory,
1354 /* Look through any domain */
1355 typoid = getBaseType(typoid);
1357 *outfuncoid = InvalidOid;
1360 * We need to get the output function for everything except date and
1361 * timestamp types, array and composite types, booleans, and non-builtin
1362 * types where there's a cast to json.
1368 *tcategory = JSONTYPE_BOOL;
1377 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1378 *tcategory = JSONTYPE_NUMERIC;
1382 *tcategory = JSONTYPE_DATE;
1386 *tcategory = JSONTYPE_TIMESTAMP;
1389 case TIMESTAMPTZOID:
1390 *tcategory = JSONTYPE_TIMESTAMPTZ;
1395 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1396 *tcategory = JSONTYPE_JSON;
1400 /* Check for arrays and composites */
1401 if (OidIsValid(get_element_type(typoid)) || typoid == ANYARRAYOID
1402 || typoid == RECORDARRAYOID)
1403 *tcategory = JSONTYPE_ARRAY;
1404 else if (type_is_rowtype(typoid)) /* includes RECORDOID */
1405 *tcategory = JSONTYPE_COMPOSITE;
1408 /* It's probably the general case ... */
1409 *tcategory = JSONTYPE_OTHER;
1410 /* but let's look for a cast to json, if it's not built-in */
1411 if (typoid >= FirstNormalObjectId)
1414 CoercionPathType ctype;
1416 ctype = find_coercion_pathway(JSONOID, typoid,
1419 if (ctype == COERCION_PATH_FUNC && OidIsValid(castfunc))
1421 *tcategory = JSONTYPE_CAST;
1422 *outfuncoid = castfunc;
1426 /* non builtin type with no cast */
1427 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1432 /* any other builtin type */
1433 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1441 * Turn a Datum into JSON text, appending the string to "result".
1443 * tcategory and outfuncoid are from a previous call to json_categorize_type,
1444 * except that if is_null is true then they can be invalid.
1446 * If key_scalar is true, the value is being printed as a key, so insist
1447 * it's of an acceptable type, and force it to be quoted.
1450 datum_to_json(Datum val, bool is_null, StringInfo result,
1451 JsonTypeCategory tcategory, Oid outfuncoid,
1457 check_stack_depth();
1459 /* callers are expected to ensure that null keys are not passed in */
1460 Assert(!(key_scalar && is_null));
1464 appendStringInfoString(result, "null");
1469 (tcategory == JSONTYPE_ARRAY ||
1470 tcategory == JSONTYPE_COMPOSITE ||
1471 tcategory == JSONTYPE_JSON ||
1472 tcategory == JSONTYPE_CAST))
1474 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1475 errmsg("key value must be scalar, not array, composite, or json")));
1479 case JSONTYPE_ARRAY:
1480 array_to_json_internal(val, result, false);
1482 case JSONTYPE_COMPOSITE:
1483 composite_to_json(val, result, false);
1486 outputstr = DatumGetBool(val) ? "true" : "false";
1488 escape_json(result, outputstr);
1490 appendStringInfoString(result, outputstr);
1492 case JSONTYPE_NUMERIC:
1493 outputstr = OidOutputFunctionCall(outfuncoid, val);
1496 * Don't call escape_json for a non-key if it's a valid JSON
1499 if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
1500 appendStringInfoString(result, outputstr);
1502 escape_json(result, outputstr);
1507 char buf[MAXDATELEN + 1];
1509 JsonEncodeDateTime(buf, val, DATEOID);
1510 appendStringInfo(result, "\"%s\"", buf);
1513 case JSONTYPE_TIMESTAMP:
1515 char buf[MAXDATELEN + 1];
1517 JsonEncodeDateTime(buf, val, TIMESTAMPOID);
1518 appendStringInfo(result, "\"%s\"", buf);
1521 case JSONTYPE_TIMESTAMPTZ:
1523 char buf[MAXDATELEN + 1];
1525 JsonEncodeDateTime(buf, val, TIMESTAMPTZOID);
1526 appendStringInfo(result, "\"%s\"", buf);
1530 /* JSON and JSONB output will already be escaped */
1531 outputstr = OidOutputFunctionCall(outfuncoid, val);
1532 appendStringInfoString(result, outputstr);
1536 /* outfuncoid refers to a cast function, not an output function */
1537 jsontext = DatumGetTextPP(OidFunctionCall1(outfuncoid, val));
1538 outputstr = text_to_cstring(jsontext);
1539 appendStringInfoString(result, outputstr);
1544 outputstr = OidOutputFunctionCall(outfuncoid, val);
1545 escape_json(result, outputstr);
1552 * Encode 'value' of datetime type 'typid' into JSON string in ISO format using
1553 * optionally preallocated buffer 'buf'.
1556 JsonEncodeDateTime(char *buf, Datum value, Oid typid)
1559 buf = palloc(MAXDATELEN + 1);
1568 date = DatumGetDateADT(value);
1570 /* Same as date_out(), but forcing DateStyle */
1571 if (DATE_NOT_FINITE(date))
1572 EncodeSpecialDate(date, buf);
1575 j2date(date + POSTGRES_EPOCH_JDATE,
1576 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1577 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1583 TimeADT time = DatumGetTimeADT(value);
1588 /* Same as time_out(), but forcing DateStyle */
1589 time2tm(time, tm, &fsec);
1590 EncodeTimeOnly(tm, fsec, false, 0, USE_XSD_DATES, buf);
1595 TimeTzADT *time = DatumGetTimeTzADTP(value);
1601 /* Same as timetz_out(), but forcing DateStyle */
1602 timetz2tm(time, tm, &fsec, &tz);
1603 EncodeTimeOnly(tm, fsec, true, tz, USE_XSD_DATES, buf);
1608 Timestamp timestamp;
1612 timestamp = DatumGetTimestamp(value);
1613 /* Same as timestamp_out(), but forcing DateStyle */
1614 if (TIMESTAMP_NOT_FINITE(timestamp))
1615 EncodeSpecialTimestamp(timestamp, buf);
1616 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1617 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
1620 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1621 errmsg("timestamp out of range")));
1624 case TIMESTAMPTZOID:
1626 TimestampTz timestamp;
1630 const char *tzn = NULL;
1632 timestamp = DatumGetTimestampTz(value);
1633 /* Same as timestamptz_out(), but forcing DateStyle */
1634 if (TIMESTAMP_NOT_FINITE(timestamp))
1635 EncodeSpecialTimestamp(timestamp, buf);
1636 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1637 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
1640 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1641 errmsg("timestamp out of range")));
1645 elog(ERROR, "unknown jsonb value datetime type oid %d", typid);
1653 * Process a single dimension of an array.
1654 * If it's the innermost dimension, output the values, otherwise call
1655 * ourselves recursively to process the next dimension.
1658 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1659 bool *nulls, int *valcount, JsonTypeCategory tcategory,
1660 Oid outfuncoid, bool use_line_feeds)
1665 Assert(dim < ndims);
1667 sep = use_line_feeds ? ",\n " : ",";
1669 appendStringInfoChar(result, '[');
1671 for (i = 1; i <= dims[dim]; i++)
1674 appendStringInfoString(result, sep);
1676 if (dim + 1 == ndims)
1678 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1685 * Do we want line feeds on inner dimensions of arrays? For now
1688 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1689 valcount, tcategory, outfuncoid, false);
1693 appendStringInfoChar(result, ']');
1697 * Turn an array into JSON.
1700 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1702 ArrayType *v = DatumGetArrayTypeP(array);
1703 Oid element_type = ARR_ELEMTYPE(v);
1713 JsonTypeCategory tcategory;
1718 nitems = ArrayGetNItems(ndim, dim);
1722 appendStringInfoString(result, "[]");
1726 get_typlenbyvalalign(element_type,
1727 &typlen, &typbyval, &typalign);
1729 json_categorize_type(element_type,
1730 &tcategory, &outfuncoid);
1732 deconstruct_array(v, element_type, typlen, typbyval,
1733 typalign, &elements, &nulls,
1736 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1737 outfuncoid, use_line_feeds);
1744 * Turn a composite / record into JSON.
1747 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1753 HeapTupleData tmptup,
1756 bool needsep = false;
1759 sep = use_line_feeds ? ",\n " : ",";
1761 td = DatumGetHeapTupleHeader(composite);
1763 /* Extract rowtype info and find a tupdesc */
1764 tupType = HeapTupleHeaderGetTypeId(td);
1765 tupTypmod = HeapTupleHeaderGetTypMod(td);
1766 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1768 /* Build a temporary HeapTuple control structure */
1769 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1773 appendStringInfoChar(result, '{');
1775 for (i = 0; i < tupdesc->natts; i++)
1780 JsonTypeCategory tcategory;
1782 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1784 if (att->attisdropped)
1788 appendStringInfoString(result, sep);
1791 attname = NameStr(att->attname);
1792 escape_json(result, attname);
1793 appendStringInfoChar(result, ':');
1795 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1799 tcategory = JSONTYPE_NULL;
1800 outfuncoid = InvalidOid;
1803 json_categorize_type(att->atttypid, &tcategory, &outfuncoid);
1805 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1808 appendStringInfoChar(result, '}');
1809 ReleaseTupleDesc(tupdesc);
1813 * Append JSON text for "val" to "result".
1815 * This is just a thin wrapper around datum_to_json. If the same type will be
1816 * printed many times, avoid using this; better to do the json_categorize_type
1817 * lookups only once.
1820 add_json(Datum val, bool is_null, StringInfo result,
1821 Oid val_type, bool key_scalar)
1823 JsonTypeCategory tcategory;
1826 if (val_type == InvalidOid)
1828 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1829 errmsg("could not determine input data type")));
1833 tcategory = JSONTYPE_NULL;
1834 outfuncoid = InvalidOid;
1837 json_categorize_type(val_type,
1838 &tcategory, &outfuncoid);
1840 datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1844 * SQL function array_to_json(row)
1847 array_to_json(PG_FUNCTION_ARGS)
1849 Datum array = PG_GETARG_DATUM(0);
1852 result = makeStringInfo();
1854 array_to_json_internal(array, result, false);
1856 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1860 * SQL function array_to_json(row, prettybool)
1863 array_to_json_pretty(PG_FUNCTION_ARGS)
1865 Datum array = PG_GETARG_DATUM(0);
1866 bool use_line_feeds = PG_GETARG_BOOL(1);
1869 result = makeStringInfo();
1871 array_to_json_internal(array, result, use_line_feeds);
1873 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1877 * SQL function row_to_json(row)
1880 row_to_json(PG_FUNCTION_ARGS)
1882 Datum array = PG_GETARG_DATUM(0);
1885 result = makeStringInfo();
1887 composite_to_json(array, result, false);
1889 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1893 * SQL function row_to_json(row, prettybool)
1896 row_to_json_pretty(PG_FUNCTION_ARGS)
1898 Datum array = PG_GETARG_DATUM(0);
1899 bool use_line_feeds = PG_GETARG_BOOL(1);
1902 result = makeStringInfo();
1904 composite_to_json(array, result, use_line_feeds);
1906 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1910 * SQL function to_json(anyvalue)
1913 to_json(PG_FUNCTION_ARGS)
1915 Datum val = PG_GETARG_DATUM(0);
1916 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1918 JsonTypeCategory tcategory;
1921 if (val_type == InvalidOid)
1923 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1924 errmsg("could not determine input data type")));
1926 json_categorize_type(val_type,
1927 &tcategory, &outfuncoid);
1929 result = makeStringInfo();
1931 datum_to_json(val, false, result, tcategory, outfuncoid, false);
1933 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1937 * json_agg transition function
1939 * aggregate input column as a json array value.
1942 json_agg_transfn(PG_FUNCTION_ARGS)
1944 MemoryContext aggcontext,
1946 JsonAggState *state;
1949 if (!AggCheckCallContext(fcinfo, &aggcontext))
1951 /* cannot be called directly because of internal-type argument */
1952 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1955 if (PG_ARGISNULL(0))
1957 Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1959 if (arg_type == InvalidOid)
1961 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1962 errmsg("could not determine input data type")));
1965 * Make this state object in a context where it will persist for the
1966 * duration of the aggregate call. MemoryContextSwitchTo is only
1967 * needed the first time, as the StringInfo routines make sure they
1968 * use the right context to enlarge the object if necessary.
1970 oldcontext = MemoryContextSwitchTo(aggcontext);
1971 state = (JsonAggState *) palloc(sizeof(JsonAggState));
1972 state->str = makeStringInfo();
1973 MemoryContextSwitchTo(oldcontext);
1975 appendStringInfoChar(state->str, '[');
1976 json_categorize_type(arg_type, &state->val_category,
1977 &state->val_output_func);
1981 state = (JsonAggState *) PG_GETARG_POINTER(0);
1982 appendStringInfoString(state->str, ", ");
1985 /* fast path for NULLs */
1986 if (PG_ARGISNULL(1))
1988 datum_to_json((Datum) 0, true, state->str, JSONTYPE_NULL,
1990 PG_RETURN_POINTER(state);
1993 val = PG_GETARG_DATUM(1);
1995 /* add some whitespace if structured type and not first item */
1996 if (!PG_ARGISNULL(0) &&
1997 (state->val_category == JSONTYPE_ARRAY ||
1998 state->val_category == JSONTYPE_COMPOSITE))
2000 appendStringInfoString(state->str, "\n ");
2003 datum_to_json(val, false, state->str, state->val_category,
2004 state->val_output_func, false);
2007 * The transition type for json_agg() is declared to be "internal", which
2008 * is a pass-by-value type the same size as a pointer. So we can safely
2009 * pass the JsonAggState pointer through nodeAgg.c's machinations.
2011 PG_RETURN_POINTER(state);
2015 * json_agg final function
2018 json_agg_finalfn(PG_FUNCTION_ARGS)
2020 JsonAggState *state;
2022 /* cannot be called directly because of internal-type argument */
2023 Assert(AggCheckCallContext(fcinfo, NULL));
2025 state = PG_ARGISNULL(0) ?
2027 (JsonAggState *) PG_GETARG_POINTER(0);
2029 /* NULL result for no rows in, as is standard with aggregates */
2033 /* Else return state with appropriate array terminator added */
2034 PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, "]"));
2038 * json_object_agg transition function.
2040 * aggregate two input columns as a single json object value.
2043 json_object_agg_transfn(PG_FUNCTION_ARGS)
2045 MemoryContext aggcontext,
2047 JsonAggState *state;
2050 if (!AggCheckCallContext(fcinfo, &aggcontext))
2052 /* cannot be called directly because of internal-type argument */
2053 elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
2056 if (PG_ARGISNULL(0))
2061 * Make the StringInfo in a context where it will persist for the
2062 * duration of the aggregate call. Switching context is only needed
2063 * for this initial step, as the StringInfo routines make sure they
2064 * use the right context to enlarge the object if necessary.
2066 oldcontext = MemoryContextSwitchTo(aggcontext);
2067 state = (JsonAggState *) palloc(sizeof(JsonAggState));
2068 state->str = makeStringInfo();
2069 MemoryContextSwitchTo(oldcontext);
2071 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
2073 if (arg_type == InvalidOid)
2075 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2076 errmsg("could not determine data type for argument %d", 1)));
2078 json_categorize_type(arg_type, &state->key_category,
2079 &state->key_output_func);
2081 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
2083 if (arg_type == InvalidOid)
2085 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2086 errmsg("could not determine data type for argument %d", 2)));
2088 json_categorize_type(arg_type, &state->val_category,
2089 &state->val_output_func);
2091 appendStringInfoString(state->str, "{ ");
2095 state = (JsonAggState *) PG_GETARG_POINTER(0);
2096 appendStringInfoString(state->str, ", ");
2100 * Note: since json_object_agg() is declared as taking type "any", the
2101 * parser will not do any type conversion on unknown-type literals (that
2102 * is, undecorated strings or NULLs). Such values will arrive here as
2103 * type UNKNOWN, which fortunately does not matter to us, since
2104 * unknownout() works fine.
2107 if (PG_ARGISNULL(1))
2109 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2110 errmsg("field name must not be null")));
2112 arg = PG_GETARG_DATUM(1);
2114 datum_to_json(arg, false, state->str, state->key_category,
2115 state->key_output_func, true);
2117 appendStringInfoString(state->str, " : ");
2119 if (PG_ARGISNULL(2))
2122 arg = PG_GETARG_DATUM(2);
2124 datum_to_json(arg, PG_ARGISNULL(2), state->str, state->val_category,
2125 state->val_output_func, false);
2127 PG_RETURN_POINTER(state);
2131 * json_object_agg final function.
2134 json_object_agg_finalfn(PG_FUNCTION_ARGS)
2136 JsonAggState *state;
2138 /* cannot be called directly because of internal-type argument */
2139 Assert(AggCheckCallContext(fcinfo, NULL));
2141 state = PG_ARGISNULL(0) ? NULL : (JsonAggState *) PG_GETARG_POINTER(0);
2143 /* NULL result for no rows in, as is standard with aggregates */
2147 /* Else return state with appropriate object terminator added */
2148 PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, " }"));
2152 * Helper function for aggregates: return given StringInfo's contents plus
2153 * specified trailing string, as a text datum. We need this because aggregate
2154 * final functions are not allowed to modify the aggregate state.
2157 catenate_stringinfo_string(StringInfo buffer, const char *addon)
2159 /* custom version of cstring_to_text_with_len */
2160 int buflen = buffer->len;
2161 int addlen = strlen(addon);
2162 text *result = (text *) palloc(buflen + addlen + VARHDRSZ);
2164 SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
2165 memcpy(VARDATA(result), buffer->data, buflen);
2166 memcpy(VARDATA(result) + buflen, addon, addlen);
2172 * SQL function json_build_object(variadic "any")
2175 json_build_object(PG_FUNCTION_ARGS)
2177 int nargs = PG_NARGS();
2179 const char *sep = "";
2185 /* fetch argument values to build the object */
2186 nargs = extract_variadic_args(fcinfo, 0, false, &args, &types, &nulls);
2193 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2194 errmsg("argument list must have even number of elements"),
2195 /* translator: %s is a SQL function name */
2196 errhint("The arguments of %s must consist of alternating keys and values.",
2197 "json_build_object()")));
2199 result = makeStringInfo();
2201 appendStringInfoChar(result, '{');
2203 for (i = 0; i < nargs; i += 2)
2205 appendStringInfoString(result, sep);
2211 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2212 errmsg("argument %d cannot be null", i + 1),
2213 errhint("Object keys should be text.")));
2215 add_json(args[i], false, result, types[i], true);
2217 appendStringInfoString(result, " : ");
2220 add_json(args[i + 1], nulls[i + 1], result, types[i + 1], false);
2223 appendStringInfoChar(result, '}');
2225 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2229 * degenerate case of json_build_object where it gets 0 arguments.
2232 json_build_object_noargs(PG_FUNCTION_ARGS)
2234 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2238 * SQL function json_build_array(variadic "any")
2241 json_build_array(PG_FUNCTION_ARGS)
2245 const char *sep = "";
2251 /* fetch argument values to build the array */
2252 nargs = extract_variadic_args(fcinfo, 0, false, &args, &types, &nulls);
2257 result = makeStringInfo();
2259 appendStringInfoChar(result, '[');
2261 for (i = 0; i < nargs; i++)
2263 appendStringInfoString(result, sep);
2265 add_json(args[i], nulls[i], result, types[i], false);
2268 appendStringInfoChar(result, ']');
2270 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2274 * degenerate case of json_build_array where it gets 0 arguments.
2277 json_build_array_noargs(PG_FUNCTION_ARGS)
2279 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2283 * SQL function json_object(text[])
2285 * take a one or two dimensional array of text as key/value pairs
2286 * for a json object.
2289 json_object(PG_FUNCTION_ARGS)
2291 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2292 int ndims = ARR_NDIM(in_array);
2293 StringInfoData result;
2305 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2309 if ((ARR_DIMS(in_array)[0]) % 2)
2311 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2312 errmsg("array must have even number of elements")));
2316 if ((ARR_DIMS(in_array)[1]) != 2)
2318 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2319 errmsg("array must have two columns")));
2324 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2325 errmsg("wrong number of array subscripts")));
2328 deconstruct_array(in_array,
2329 TEXTOID, -1, false, 'i',
2330 &in_datums, &in_nulls, &in_count);
2332 count = in_count / 2;
2334 initStringInfo(&result);
2336 appendStringInfoChar(&result, '{');
2338 for (i = 0; i < count; ++i)
2340 if (in_nulls[i * 2])
2342 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2343 errmsg("null value not allowed for object key")));
2345 v = TextDatumGetCString(in_datums[i * 2]);
2347 appendStringInfoString(&result, ", ");
2348 escape_json(&result, v);
2349 appendStringInfoString(&result, " : ");
2351 if (in_nulls[i * 2 + 1])
2352 appendStringInfoString(&result, "null");
2355 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2356 escape_json(&result, v);
2361 appendStringInfoChar(&result, '}');
2366 rval = cstring_to_text_with_len(result.data, result.len);
2369 PG_RETURN_TEXT_P(rval);
2374 * SQL function json_object(text[], text[])
2376 * take separate key and value arrays of text to construct a json object
2380 json_object_two_arg(PG_FUNCTION_ARGS)
2382 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2383 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2384 int nkdims = ARR_NDIM(key_array);
2385 int nvdims = ARR_NDIM(val_array);
2386 StringInfoData result;
2397 if (nkdims > 1 || nkdims != nvdims)
2399 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2400 errmsg("wrong number of array subscripts")));
2403 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2405 deconstruct_array(key_array,
2406 TEXTOID, -1, false, 'i',
2407 &key_datums, &key_nulls, &key_count);
2409 deconstruct_array(val_array,
2410 TEXTOID, -1, false, 'i',
2411 &val_datums, &val_nulls, &val_count);
2413 if (key_count != val_count)
2415 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2416 errmsg("mismatched array dimensions")));
2418 initStringInfo(&result);
2420 appendStringInfoChar(&result, '{');
2422 for (i = 0; i < key_count; ++i)
2426 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2427 errmsg("null value not allowed for object key")));
2429 v = TextDatumGetCString(key_datums[i]);
2431 appendStringInfoString(&result, ", ");
2432 escape_json(&result, v);
2433 appendStringInfoString(&result, " : ");
2436 appendStringInfoString(&result, "null");
2439 v = TextDatumGetCString(val_datums[i]);
2440 escape_json(&result, v);
2445 appendStringInfoChar(&result, '}');
2452 rval = cstring_to_text_with_len(result.data, result.len);
2455 PG_RETURN_TEXT_P(rval);
2460 * Produce a JSON string literal, properly escaping characters in the text.
2463 escape_json(StringInfo buf, const char *str)
2467 appendStringInfoCharMacro(buf, '"');
2468 for (p = str; *p; p++)
2473 appendStringInfoString(buf, "\\b");
2476 appendStringInfoString(buf, "\\f");
2479 appendStringInfoString(buf, "\\n");
2482 appendStringInfoString(buf, "\\r");
2485 appendStringInfoString(buf, "\\t");
2488 appendStringInfoString(buf, "\\\"");
2491 appendStringInfoString(buf, "\\\\");
2494 if ((unsigned char) *p < ' ')
2495 appendStringInfo(buf, "\\u%04x", (int) *p);
2497 appendStringInfoCharMacro(buf, *p);
2501 appendStringInfoCharMacro(buf, '"');
2505 * SQL function json_typeof(json) -> text
2507 * Returns the type of the outermost JSON value as TEXT. Possible types are
2508 * "object", "array", "string", "number", "boolean", and "null".
2510 * Performs a single call to json_lex() to get the first token of the supplied
2511 * value. This initial token uniquely determines the value's type. As our
2512 * input must already have been validated by json_in() or json_recv(), the
2513 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2514 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2517 json_typeof(PG_FUNCTION_ARGS)
2521 JsonLexContext *lex;
2525 json = PG_GETARG_TEXT_PP(0);
2526 lex = makeJsonLexContext(json, false);
2528 /* Lex exactly one token from the input and check its type. */
2530 tok = lex_peek(lex);
2533 case JSON_TOKEN_OBJECT_START:
2536 case JSON_TOKEN_ARRAY_START:
2539 case JSON_TOKEN_STRING:
2542 case JSON_TOKEN_NUMBER:
2545 case JSON_TOKEN_TRUE:
2546 case JSON_TOKEN_FALSE:
2549 case JSON_TOKEN_NULL:
2553 elog(ERROR, "unexpected json token: %d", tok);
2556 PG_RETURN_TEXT_P(cstring_to_text(type));