1 /*-------------------------------------------------------------------------
4 * JSON data type support.
6 * Portions Copyright (c) 1996-2017, 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);
88 static void report_invalid_token(JsonLexContext *lex);
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 = (char *) str + 1;
211 dummy_lex.input_length = len - 1;
215 dummy_lex.input = (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);
1509 char buf[MAXDATELEN + 1];
1511 date = DatumGetDateADT(val);
1512 /* Same as date_out(), but forcing DateStyle */
1513 if (DATE_NOT_FINITE(date))
1514 EncodeSpecialDate(date, buf);
1517 j2date(date + POSTGRES_EPOCH_JDATE,
1518 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1519 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1521 appendStringInfo(result, "\"%s\"", buf);
1524 case JSONTYPE_TIMESTAMP:
1526 Timestamp timestamp;
1529 char buf[MAXDATELEN + 1];
1531 timestamp = DatumGetTimestamp(val);
1532 /* Same as timestamp_out(), but forcing DateStyle */
1533 if (TIMESTAMP_NOT_FINITE(timestamp))
1534 EncodeSpecialTimestamp(timestamp, buf);
1535 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1536 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
1539 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1540 errmsg("timestamp out of range")));
1541 appendStringInfo(result, "\"%s\"", buf);
1544 case JSONTYPE_TIMESTAMPTZ:
1546 TimestampTz timestamp;
1550 const char *tzn = NULL;
1551 char buf[MAXDATELEN + 1];
1553 timestamp = DatumGetTimestampTz(val);
1554 /* Same as timestamptz_out(), but forcing DateStyle */
1555 if (TIMESTAMP_NOT_FINITE(timestamp))
1556 EncodeSpecialTimestamp(timestamp, buf);
1557 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1558 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
1561 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1562 errmsg("timestamp out of range")));
1563 appendStringInfo(result, "\"%s\"", buf);
1567 /* JSON and JSONB output will already be escaped */
1568 outputstr = OidOutputFunctionCall(outfuncoid, val);
1569 appendStringInfoString(result, outputstr);
1573 /* outfuncoid refers to a cast function, not an output function */
1574 jsontext = DatumGetTextPP(OidFunctionCall1(outfuncoid, val));
1575 outputstr = text_to_cstring(jsontext);
1576 appendStringInfoString(result, outputstr);
1581 outputstr = OidOutputFunctionCall(outfuncoid, val);
1582 escape_json(result, outputstr);
1589 * Process a single dimension of an array.
1590 * If it's the innermost dimension, output the values, otherwise call
1591 * ourselves recursively to process the next dimension.
1594 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1595 bool *nulls, int *valcount, JsonTypeCategory tcategory,
1596 Oid outfuncoid, bool use_line_feeds)
1601 Assert(dim < ndims);
1603 sep = use_line_feeds ? ",\n " : ",";
1605 appendStringInfoChar(result, '[');
1607 for (i = 1; i <= dims[dim]; i++)
1610 appendStringInfoString(result, sep);
1612 if (dim + 1 == ndims)
1614 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1621 * Do we want line feeds on inner dimensions of arrays? For now
1624 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1625 valcount, tcategory, outfuncoid, false);
1629 appendStringInfoChar(result, ']');
1633 * Turn an array into JSON.
1636 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1638 ArrayType *v = DatumGetArrayTypeP(array);
1639 Oid element_type = ARR_ELEMTYPE(v);
1649 JsonTypeCategory tcategory;
1654 nitems = ArrayGetNItems(ndim, dim);
1658 appendStringInfoString(result, "[]");
1662 get_typlenbyvalalign(element_type,
1663 &typlen, &typbyval, &typalign);
1665 json_categorize_type(element_type,
1666 &tcategory, &outfuncoid);
1668 deconstruct_array(v, element_type, typlen, typbyval,
1669 typalign, &elements, &nulls,
1672 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1673 outfuncoid, use_line_feeds);
1680 * Turn a composite / record into JSON.
1683 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1689 HeapTupleData tmptup,
1692 bool needsep = false;
1695 sep = use_line_feeds ? ",\n " : ",";
1697 td = DatumGetHeapTupleHeader(composite);
1699 /* Extract rowtype info and find a tupdesc */
1700 tupType = HeapTupleHeaderGetTypeId(td);
1701 tupTypmod = HeapTupleHeaderGetTypMod(td);
1702 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1704 /* Build a temporary HeapTuple control structure */
1705 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1709 appendStringInfoChar(result, '{');
1711 for (i = 0; i < tupdesc->natts; i++)
1716 JsonTypeCategory tcategory;
1718 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1720 if (att->attisdropped)
1724 appendStringInfoString(result, sep);
1727 attname = NameStr(att->attname);
1728 escape_json(result, attname);
1729 appendStringInfoChar(result, ':');
1731 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1735 tcategory = JSONTYPE_NULL;
1736 outfuncoid = InvalidOid;
1739 json_categorize_type(att->atttypid, &tcategory, &outfuncoid);
1741 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1744 appendStringInfoChar(result, '}');
1745 ReleaseTupleDesc(tupdesc);
1749 * Append JSON text for "val" to "result".
1751 * This is just a thin wrapper around datum_to_json. If the same type will be
1752 * printed many times, avoid using this; better to do the json_categorize_type
1753 * lookups only once.
1756 add_json(Datum val, bool is_null, StringInfo result,
1757 Oid val_type, bool key_scalar)
1759 JsonTypeCategory tcategory;
1762 if (val_type == InvalidOid)
1764 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1765 errmsg("could not determine input data type")));
1769 tcategory = JSONTYPE_NULL;
1770 outfuncoid = InvalidOid;
1773 json_categorize_type(val_type,
1774 &tcategory, &outfuncoid);
1776 datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1780 * SQL function array_to_json(row)
1783 array_to_json(PG_FUNCTION_ARGS)
1785 Datum array = PG_GETARG_DATUM(0);
1788 result = makeStringInfo();
1790 array_to_json_internal(array, result, false);
1792 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1796 * SQL function array_to_json(row, prettybool)
1799 array_to_json_pretty(PG_FUNCTION_ARGS)
1801 Datum array = PG_GETARG_DATUM(0);
1802 bool use_line_feeds = PG_GETARG_BOOL(1);
1805 result = makeStringInfo();
1807 array_to_json_internal(array, result, use_line_feeds);
1809 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1813 * SQL function row_to_json(row)
1816 row_to_json(PG_FUNCTION_ARGS)
1818 Datum array = PG_GETARG_DATUM(0);
1821 result = makeStringInfo();
1823 composite_to_json(array, result, false);
1825 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1829 * SQL function row_to_json(row, prettybool)
1832 row_to_json_pretty(PG_FUNCTION_ARGS)
1834 Datum array = PG_GETARG_DATUM(0);
1835 bool use_line_feeds = PG_GETARG_BOOL(1);
1838 result = makeStringInfo();
1840 composite_to_json(array, result, use_line_feeds);
1842 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1846 * SQL function to_json(anyvalue)
1849 to_json(PG_FUNCTION_ARGS)
1851 Datum val = PG_GETARG_DATUM(0);
1852 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1854 JsonTypeCategory tcategory;
1857 if (val_type == InvalidOid)
1859 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1860 errmsg("could not determine input data type")));
1862 json_categorize_type(val_type,
1863 &tcategory, &outfuncoid);
1865 result = makeStringInfo();
1867 datum_to_json(val, false, result, tcategory, outfuncoid, false);
1869 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1873 * json_agg transition function
1875 * aggregate input column as a json array value.
1878 json_agg_transfn(PG_FUNCTION_ARGS)
1880 MemoryContext aggcontext,
1882 JsonAggState *state;
1885 if (!AggCheckCallContext(fcinfo, &aggcontext))
1887 /* cannot be called directly because of internal-type argument */
1888 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1891 if (PG_ARGISNULL(0))
1893 Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1895 if (arg_type == InvalidOid)
1897 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1898 errmsg("could not determine input data type")));
1901 * Make this state object in a context where it will persist for the
1902 * duration of the aggregate call. MemoryContextSwitchTo is only
1903 * needed the first time, as the StringInfo routines make sure they
1904 * use the right context to enlarge the object if necessary.
1906 oldcontext = MemoryContextSwitchTo(aggcontext);
1907 state = (JsonAggState *) palloc(sizeof(JsonAggState));
1908 state->str = makeStringInfo();
1909 MemoryContextSwitchTo(oldcontext);
1911 appendStringInfoChar(state->str, '[');
1912 json_categorize_type(arg_type, &state->val_category,
1913 &state->val_output_func);
1917 state = (JsonAggState *) PG_GETARG_POINTER(0);
1918 appendStringInfoString(state->str, ", ");
1921 /* fast path for NULLs */
1922 if (PG_ARGISNULL(1))
1924 datum_to_json((Datum) 0, true, state->str, JSONTYPE_NULL,
1926 PG_RETURN_POINTER(state);
1929 val = PG_GETARG_DATUM(1);
1931 /* add some whitespace if structured type and not first item */
1932 if (!PG_ARGISNULL(0) &&
1933 (state->val_category == JSONTYPE_ARRAY ||
1934 state->val_category == JSONTYPE_COMPOSITE))
1936 appendStringInfoString(state->str, "\n ");
1939 datum_to_json(val, false, state->str, state->val_category,
1940 state->val_output_func, false);
1943 * The transition type for json_agg() is declared to be "internal", which
1944 * is a pass-by-value type the same size as a pointer. So we can safely
1945 * pass the JsonAggState pointer through nodeAgg.c's machinations.
1947 PG_RETURN_POINTER(state);
1951 * json_agg final function
1954 json_agg_finalfn(PG_FUNCTION_ARGS)
1956 JsonAggState *state;
1958 /* cannot be called directly because of internal-type argument */
1959 Assert(AggCheckCallContext(fcinfo, NULL));
1961 state = PG_ARGISNULL(0) ?
1963 (JsonAggState *) PG_GETARG_POINTER(0);
1965 /* NULL result for no rows in, as is standard with aggregates */
1969 /* Else return state with appropriate array terminator added */
1970 PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, "]"));
1974 * json_object_agg transition function.
1976 * aggregate two input columns as a single json object value.
1979 json_object_agg_transfn(PG_FUNCTION_ARGS)
1981 MemoryContext aggcontext,
1983 JsonAggState *state;
1986 if (!AggCheckCallContext(fcinfo, &aggcontext))
1988 /* cannot be called directly because of internal-type argument */
1989 elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
1992 if (PG_ARGISNULL(0))
1997 * Make the StringInfo in a context where it will persist for the
1998 * duration of the aggregate call. Switching context is only needed
1999 * for this initial step, as the StringInfo routines make sure they
2000 * use the right context to enlarge the object if necessary.
2002 oldcontext = MemoryContextSwitchTo(aggcontext);
2003 state = (JsonAggState *) palloc(sizeof(JsonAggState));
2004 state->str = makeStringInfo();
2005 MemoryContextSwitchTo(oldcontext);
2007 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
2009 if (arg_type == InvalidOid)
2011 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2012 errmsg("could not determine data type for argument %d", 1)));
2014 json_categorize_type(arg_type, &state->key_category,
2015 &state->key_output_func);
2017 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
2019 if (arg_type == InvalidOid)
2021 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2022 errmsg("could not determine data type for argument %d", 2)));
2024 json_categorize_type(arg_type, &state->val_category,
2025 &state->val_output_func);
2027 appendStringInfoString(state->str, "{ ");
2031 state = (JsonAggState *) PG_GETARG_POINTER(0);
2032 appendStringInfoString(state->str, ", ");
2036 * Note: since json_object_agg() is declared as taking type "any", the
2037 * parser will not do any type conversion on unknown-type literals (that
2038 * is, undecorated strings or NULLs). Such values will arrive here as
2039 * type UNKNOWN, which fortunately does not matter to us, since
2040 * unknownout() works fine.
2043 if (PG_ARGISNULL(1))
2045 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2046 errmsg("field name must not be null")));
2048 arg = PG_GETARG_DATUM(1);
2050 datum_to_json(arg, false, state->str, state->key_category,
2051 state->key_output_func, true);
2053 appendStringInfoString(state->str, " : ");
2055 if (PG_ARGISNULL(2))
2058 arg = PG_GETARG_DATUM(2);
2060 datum_to_json(arg, PG_ARGISNULL(2), state->str, state->val_category,
2061 state->val_output_func, false);
2063 PG_RETURN_POINTER(state);
2067 * json_object_agg final function.
2070 json_object_agg_finalfn(PG_FUNCTION_ARGS)
2072 JsonAggState *state;
2074 /* cannot be called directly because of internal-type argument */
2075 Assert(AggCheckCallContext(fcinfo, NULL));
2077 state = PG_ARGISNULL(0) ? NULL : (JsonAggState *) PG_GETARG_POINTER(0);
2079 /* NULL result for no rows in, as is standard with aggregates */
2083 /* Else return state with appropriate object terminator added */
2084 PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, " }"));
2088 * Helper function for aggregates: return given StringInfo's contents plus
2089 * specified trailing string, as a text datum. We need this because aggregate
2090 * final functions are not allowed to modify the aggregate state.
2093 catenate_stringinfo_string(StringInfo buffer, const char *addon)
2095 /* custom version of cstring_to_text_with_len */
2096 int buflen = buffer->len;
2097 int addlen = strlen(addon);
2098 text *result = (text *) palloc(buflen + addlen + VARHDRSZ);
2100 SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
2101 memcpy(VARDATA(result), buffer->data, buflen);
2102 memcpy(VARDATA(result) + buflen, addon, addlen);
2108 * SQL function json_build_object(variadic "any")
2111 json_build_object(PG_FUNCTION_ARGS)
2113 int nargs = PG_NARGS();
2115 const char *sep = "";
2121 /* fetch argument values to build the object */
2122 nargs = extract_variadic_args(fcinfo, 0, false, &args, &types, &nulls);
2129 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2130 errmsg("argument list must have even number of elements"),
2131 errhint("The arguments of json_build_object() must consist of alternating keys and values.")));
2133 result = makeStringInfo();
2135 appendStringInfoChar(result, '{');
2137 for (i = 0; i < nargs; i += 2)
2139 appendStringInfoString(result, sep);
2145 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2146 errmsg("argument %d cannot be null", i + 1),
2147 errhint("Object keys should be text.")));
2149 add_json(args[i], false, result, types[i], true);
2151 appendStringInfoString(result, " : ");
2154 add_json(args[i + 1], nulls[i + 1], result, types[i + 1], false);
2157 appendStringInfoChar(result, '}');
2159 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2163 * degenerate case of json_build_object where it gets 0 arguments.
2166 json_build_object_noargs(PG_FUNCTION_ARGS)
2168 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2172 * SQL function json_build_array(variadic "any")
2175 json_build_array(PG_FUNCTION_ARGS)
2179 const char *sep = "";
2185 /* fetch argument values to build the array */
2186 nargs = extract_variadic_args(fcinfo, 0, false, &args, &types, &nulls);
2191 result = makeStringInfo();
2193 appendStringInfoChar(result, '[');
2195 for (i = 0; i < nargs; i++)
2197 appendStringInfoString(result, sep);
2199 add_json(args[i], nulls[i], result, types[i], false);
2202 appendStringInfoChar(result, ']');
2204 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2208 * degenerate case of json_build_array where it gets 0 arguments.
2211 json_build_array_noargs(PG_FUNCTION_ARGS)
2213 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2217 * SQL function json_object(text[])
2219 * take a one or two dimensional array of text as key/value pairs
2220 * for a json object.
2223 json_object(PG_FUNCTION_ARGS)
2225 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2226 int ndims = ARR_NDIM(in_array);
2227 StringInfoData result;
2239 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2243 if ((ARR_DIMS(in_array)[0]) % 2)
2245 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2246 errmsg("array must have even number of elements")));
2250 if ((ARR_DIMS(in_array)[1]) != 2)
2252 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2253 errmsg("array must have two columns")));
2258 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2259 errmsg("wrong number of array subscripts")));
2262 deconstruct_array(in_array,
2263 TEXTOID, -1, false, 'i',
2264 &in_datums, &in_nulls, &in_count);
2266 count = in_count / 2;
2268 initStringInfo(&result);
2270 appendStringInfoChar(&result, '{');
2272 for (i = 0; i < count; ++i)
2274 if (in_nulls[i * 2])
2276 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2277 errmsg("null value not allowed for object key")));
2279 v = TextDatumGetCString(in_datums[i * 2]);
2281 appendStringInfoString(&result, ", ");
2282 escape_json(&result, v);
2283 appendStringInfoString(&result, " : ");
2285 if (in_nulls[i * 2 + 1])
2286 appendStringInfoString(&result, "null");
2289 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2290 escape_json(&result, v);
2295 appendStringInfoChar(&result, '}');
2300 rval = cstring_to_text_with_len(result.data, result.len);
2303 PG_RETURN_TEXT_P(rval);
2308 * SQL function json_object(text[], text[])
2310 * take separate key and value arrays of text to construct a json object
2314 json_object_two_arg(PG_FUNCTION_ARGS)
2316 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2317 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2318 int nkdims = ARR_NDIM(key_array);
2319 int nvdims = ARR_NDIM(val_array);
2320 StringInfoData result;
2331 if (nkdims > 1 || nkdims != nvdims)
2333 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2334 errmsg("wrong number of array subscripts")));
2337 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2339 deconstruct_array(key_array,
2340 TEXTOID, -1, false, 'i',
2341 &key_datums, &key_nulls, &key_count);
2343 deconstruct_array(val_array,
2344 TEXTOID, -1, false, 'i',
2345 &val_datums, &val_nulls, &val_count);
2347 if (key_count != val_count)
2349 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2350 errmsg("mismatched array dimensions")));
2352 initStringInfo(&result);
2354 appendStringInfoChar(&result, '{');
2356 for (i = 0; i < key_count; ++i)
2360 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2361 errmsg("null value not allowed for object key")));
2363 v = TextDatumGetCString(key_datums[i]);
2365 appendStringInfoString(&result, ", ");
2366 escape_json(&result, v);
2367 appendStringInfoString(&result, " : ");
2370 appendStringInfoString(&result, "null");
2373 v = TextDatumGetCString(val_datums[i]);
2374 escape_json(&result, v);
2379 appendStringInfoChar(&result, '}');
2386 rval = cstring_to_text_with_len(result.data, result.len);
2389 PG_RETURN_TEXT_P(rval);
2394 * Produce a JSON string literal, properly escaping characters in the text.
2397 escape_json(StringInfo buf, const char *str)
2401 appendStringInfoCharMacro(buf, '"');
2402 for (p = str; *p; p++)
2407 appendStringInfoString(buf, "\\b");
2410 appendStringInfoString(buf, "\\f");
2413 appendStringInfoString(buf, "\\n");
2416 appendStringInfoString(buf, "\\r");
2419 appendStringInfoString(buf, "\\t");
2422 appendStringInfoString(buf, "\\\"");
2425 appendStringInfoString(buf, "\\\\");
2428 if ((unsigned char) *p < ' ')
2429 appendStringInfo(buf, "\\u%04x", (int) *p);
2431 appendStringInfoCharMacro(buf, *p);
2435 appendStringInfoCharMacro(buf, '"');
2439 * SQL function json_typeof(json) -> text
2441 * Returns the type of the outermost JSON value as TEXT. Possible types are
2442 * "object", "array", "string", "number", "boolean", and "null".
2444 * Performs a single call to json_lex() to get the first token of the supplied
2445 * value. This initial token uniquely determines the value's type. As our
2446 * input must already have been validated by json_in() or json_recv(), the
2447 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2448 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2451 json_typeof(PG_FUNCTION_ARGS)
2455 JsonLexContext *lex;
2459 json = PG_GETARG_TEXT_PP(0);
2460 lex = makeJsonLexContext(json, false);
2462 /* Lex exactly one token from the input and check its type. */
2464 tok = lex_peek(lex);
2467 case JSON_TOKEN_OBJECT_START:
2470 case JSON_TOKEN_ARRAY_START:
2473 case JSON_TOKEN_STRING:
2476 case JSON_TOKEN_NUMBER:
2479 case JSON_TOKEN_TRUE:
2480 case JSON_TOKEN_FALSE:
2483 case JSON_TOKEN_NULL:
2487 elog(ERROR, "unexpected json token: %d", tok);
2490 PG_RETURN_TEXT_P(cstring_to_text(type));