1 /*-------------------------------------------------------------------------
4 * JSON data type support.
6 * Portions Copyright (c) 1996-2013, 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_cast.h"
19 #include "catalog/pg_type.h"
20 #include "executor/spi.h"
21 #include "lib/stringinfo.h"
22 #include "libpq/pqformat.h"
23 #include "mb/pg_wchar.h"
24 #include "parser/parse_coerce.h"
25 #include "utils/array.h"
26 #include "utils/builtins.h"
27 #include "utils/lsyscache.h"
28 #include "utils/json.h"
29 #include "utils/jsonapi.h"
30 #include "utils/typcache.h"
31 #include "utils/syscache.h"
34 * The context of the parser is maintained by the recursive descent
35 * mechanism, but is passed explicitly to the error reporting routine
36 * for better diagnostics.
38 typedef enum /* contexts of JSON parser */
40 JSON_PARSE_VALUE, /* expecting a value */
41 JSON_PARSE_STRING, /* expecting a string (for a field name) */
42 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
43 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
44 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
45 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
46 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
47 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
48 JSON_PARSE_END /* saw the end of a document, expect nothing */
51 static inline void json_lex(JsonLexContext *lex);
52 static inline void json_lex_string(JsonLexContext *lex);
53 static inline void json_lex_number(JsonLexContext *lex, char *s);
54 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
55 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
56 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
57 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
58 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
59 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
60 static void report_invalid_token(JsonLexContext *lex);
61 static int report_json_context(JsonLexContext *lex);
62 static char *extract_mb_char(char *s);
63 static void composite_to_json(Datum composite, StringInfo result,
65 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
66 Datum *vals, bool *nulls, int *valcount,
67 TYPCATEGORY tcategory, Oid typoutputfunc,
69 static void array_to_json_internal(Datum array, StringInfo result,
72 /* the null action object used for pure validation */
73 static JsonSemAction nullSemAction =
75 NULL, NULL, NULL, NULL, NULL,
76 NULL, NULL, NULL, NULL, NULL
79 /* Recursive Descent parser support routines */
84 * what is the current look_ahead token?
86 static inline JsonTokenType
87 lex_peek(JsonLexContext *lex)
89 return lex->token_type;
95 * accept the look_ahead token and move the lexer to the next token if the
96 * look_ahead token matches the token parameter. In that case, and if required,
97 * also hand back the de-escaped lexeme.
99 * returns true if the token matched, false otherwise.
102 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
104 if (lex->token_type == token)
108 if (lex->token_type == JSON_TOKEN_STRING)
110 if (lex->strval != NULL)
111 *lexeme = pstrdup(lex->strval->data);
115 int len = (lex->token_terminator - lex->token_start);
116 char *tokstr = palloc(len + 1);
118 memcpy(tokstr, lex->token_start, len);
132 * move the lexer to the next token if the current look_ahead token matches
133 * the parameter token. Otherwise, report an error.
136 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
138 if (!lex_accept(lex, token, NULL))
139 report_parse_error(ctx, lex);;
143 * All the defined type categories are upper case , so use lower case here
144 * so we avoid any possible clash.
146 /* fake type category for JSON so we can distinguish it in datum_to_json */
147 #define TYPCATEGORY_JSON 'j'
148 /* fake category for types that have a cast to json */
149 #define TYPCATEGORY_JSON_CAST 'c'
150 /* letters appearing in numeric output that aren't valid in a JSON number */
151 #define NON_NUMERIC_LETTER "NnAaIiFfTtYy"
152 /* chars to consider as part of an alphanumeric token */
153 #define JSON_ALPHANUMERIC_CHAR(c) \
154 (((c) >= 'a' && (c) <= 'z') || \
155 ((c) >= 'A' && (c) <= 'Z') || \
156 ((c) >= '0' && (c) <= '9') || \
164 json_in(PG_FUNCTION_ARGS)
166 char *json = PG_GETARG_CSTRING(0);
167 text *result = cstring_to_text(json);
171 lex = makeJsonLexContext(result, false);
172 pg_parse_json(lex, &nullSemAction);
174 /* Internal representation is the same as text, for now */
175 PG_RETURN_TEXT_P(result);
182 json_out(PG_FUNCTION_ARGS)
184 /* we needn't detoast because text_to_cstring will handle that */
185 Datum txt = PG_GETARG_DATUM(0);
187 PG_RETURN_CSTRING(TextDatumGetCString(txt));
194 json_send(PG_FUNCTION_ARGS)
196 text *t = PG_GETARG_TEXT_PP(0);
199 pq_begintypsend(&buf);
200 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
201 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
208 json_recv(PG_FUNCTION_ARGS)
210 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
216 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
218 result = palloc(nbytes + VARHDRSZ);
219 SET_VARSIZE(result, nbytes + VARHDRSZ);
220 memcpy(VARDATA(result), str, nbytes);
223 lex = makeJsonLexContext(result, false);
224 pg_parse_json(lex, &nullSemAction);
226 PG_RETURN_TEXT_P(result);
232 * lex constructor, with or without StringInfo object
233 * for de-escaped lexemes.
235 * Without is better as it makes the processing faster, so only make one
236 * if really required.
239 makeJsonLexContext(text *json, bool need_escapes)
241 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
243 lex->input = lex->token_terminator = lex->line_start = VARDATA(json);
244 lex->line_number = 1;
245 lex->input_length = VARSIZE(json) - VARHDRSZ;
247 lex->strval = makeStringInfo();
254 * Publicly visible entry point for the JSON parser.
256 * lex is a lexing context, set up for the json to be processed by calling
257 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
258 * action routines to be called at appropriate spots during parsing, and a
259 * pointer to a state object to be passed to those routines.
262 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
266 /* get the initial token */
271 /* parse by recursive descent */
274 case JSON_TOKEN_OBJECT_START:
275 parse_object(lex, sem);
277 case JSON_TOKEN_ARRAY_START:
278 parse_array(lex, sem);
281 parse_scalar(lex, sem); /* json can be a bare scalar */
284 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
289 * Recursive Descent parse routines. There is one for each structural
290 * element in a json document:
291 * - scalar (string, number, true, false, null)
298 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
301 json_scalar_action sfunc = sem->scalar;
303 JsonTokenType tok = lex_peek(lex);
305 valaddr = sfunc == NULL ? NULL : &val;
307 /* a scalar must be a string, a number, true, false, or null */
310 case JSON_TOKEN_TRUE:
311 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
313 case JSON_TOKEN_FALSE:
314 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
316 case JSON_TOKEN_NULL:
317 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
319 case JSON_TOKEN_NUMBER:
320 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
322 case JSON_TOKEN_STRING:
323 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
326 report_parse_error(JSON_PARSE_VALUE, lex);
330 (*sfunc) (sem->semstate, val, tok);
334 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
337 * an object field is "fieldname" : value where value can be a scalar,
341 char *fname = NULL; /* keep compiler quiet */
342 json_ofield_action ostart = sem->object_field_start;
343 json_ofield_action oend = sem->object_field_end;
345 char **fnameaddr = NULL;
348 if (ostart != NULL || oend != NULL)
351 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
352 report_parse_error(JSON_PARSE_STRING, lex);
354 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
357 isnull = tok == JSON_TOKEN_NULL;
360 (*ostart) (sem->semstate, fname, isnull);
364 case JSON_TOKEN_OBJECT_START:
365 parse_object(lex, sem);
367 case JSON_TOKEN_ARRAY_START:
368 parse_array(lex, sem);
371 parse_scalar(lex, sem);
375 (*oend) (sem->semstate, fname, isnull);
382 parse_object(JsonLexContext *lex, JsonSemAction *sem)
385 * an object is a possibly empty sequence of object fields, separated by
386 * commas and surrounde by curly braces.
388 json_struct_action ostart = sem->object_start;
389 json_struct_action oend = sem->object_end;
393 (*ostart) (sem->semstate);
396 * Data inside an object at at a higher nesting level than the object
397 * itself. Note that we increment this after we call the semantic routine
398 * for the object start and restore it before we call the routine for the
403 /* we know this will succeeed, just clearing the token */
404 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
409 case JSON_TOKEN_STRING:
410 parse_object_field(lex, sem);
411 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
412 parse_object_field(lex, sem);
414 case JSON_TOKEN_OBJECT_END:
417 /* case of an invalid initial token inside the object */
418 report_parse_error(JSON_PARSE_OBJECT_START, lex);
421 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
426 (*oend) (sem->semstate);
430 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
432 json_aelem_action astart = sem->array_element_start;
433 json_aelem_action aend = sem->array_element_end;
434 JsonTokenType tok = lex_peek(lex);
438 isnull = tok == JSON_TOKEN_NULL;
441 (*astart) (sem->semstate, isnull);
443 /* an array element is any object, array or scalar */
446 case JSON_TOKEN_OBJECT_START:
447 parse_object(lex, sem);
449 case JSON_TOKEN_ARRAY_START:
450 parse_array(lex, sem);
453 parse_scalar(lex, sem);
457 (*aend) (sem->semstate, isnull);
461 parse_array(JsonLexContext *lex, JsonSemAction *sem)
464 * an array is a possibly empty sequence of array elements, separated by
465 * commas and surrounded by square brackets.
467 json_struct_action astart = sem->array_start;
468 json_struct_action aend = sem->array_end;
471 (*astart) (sem->semstate);
474 * Data inside an array at at a higher nesting level than the array
475 * itself. Note that we increment this after we call the semantic routine
476 * for the array start and restore it before we call the routine for the
481 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
482 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
485 parse_array_element(lex, sem);
487 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
488 parse_array_element(lex, sem);
491 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
496 (*aend) (sem->semstate);
500 * Lex one token from the input stream.
503 json_lex(JsonLexContext *lex)
508 /* Skip leading whitespace. */
509 s = lex->token_terminator;
510 len = s - lex->input;
511 while (len < lex->input_length &&
512 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
519 lex->token_start = s;
521 /* Determine token type. */
522 if (len >= lex->input_length)
524 lex->token_start = NULL;
525 lex->prev_token_terminator = lex->token_terminator;
526 lex->token_terminator = s;
527 lex->token_type = JSON_TOKEN_END;
532 /* Single-character token, some kind of punctuation mark. */
534 lex->prev_token_terminator = lex->token_terminator;
535 lex->token_terminator = s + 1;
536 lex->token_type = JSON_TOKEN_OBJECT_START;
539 lex->prev_token_terminator = lex->token_terminator;
540 lex->token_terminator = s + 1;
541 lex->token_type = JSON_TOKEN_OBJECT_END;
544 lex->prev_token_terminator = lex->token_terminator;
545 lex->token_terminator = s + 1;
546 lex->token_type = JSON_TOKEN_ARRAY_START;
549 lex->prev_token_terminator = lex->token_terminator;
550 lex->token_terminator = s + 1;
551 lex->token_type = JSON_TOKEN_ARRAY_END;
554 lex->prev_token_terminator = lex->token_terminator;
555 lex->token_terminator = s + 1;
556 lex->token_type = JSON_TOKEN_COMMA;
559 lex->prev_token_terminator = lex->token_terminator;
560 lex->token_terminator = s + 1;
561 lex->token_type = JSON_TOKEN_COLON;
565 json_lex_string(lex);
566 lex->token_type = JSON_TOKEN_STRING;
569 /* Negative number. */
570 json_lex_number(lex, s + 1);
571 lex->token_type = JSON_TOKEN_NUMBER;
583 /* Positive number. */
584 json_lex_number(lex, s);
585 lex->token_type = JSON_TOKEN_NUMBER;
592 * We're not dealing with a string, number, legal
593 * punctuation mark, or end of string. The only legal
594 * tokens we might find here are true, false, and null,
595 * but for error reporting purposes we scan until we see a
596 * non-alphanumeric character. That way, we can report
597 * the whole word as an unexpected token, rather than just
598 * some unintuitive prefix thereof.
600 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
604 * We got some sort of unexpected punctuation or an
605 * otherwise unexpected character, so just complain about
606 * that one character.
610 lex->prev_token_terminator = lex->token_terminator;
611 lex->token_terminator = s + 1;
612 report_invalid_token(lex);
616 * We've got a real alphanumeric token here. If it
617 * happens to be true, false, or null, all is well. If
620 lex->prev_token_terminator = lex->token_terminator;
621 lex->token_terminator = p;
624 if (memcmp(s, "true", 4) == 0)
625 lex->token_type = JSON_TOKEN_TRUE;
626 else if (memcmp(s, "null", 4) == 0)
627 lex->token_type = JSON_TOKEN_NULL;
629 report_invalid_token(lex);
631 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
632 lex->token_type = JSON_TOKEN_FALSE;
634 report_invalid_token(lex);
637 } /* end of switch */
641 * The next token in the input stream is known to be a string; lex it.
644 json_lex_string(JsonLexContext *lex)
648 int hi_surrogate = -1;
650 if (lex->strval != NULL)
651 resetStringInfo(lex->strval);
653 Assert(lex->input_length > 0);
654 s = lex->token_start;
655 len = lex->token_start - lex->input;
660 /* Premature end of the string. */
661 if (len >= lex->input_length)
663 lex->token_terminator = s;
664 report_invalid_token(lex);
668 else if ((unsigned char) *s < 32)
670 /* Per RFC4627, these characters MUST be escaped. */
671 /* Since *s isn't printable, exclude it from the context string */
672 lex->token_terminator = s;
674 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
675 errmsg("invalid input syntax for type json"),
676 errdetail("Character with value 0x%02x must be escaped.",
678 report_json_context(lex)));
682 /* OK, we have an escape character. */
685 if (len >= lex->input_length)
687 lex->token_terminator = s;
688 report_invalid_token(lex);
695 for (i = 1; i <= 4; i++)
699 if (len >= lex->input_length)
701 lex->token_terminator = s;
702 report_invalid_token(lex);
704 else if (*s >= '0' && *s <= '9')
705 ch = (ch * 16) + (*s - '0');
706 else if (*s >= 'a' && *s <= 'f')
707 ch = (ch * 16) + (*s - 'a') + 10;
708 else if (*s >= 'A' && *s <= 'F')
709 ch = (ch * 16) + (*s - 'A') + 10;
712 lex->token_terminator = s + pg_mblen(s);
714 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
715 errmsg("invalid input syntax for type json"),
716 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
717 report_json_context(lex)));
720 if (lex->strval != NULL)
725 if (ch >= 0xd800 && ch <= 0xdbff)
727 if (hi_surrogate != -1)
729 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
730 errmsg("invalid input syntax for type json"),
731 errdetail("high order surrogate must not follow a high order surrogate."),
732 report_json_context(lex)));
733 hi_surrogate = (ch & 0x3ff) << 10;
736 else if (ch >= 0xdc00 && ch <= 0xdfff)
738 if (hi_surrogate == -1)
740 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
741 errmsg("invalid input syntax for type json"),
742 errdetail("low order surrogate must follow a high order surrogate."),
743 report_json_context(lex)));
744 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
748 if (hi_surrogate != -1)
750 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
751 errmsg("invalid input syntax for type json"),
752 errdetail("low order surrogate must follow a high order surrogate."),
753 report_json_context(lex)));
756 * For UTF8, replace the escape sequence by the actual utf8
757 * character in lex->strval. Do this also for other encodings
758 * if the escape designates an ASCII character, otherwise
759 * raise an error. We don't ever unescape a \u0000, since that
760 * would result in an impermissible nul byte.
765 appendStringInfoString(lex->strval, "\\u0000");
767 else if (GetDatabaseEncoding() == PG_UTF8)
769 unicode_to_utf8(ch, (unsigned char *) utf8str);
770 utf8len = pg_utf_mblen((unsigned char *) utf8str);
771 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
773 else if (ch <= 0x007f)
776 * This is the only way to designate things like a form feed
777 * character in JSON, so it's useful in all encodings.
779 appendStringInfoChar(lex->strval, (char) ch);
784 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
785 errmsg("invalid input syntax for type json"),
786 errdetail("Unicode escape for code points higher than U+007F not permitted in non-UTF8 encoding"),
787 report_json_context(lex)));
792 else if (lex->strval != NULL)
794 if (hi_surrogate != -1)
796 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
797 errmsg("invalid input syntax for type json"),
798 errdetail("low order surrogate must follow a high order surrogate."),
799 report_json_context(lex)));
806 appendStringInfoChar(lex->strval, *s);
809 appendStringInfoChar(lex->strval, '\b');
812 appendStringInfoChar(lex->strval, '\f');
815 appendStringInfoChar(lex->strval, '\n');
818 appendStringInfoChar(lex->strval, '\r');
821 appendStringInfoChar(lex->strval, '\t');
824 /* Not a valid string escape, so error out. */
825 lex->token_terminator = s + pg_mblen(s);
827 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
828 errmsg("invalid input syntax for type json"),
829 errdetail("Escape sequence \"\\%s\" is invalid.",
831 report_json_context(lex)));
834 else if (strchr("\"\\/bfnrt", *s) == NULL)
837 * Simpler processing if we're not bothered about de-escaping
839 * It's very tempting to remove the strchr() call here and
840 * replace it with a switch statement, but testing so far has
841 * shown it's not a performance win.
843 lex->token_terminator = s + pg_mblen(s);
845 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
846 errmsg("invalid input syntax for type json"),
847 errdetail("Escape sequence \"\\%s\" is invalid.",
849 report_json_context(lex)));
853 else if (lex->strval != NULL)
855 if (hi_surrogate != -1)
857 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
858 errmsg("invalid input syntax for type json"),
859 errdetail("low order surrogate must follow a high order surrogate."),
860 report_json_context(lex)));
862 appendStringInfoChar(lex->strval, *s);
867 if (hi_surrogate != -1)
869 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
870 errmsg("invalid input syntax for type json"),
871 errdetail("low order surrogate must follow a high order surrogate."),
872 report_json_context(lex)));
874 /* Hooray, we found the end of the string! */
875 lex->prev_token_terminator = lex->token_terminator;
876 lex->token_terminator = s + 1;
879 /*-------------------------------------------------------------------------
880 * The next token in the input stream is known to be a number; lex it.
882 * In JSON, a number consists of four parts:
884 * (1) An optional minus sign ('-').
886 * (2) Either a single '0', or a string of one or more digits that does not
889 * (3) An optional decimal part, consisting of a period ('.') followed by
890 * one or more digits. (Note: While this part can be omitted
891 * completely, it's not OK to have only the decimal point without
892 * any digits afterwards.)
894 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
895 * followed by '+' or '-', followed by one or more digits. (Note:
896 * As with the decimal part, if 'e' or 'E' is present, it must be
897 * followed by at least one digit.)
899 * The 's' argument to this function points to the ostensible beginning
900 * of part 2 - i.e. the character after any optional minus sign, and the
901 * first character of the string if there is none.
903 *-------------------------------------------------------------------------
906 json_lex_number(JsonLexContext *lex, char *s)
912 len = s - lex->input;
913 /* Part (1): leading sign indicator. */
914 /* Caller already did this for us; so do nothing. */
916 /* Part (2): parse main digit string. */
922 else if (*s >= '1' && *s <= '9')
928 } while (len < lex->input_length && *s >= '0' && *s <= '9');
933 /* Part (3): parse optional decimal portion. */
934 if (len < lex->input_length && *s == '.')
938 if (len == lex->input_length || *s < '0' || *s > '9')
946 } while (len < lex->input_length && *s >= '0' && *s <= '9');
950 /* Part (4): parse optional exponent. */
951 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
955 if (len < lex->input_length && (*s == '+' || *s == '-'))
960 if (len == lex->input_length || *s < '0' || *s > '9')
968 } while (len < lex->input_length && *s >= '0' && *s <= '9');
973 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
974 * here should be considered part of the token for error-reporting
977 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
979 lex->prev_token_terminator = lex->token_terminator;
980 lex->token_terminator = p;
982 report_invalid_token(lex);
986 * Report a parse error.
988 * lex->token_start and lex->token_terminator must identify the current token.
991 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
996 /* Handle case where the input ended prematurely. */
997 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
999 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1000 errmsg("invalid input syntax for type json"),
1001 errdetail("The input string ended unexpectedly."),
1002 report_json_context(lex)));
1004 /* Separate out the current token. */
1005 toklen = lex->token_terminator - lex->token_start;
1006 token = palloc(toklen + 1);
1007 memcpy(token, lex->token_start, toklen);
1008 token[toklen] = '\0';
1010 /* Complain, with the appropriate detail message. */
1011 if (ctx == JSON_PARSE_END)
1013 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1014 errmsg("invalid input syntax for type json"),
1015 errdetail("Expected end of input, but found \"%s\".",
1017 report_json_context(lex)));
1022 case JSON_PARSE_VALUE:
1024 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1025 errmsg("invalid input syntax for type json"),
1026 errdetail("Expected JSON value, but found \"%s\".",
1028 report_json_context(lex)));
1030 case JSON_PARSE_STRING:
1032 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1033 errmsg("invalid input syntax for type json"),
1034 errdetail("Expected string, but found \"%s\".",
1036 report_json_context(lex)));
1038 case JSON_PARSE_ARRAY_START:
1040 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1041 errmsg("invalid input syntax for type json"),
1042 errdetail("Expected array element or \"]\", but found \"%s\".",
1044 report_json_context(lex)));
1046 case JSON_PARSE_ARRAY_NEXT:
1048 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1049 errmsg("invalid input syntax for type json"),
1050 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1052 report_json_context(lex)));
1054 case JSON_PARSE_OBJECT_START:
1056 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1057 errmsg("invalid input syntax for type json"),
1058 errdetail("Expected string or \"}\", but found \"%s\".",
1060 report_json_context(lex)));
1062 case JSON_PARSE_OBJECT_LABEL:
1064 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1065 errmsg("invalid input syntax for type json"),
1066 errdetail("Expected \":\", but found \"%s\".",
1068 report_json_context(lex)));
1070 case JSON_PARSE_OBJECT_NEXT:
1072 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1073 errmsg("invalid input syntax for type json"),
1074 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1076 report_json_context(lex)));
1078 case JSON_PARSE_OBJECT_COMMA:
1080 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1081 errmsg("invalid input syntax for type json"),
1082 errdetail("Expected string, but found \"%s\".",
1084 report_json_context(lex)));
1087 elog(ERROR, "unexpected json parse state: %d", ctx);
1093 * Report an invalid input token.
1095 * lex->token_start and lex->token_terminator must identify the token.
1098 report_invalid_token(JsonLexContext *lex)
1103 /* Separate out the offending token. */
1104 toklen = lex->token_terminator - lex->token_start;
1105 token = palloc(toklen + 1);
1106 memcpy(token, lex->token_start, toklen);
1107 token[toklen] = '\0';
1110 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1111 errmsg("invalid input syntax for type json"),
1112 errdetail("Token \"%s\" is invalid.", token),
1113 report_json_context(lex)));
1117 * Report a CONTEXT line for bogus JSON input.
1119 * lex->token_terminator must be set to identify the spot where we detected
1120 * the error. Note that lex->token_start might be NULL, in case we recognized
1123 * The return value isn't meaningful, but we make it non-void so that this
1124 * can be invoked inside ereport().
1127 report_json_context(JsonLexContext *lex)
1129 const char *context_start;
1130 const char *context_end;
1131 const char *line_start;
1138 /* Choose boundaries for the part of the input we will display */
1139 context_start = lex->input;
1140 context_end = lex->token_terminator;
1141 line_start = context_start;
1145 /* Always advance over newlines */
1146 if (context_start < context_end && *context_start == '\n')
1149 line_start = context_start;
1153 /* Otherwise, done as soon as we are close enough to context_end */
1154 if (context_end - context_start < 50)
1156 /* Advance to next multibyte character */
1157 if (IS_HIGHBIT_SET(*context_start))
1158 context_start += pg_mblen(context_start);
1164 * We add "..." to indicate that the excerpt doesn't start at the
1165 * beginning of the line ... but if we're within 3 characters of the
1166 * beginning of the line, we might as well just show the whole line.
1168 if (context_start - line_start <= 3)
1169 context_start = line_start;
1171 /* Get a null-terminated copy of the data to present */
1172 ctxtlen = context_end - context_start;
1173 ctxt = palloc(ctxtlen + 1);
1174 memcpy(ctxt, context_start, ctxtlen);
1175 ctxt[ctxtlen] = '\0';
1178 * Show the context, prefixing "..." if not starting at start of line, and
1179 * suffixing "..." if not ending at end of line.
1181 prefix = (context_start > line_start) ? "..." : "";
1182 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1184 return errcontext("JSON data, line %d: %s%s%s",
1185 line_number, prefix, ctxt, suffix);
1189 * Extract a single, possibly multi-byte char from the input string.
1192 extract_mb_char(char *s)
1198 res = palloc(len + 1);
1199 memcpy(res, s, len);
1206 * Turn a scalar Datum into JSON, appending the string to "result".
1208 * Hand off a non-scalar datum to composite_to_json or array_to_json_internal
1212 datum_to_json(Datum val, bool is_null, StringInfo result,
1213 TYPCATEGORY tcategory, Oid typoutputfunc)
1220 appendStringInfoString(result, "null");
1226 case TYPCATEGORY_ARRAY:
1227 array_to_json_internal(val, result, false);
1229 case TYPCATEGORY_COMPOSITE:
1230 composite_to_json(val, result, false);
1232 case TYPCATEGORY_BOOLEAN:
1233 if (DatumGetBool(val))
1234 appendStringInfoString(result, "true");
1236 appendStringInfoString(result, "false");
1238 case TYPCATEGORY_NUMERIC:
1239 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1242 * Don't call escape_json here if it's a valid JSON number.
1243 * Numeric output should usually be a valid JSON number and JSON
1244 * numbers shouldn't be quoted. Quote cases like "Nan" and
1245 * "Infinity", however.
1247 if (strpbrk(outputstr, NON_NUMERIC_LETTER) == NULL)
1248 appendStringInfoString(result, outputstr);
1250 escape_json(result, outputstr);
1253 case TYPCATEGORY_JSON:
1254 /* JSON will already be escaped */
1255 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1256 appendStringInfoString(result, outputstr);
1259 case TYPCATEGORY_JSON_CAST:
1260 jsontext = DatumGetTextP(OidFunctionCall1(typoutputfunc, val));
1261 outputstr = text_to_cstring(jsontext);
1262 appendStringInfoString(result, outputstr);
1267 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1268 escape_json(result, outputstr);
1275 * Process a single dimension of an array.
1276 * If it's the innermost dimension, output the values, otherwise call
1277 * ourselves recursively to process the next dimension.
1280 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1281 bool *nulls, int *valcount, TYPCATEGORY tcategory,
1282 Oid typoutputfunc, bool use_line_feeds)
1287 Assert(dim < ndims);
1289 sep = use_line_feeds ? ",\n " : ",";
1291 appendStringInfoChar(result, '[');
1293 for (i = 1; i <= dims[dim]; i++)
1296 appendStringInfoString(result, sep);
1298 if (dim + 1 == ndims)
1300 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1307 * Do we want line feeds on inner dimensions of arrays? For now
1310 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1311 valcount, tcategory, typoutputfunc, false);
1315 appendStringInfoChar(result, ']');
1319 * Turn an array into JSON.
1322 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1324 ArrayType *v = DatumGetArrayTypeP(array);
1325 Oid element_type = ARR_ELEMTYPE(v);
1338 TYPCATEGORY tcategory;
1339 Oid castfunc = InvalidOid;
1343 nitems = ArrayGetNItems(ndim, dim);
1347 appendStringInfoString(result, "[]");
1351 get_type_io_data(element_type, IOFunc_output,
1352 &typlen, &typbyval, &typalign,
1353 &typdelim, &typioparam, &typoutputfunc);
1355 if (element_type > FirstNormalObjectId)
1358 Form_pg_cast castForm;
1360 tuple = SearchSysCache2(CASTSOURCETARGET,
1361 ObjectIdGetDatum(element_type),
1362 ObjectIdGetDatum(JSONOID));
1363 if (HeapTupleIsValid(tuple))
1365 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1367 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1368 castfunc = typoutputfunc = castForm->castfunc;
1370 ReleaseSysCache(tuple);
1374 deconstruct_array(v, element_type, typlen, typbyval,
1375 typalign, &elements, &nulls,
1378 if (castfunc != InvalidOid)
1379 tcategory = TYPCATEGORY_JSON_CAST;
1380 else if (element_type == RECORDOID)
1381 tcategory = TYPCATEGORY_COMPOSITE;
1382 else if (element_type == JSONOID)
1383 tcategory = TYPCATEGORY_JSON;
1385 tcategory = TypeCategory(element_type);
1387 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1388 typoutputfunc, use_line_feeds);
1395 * Turn a composite / record into JSON.
1398 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1404 HeapTupleData tmptup,
1407 bool needsep = false;
1410 sep = use_line_feeds ? ",\n " : ",";
1412 td = DatumGetHeapTupleHeader(composite);
1414 /* Extract rowtype info and find a tupdesc */
1415 tupType = HeapTupleHeaderGetTypeId(td);
1416 tupTypmod = HeapTupleHeaderGetTypMod(td);
1417 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1419 /* Build a temporary HeapTuple control structure */
1420 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1424 appendStringInfoChar(result, '{');
1426 for (i = 0; i < tupdesc->natts; i++)
1432 TYPCATEGORY tcategory;
1435 Oid castfunc = InvalidOid;
1437 if (tupdesc->attrs[i]->attisdropped)
1441 appendStringInfoString(result, sep);
1444 attname = NameStr(tupdesc->attrs[i]->attname);
1445 escape_json(result, attname);
1446 appendStringInfoChar(result, ':');
1448 origval = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1450 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1451 &typoutput, &typisvarlena);
1453 if (tupdesc->attrs[i]->atttypid > FirstNormalObjectId)
1455 HeapTuple cast_tuple;
1456 Form_pg_cast castForm;
1458 cast_tuple = SearchSysCache2(CASTSOURCETARGET,
1459 ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),
1460 ObjectIdGetDatum(JSONOID));
1461 if (HeapTupleIsValid(cast_tuple))
1463 castForm = (Form_pg_cast) GETSTRUCT(cast_tuple);
1465 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1466 castfunc = typoutput = castForm->castfunc;
1468 ReleaseSysCache(cast_tuple);
1472 if (castfunc != InvalidOid)
1473 tcategory = TYPCATEGORY_JSON_CAST;
1474 else if (tupdesc->attrs[i]->atttypid == RECORDARRAYOID)
1475 tcategory = TYPCATEGORY_ARRAY;
1476 else if (tupdesc->attrs[i]->atttypid == RECORDOID)
1477 tcategory = TYPCATEGORY_COMPOSITE;
1478 else if (tupdesc->attrs[i]->atttypid == JSONOID)
1479 tcategory = TYPCATEGORY_JSON;
1481 tcategory = TypeCategory(tupdesc->attrs[i]->atttypid);
1484 * If we have a toasted datum, forcibly detoast it here to avoid
1485 * memory leakage inside the type's output routine.
1487 if (typisvarlena && !isnull)
1488 val = PointerGetDatum(PG_DETOAST_DATUM(origval));
1492 datum_to_json(val, isnull, result, tcategory, typoutput);
1494 /* Clean up detoasted copy, if any */
1496 pfree(DatumGetPointer(val));
1499 appendStringInfoChar(result, '}');
1500 ReleaseTupleDesc(tupdesc);
1504 * SQL function array_to_json(row)
1507 array_to_json(PG_FUNCTION_ARGS)
1509 Datum array = PG_GETARG_DATUM(0);
1512 result = makeStringInfo();
1514 array_to_json_internal(array, result, false);
1516 PG_RETURN_TEXT_P(cstring_to_text(result->data));
1520 * SQL function array_to_json(row, prettybool)
1523 array_to_json_pretty(PG_FUNCTION_ARGS)
1525 Datum array = PG_GETARG_DATUM(0);
1526 bool use_line_feeds = PG_GETARG_BOOL(1);
1529 result = makeStringInfo();
1531 array_to_json_internal(array, result, use_line_feeds);
1533 PG_RETURN_TEXT_P(cstring_to_text(result->data));
1537 * SQL function row_to_json(row)
1540 row_to_json(PG_FUNCTION_ARGS)
1542 Datum array = PG_GETARG_DATUM(0);
1545 result = makeStringInfo();
1547 composite_to_json(array, result, false);
1549 PG_RETURN_TEXT_P(cstring_to_text(result->data));
1553 * SQL function row_to_json(row, prettybool)
1556 row_to_json_pretty(PG_FUNCTION_ARGS)
1558 Datum array = PG_GETARG_DATUM(0);
1559 bool use_line_feeds = PG_GETARG_BOOL(1);
1562 result = makeStringInfo();
1564 composite_to_json(array, result, use_line_feeds);
1566 PG_RETURN_TEXT_P(cstring_to_text(result->data));
1570 * SQL function to_json(anyvalue)
1573 to_json(PG_FUNCTION_ARGS)
1575 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1579 TYPCATEGORY tcategory;
1582 Oid castfunc = InvalidOid;
1584 if (val_type == InvalidOid)
1586 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1587 errmsg("could not determine input data type")));
1590 result = makeStringInfo();
1592 orig_val = PG_ARGISNULL(0) ? (Datum) 0 : PG_GETARG_DATUM(0);
1594 getTypeOutputInfo(val_type, &typoutput, &typisvarlena);
1596 if (val_type > FirstNormalObjectId)
1599 Form_pg_cast castForm;
1601 tuple = SearchSysCache2(CASTSOURCETARGET,
1602 ObjectIdGetDatum(val_type),
1603 ObjectIdGetDatum(JSONOID));
1604 if (HeapTupleIsValid(tuple))
1606 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1608 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1609 castfunc = typoutput = castForm->castfunc;
1611 ReleaseSysCache(tuple);
1615 if (castfunc != InvalidOid)
1616 tcategory = TYPCATEGORY_JSON_CAST;
1617 else if (val_type == RECORDARRAYOID)
1618 tcategory = TYPCATEGORY_ARRAY;
1619 else if (val_type == RECORDOID)
1620 tcategory = TYPCATEGORY_COMPOSITE;
1621 else if (val_type == JSONOID)
1622 tcategory = TYPCATEGORY_JSON;
1624 tcategory = TypeCategory(val_type);
1627 * If we have a toasted datum, forcibly detoast it here to avoid memory
1628 * leakage inside the type's output routine.
1630 if (typisvarlena && orig_val != (Datum) 0)
1631 val = PointerGetDatum(PG_DETOAST_DATUM(orig_val));
1635 datum_to_json(val, false, result, tcategory, typoutput);
1637 /* Clean up detoasted copy, if any */
1638 if (val != orig_val)
1639 pfree(DatumGetPointer(val));
1641 PG_RETURN_TEXT_P(cstring_to_text(result->data));
1645 * json_agg transition function
1648 json_agg_transfn(PG_FUNCTION_ARGS)
1650 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1651 MemoryContext aggcontext,
1656 TYPCATEGORY tcategory;
1659 Oid castfunc = InvalidOid;
1661 if (val_type == InvalidOid)
1663 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1664 errmsg("could not determine input data type")));
1666 if (!AggCheckCallContext(fcinfo, &aggcontext))
1668 /* cannot be called directly because of internal-type argument */
1669 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1672 if (PG_ARGISNULL(0))
1675 * Make this StringInfo in a context where it will persist for the
1676 * duration off the aggregate call. It's only needed for this initial
1677 * piece, as the StringInfo routines make sure they use the right
1678 * context to enlarge the object if necessary.
1680 oldcontext = MemoryContextSwitchTo(aggcontext);
1681 state = makeStringInfo();
1682 MemoryContextSwitchTo(oldcontext);
1684 appendStringInfoChar(state, '[');
1688 state = (StringInfo) PG_GETARG_POINTER(0);
1689 appendStringInfoString(state, ", ");
1692 /* fast path for NULLs */
1693 if (PG_ARGISNULL(1))
1695 orig_val = (Datum) 0;
1696 datum_to_json(orig_val, true, state, 0, InvalidOid);
1697 PG_RETURN_POINTER(state);
1701 orig_val = PG_GETARG_DATUM(1);
1703 getTypeOutputInfo(val_type, &typoutput, &typisvarlena);
1705 if (val_type > FirstNormalObjectId)
1708 Form_pg_cast castForm;
1710 tuple = SearchSysCache2(CASTSOURCETARGET,
1711 ObjectIdGetDatum(val_type),
1712 ObjectIdGetDatum(JSONOID));
1713 if (HeapTupleIsValid(tuple))
1715 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1717 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1718 castfunc = typoutput = castForm->castfunc;
1720 ReleaseSysCache(tuple);
1724 if (castfunc != InvalidOid)
1725 tcategory = TYPCATEGORY_JSON_CAST;
1726 else if (val_type == RECORDARRAYOID)
1727 tcategory = TYPCATEGORY_ARRAY;
1728 else if (val_type == RECORDOID)
1729 tcategory = TYPCATEGORY_COMPOSITE;
1730 else if (val_type == JSONOID)
1731 tcategory = TYPCATEGORY_JSON;
1733 tcategory = TypeCategory(val_type);
1736 * If we have a toasted datum, forcibly detoast it here to avoid memory
1737 * leakage inside the type's output routine.
1740 val = PointerGetDatum(PG_DETOAST_DATUM(orig_val));
1744 if (!PG_ARGISNULL(0) &&
1745 (tcategory == TYPCATEGORY_ARRAY || tcategory == TYPCATEGORY_COMPOSITE))
1747 appendStringInfoString(state, "\n ");
1750 datum_to_json(val, false, state, tcategory, typoutput);
1752 /* Clean up detoasted copy, if any */
1753 if (val != orig_val)
1754 pfree(DatumGetPointer(val));
1757 * The transition type for array_agg() is declared to be "internal", which
1758 * is a pass-by-value type the same size as a pointer. So we can safely
1759 * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
1761 PG_RETURN_POINTER(state);
1765 * json_agg final function
1768 json_agg_finalfn(PG_FUNCTION_ARGS)
1772 /* cannot be called directly because of internal-type argument */
1773 Assert(AggCheckCallContext(fcinfo, NULL));
1775 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1780 appendStringInfoChar(state, ']');
1782 PG_RETURN_TEXT_P(cstring_to_text(state->data));
1786 * Produce a JSON string literal, properly escaping characters in the text.
1789 escape_json(StringInfo buf, const char *str)
1793 appendStringInfoCharMacro(buf, '\"');
1794 for (p = str; *p; p++)
1799 appendStringInfoString(buf, "\\b");
1802 appendStringInfoString(buf, "\\f");
1805 appendStringInfoString(buf, "\\n");
1808 appendStringInfoString(buf, "\\r");
1811 appendStringInfoString(buf, "\\t");
1814 appendStringInfoString(buf, "\\\"");
1817 appendStringInfoString(buf, "\\\\");
1820 if ((unsigned char) *p < ' ')
1821 appendStringInfo(buf, "\\u%04x", (int) *p);
1823 appendStringInfoCharMacro(buf, *p);
1827 appendStringInfoCharMacro(buf, '\"');