1 /*-------------------------------------------------------------------------
4 * JSON data type support.
6 * Portions Copyright (c) 1996-2015, 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"
20 #include "lib/stringinfo.h"
21 #include "libpq/pqformat.h"
22 #include "mb/pg_wchar.h"
23 #include "miscadmin.h"
24 #include "parser/parse_coerce.h"
25 #include "utils/array.h"
26 #include "utils/builtins.h"
27 #include "utils/date.h"
28 #include "utils/datetime.h"
29 #include "utils/lsyscache.h"
30 #include "utils/json.h"
31 #include "utils/jsonapi.h"
32 #include "utils/typcache.h"
33 #include "utils/syscache.h"
35 /* String to output for infinite dates and timestamps */
36 #define DT_INFINITY "\"infinity\""
39 * The context of the parser is maintained by the recursive descent
40 * mechanism, but is passed explicitly to the error reporting routine
41 * for better diagnostics.
43 typedef enum /* contexts of JSON parser */
45 JSON_PARSE_VALUE, /* expecting a value */
46 JSON_PARSE_STRING, /* expecting a string (for a field name) */
47 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
48 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
49 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
50 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
51 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
52 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
53 JSON_PARSE_END /* saw the end of a document, expect nothing */
56 typedef enum /* type categories for datum_to_json */
58 JSONTYPE_NULL, /* null, so we didn't bother to identify */
59 JSONTYPE_BOOL, /* boolean (built-in types only) */
60 JSONTYPE_NUMERIC, /* numeric (ditto) */
61 JSONTYPE_DATE, /* we use special formatting for datetimes */
64 JSONTYPE_JSON, /* JSON itself (and JSONB) */
65 JSONTYPE_ARRAY, /* array */
66 JSONTYPE_COMPOSITE, /* composite */
67 JSONTYPE_CAST, /* something with an explicit cast to JSON */
68 JSONTYPE_OTHER /* all else */
71 typedef struct JsonAggState
74 JsonTypeCategory key_category;
76 JsonTypeCategory val_category;
80 static inline void json_lex(JsonLexContext *lex);
81 static inline void json_lex_string(JsonLexContext *lex);
82 static inline void json_lex_number(JsonLexContext *lex, char *s, bool *num_err);
83 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
84 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
85 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
86 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
87 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
88 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
89 static void report_invalid_token(JsonLexContext *lex);
90 static int report_json_context(JsonLexContext *lex);
91 static char *extract_mb_char(char *s);
92 static void composite_to_json(Datum composite, StringInfo result,
94 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
95 Datum *vals, bool *nulls, int *valcount,
96 JsonTypeCategory tcategory, Oid outfuncoid,
98 static void array_to_json_internal(Datum array, StringInfo result,
100 static void json_categorize_type(Oid typoid,
101 JsonTypeCategory *tcategory,
103 static void datum_to_json(Datum val, bool is_null, StringInfo result,
104 JsonTypeCategory tcategory, Oid outfuncoid,
106 static void add_json(Datum val, bool is_null, StringInfo result,
107 Oid val_type, bool key_scalar);
108 static text *catenate_stringinfo_string(StringInfo buffer, const char *addon);
110 /* the null action object used for pure validation */
111 static JsonSemAction nullSemAction =
113 NULL, NULL, NULL, NULL, NULL,
114 NULL, NULL, NULL, NULL, NULL
117 /* Recursive Descent parser support routines */
122 * what is the current look_ahead token?
124 static inline JsonTokenType
125 lex_peek(JsonLexContext *lex)
127 return lex->token_type;
133 * accept the look_ahead token and move the lexer to the next token if the
134 * look_ahead token matches the token parameter. In that case, and if required,
135 * also hand back the de-escaped lexeme.
137 * returns true if the token matched, false otherwise.
140 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
142 if (lex->token_type == token)
146 if (lex->token_type == JSON_TOKEN_STRING)
148 if (lex->strval != NULL)
149 *lexeme = pstrdup(lex->strval->data);
153 int len = (lex->token_terminator - lex->token_start);
154 char *tokstr = palloc(len + 1);
156 memcpy(tokstr, lex->token_start, len);
170 * move the lexer to the next token if the current look_ahead token matches
171 * the parameter token. Otherwise, report an error.
174 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
176 if (!lex_accept(lex, token, NULL))
177 report_parse_error(ctx, lex);
180 /* chars to consider as part of an alphanumeric token */
181 #define JSON_ALPHANUMERIC_CHAR(c) \
182 (((c) >= 'a' && (c) <= 'z') || \
183 ((c) >= 'A' && (c) <= 'Z') || \
184 ((c) >= '0' && (c) <= '9') || \
188 /* utility function to check if a string is a valid JSON number */
190 IsValidJsonNumber(const char *str, int len)
193 JsonLexContext dummy_lex;
197 * json_lex_number expects a leading '-' to have been eaten already.
199 * having to cast away the constness of str is ugly, but there's not much
204 dummy_lex.input = (char *) str + 1;
205 dummy_lex.input_length = len - 1;
209 dummy_lex.input = (char *) str;
210 dummy_lex.input_length = len;
213 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
215 return !numeric_error;
222 json_in(PG_FUNCTION_ARGS)
224 char *json = PG_GETARG_CSTRING(0);
225 text *result = cstring_to_text(json);
229 lex = makeJsonLexContext(result, false);
230 pg_parse_json(lex, &nullSemAction);
232 /* Internal representation is the same as text, for now */
233 PG_RETURN_TEXT_P(result);
240 json_out(PG_FUNCTION_ARGS)
242 /* we needn't detoast because text_to_cstring will handle that */
243 Datum txt = PG_GETARG_DATUM(0);
245 PG_RETURN_CSTRING(TextDatumGetCString(txt));
252 json_send(PG_FUNCTION_ARGS)
254 text *t = PG_GETARG_TEXT_PP(0);
257 pq_begintypsend(&buf);
258 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
259 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
266 json_recv(PG_FUNCTION_ARGS)
268 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
273 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
276 lex = makeJsonLexContextCstringLen(str, nbytes, false);
277 pg_parse_json(lex, &nullSemAction);
279 PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
285 * lex constructor, with or without StringInfo object
286 * for de-escaped lexemes.
288 * Without is better as it makes the processing faster, so only make one
289 * if really required.
291 * If you already have the json as a text* value, use the first of these
292 * functions, otherwise use makeJsonLexContextCstringLen().
295 makeJsonLexContext(text *json, bool need_escapes)
297 return makeJsonLexContextCstringLen(VARDATA(json),
298 VARSIZE(json) - VARHDRSZ,
303 makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
305 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
307 lex->input = lex->token_terminator = lex->line_start = json;
308 lex->line_number = 1;
309 lex->input_length = len;
311 lex->strval = makeStringInfo();
318 * Publicly visible entry point for the JSON parser.
320 * lex is a lexing context, set up for the json to be processed by calling
321 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
322 * action routines to be called at appropriate spots during parsing, and a
323 * pointer to a state object to be passed to those routines.
326 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
330 /* get the initial token */
335 /* parse by recursive descent */
338 case JSON_TOKEN_OBJECT_START:
339 parse_object(lex, sem);
341 case JSON_TOKEN_ARRAY_START:
342 parse_array(lex, sem);
345 parse_scalar(lex, sem); /* json can be a bare scalar */
348 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
353 * json_count_array_elements
355 * Returns number of array elements in lex context at start of array token
356 * until end of array token at same nesting level.
358 * Designed to be called from array_start routines.
361 json_count_array_elements(JsonLexContext *lex)
363 JsonLexContext copylex;
367 * It's safe to do this with a shallow copy because the lexical routines
368 * don't scribble on the input. They do scribble on the other pointers etc,
369 * so doing this with a copy makes that safe.
371 memcpy(©lex, lex, sizeof(JsonLexContext));
372 copylex.strval = NULL; /* not interested in values here */
376 lex_expect(JSON_PARSE_ARRAY_START, ©lex, JSON_TOKEN_ARRAY_START);
377 if (lex_peek(©lex) != JSON_TOKEN_ARRAY_END)
382 parse_array_element(©lex, &nullSemAction);
384 while (lex_accept(©lex, JSON_TOKEN_COMMA, NULL));
386 lex_expect(JSON_PARSE_ARRAY_NEXT, ©lex, JSON_TOKEN_ARRAY_END);
392 * Recursive Descent parse routines. There is one for each structural
393 * element in a json document:
394 * - scalar (string, number, true, false, null)
401 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
404 json_scalar_action sfunc = sem->scalar;
406 JsonTokenType tok = lex_peek(lex);
408 valaddr = sfunc == NULL ? NULL : &val;
410 /* a scalar must be a string, a number, true, false, or null */
413 case JSON_TOKEN_TRUE:
414 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
416 case JSON_TOKEN_FALSE:
417 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
419 case JSON_TOKEN_NULL:
420 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
422 case JSON_TOKEN_NUMBER:
423 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
425 case JSON_TOKEN_STRING:
426 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
429 report_parse_error(JSON_PARSE_VALUE, lex);
433 (*sfunc) (sem->semstate, val, tok);
437 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
440 * An object field is "fieldname" : value where value can be a scalar,
441 * object or array. Note: in user-facing docs and error messages, we
442 * generally call a field name a "key".
445 char *fname = NULL; /* keep compiler quiet */
446 json_ofield_action ostart = sem->object_field_start;
447 json_ofield_action oend = sem->object_field_end;
449 char **fnameaddr = NULL;
452 if (ostart != NULL || oend != NULL)
455 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
456 report_parse_error(JSON_PARSE_STRING, lex);
458 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
461 isnull = tok == JSON_TOKEN_NULL;
464 (*ostart) (sem->semstate, fname, isnull);
468 case JSON_TOKEN_OBJECT_START:
469 parse_object(lex, sem);
471 case JSON_TOKEN_ARRAY_START:
472 parse_array(lex, sem);
475 parse_scalar(lex, sem);
479 (*oend) (sem->semstate, fname, isnull);
483 parse_object(JsonLexContext *lex, JsonSemAction *sem)
486 * an object is a possibly empty sequence of object fields, separated by
487 * commas and surrounded by curly braces.
489 json_struct_action ostart = sem->object_start;
490 json_struct_action oend = sem->object_end;
496 (*ostart) (sem->semstate);
499 * Data inside an object is at a higher nesting level than the object
500 * itself. Note that we increment this after we call the semantic routine
501 * for the object start and restore it before we call the routine for the
506 /* we know this will succeeed, just clearing the token */
507 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
512 case JSON_TOKEN_STRING:
513 parse_object_field(lex, sem);
514 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
515 parse_object_field(lex, sem);
517 case JSON_TOKEN_OBJECT_END:
520 /* case of an invalid initial token inside the object */
521 report_parse_error(JSON_PARSE_OBJECT_START, lex);
524 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
529 (*oend) (sem->semstate);
533 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
535 json_aelem_action astart = sem->array_element_start;
536 json_aelem_action aend = sem->array_element_end;
537 JsonTokenType tok = lex_peek(lex);
541 isnull = tok == JSON_TOKEN_NULL;
544 (*astart) (sem->semstate, isnull);
546 /* an array element is any object, array or scalar */
549 case JSON_TOKEN_OBJECT_START:
550 parse_object(lex, sem);
552 case JSON_TOKEN_ARRAY_START:
553 parse_array(lex, sem);
556 parse_scalar(lex, sem);
560 (*aend) (sem->semstate, isnull);
564 parse_array(JsonLexContext *lex, JsonSemAction *sem)
567 * an array is a possibly empty sequence of array elements, separated by
568 * commas and surrounded by square brackets.
570 json_struct_action astart = sem->array_start;
571 json_struct_action aend = sem->array_end;
576 (*astart) (sem->semstate);
579 * Data inside an array is at a higher nesting level than the array
580 * itself. Note that we increment this after we call the semantic routine
581 * for the array start and restore it before we call the routine for the
586 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
587 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
590 parse_array_element(lex, sem);
592 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
593 parse_array_element(lex, sem);
596 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
601 (*aend) (sem->semstate);
605 * Lex one token from the input stream.
608 json_lex(JsonLexContext *lex)
613 /* Skip leading whitespace. */
614 s = lex->token_terminator;
615 len = s - lex->input;
616 while (len < lex->input_length &&
617 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
624 lex->token_start = s;
626 /* Determine token type. */
627 if (len >= lex->input_length)
629 lex->token_start = NULL;
630 lex->prev_token_terminator = lex->token_terminator;
631 lex->token_terminator = s;
632 lex->token_type = JSON_TOKEN_END;
637 /* Single-character token, some kind of punctuation mark. */
639 lex->prev_token_terminator = lex->token_terminator;
640 lex->token_terminator = s + 1;
641 lex->token_type = JSON_TOKEN_OBJECT_START;
644 lex->prev_token_terminator = lex->token_terminator;
645 lex->token_terminator = s + 1;
646 lex->token_type = JSON_TOKEN_OBJECT_END;
649 lex->prev_token_terminator = lex->token_terminator;
650 lex->token_terminator = s + 1;
651 lex->token_type = JSON_TOKEN_ARRAY_START;
654 lex->prev_token_terminator = lex->token_terminator;
655 lex->token_terminator = s + 1;
656 lex->token_type = JSON_TOKEN_ARRAY_END;
659 lex->prev_token_terminator = lex->token_terminator;
660 lex->token_terminator = s + 1;
661 lex->token_type = JSON_TOKEN_COMMA;
664 lex->prev_token_terminator = lex->token_terminator;
665 lex->token_terminator = s + 1;
666 lex->token_type = JSON_TOKEN_COLON;
670 json_lex_string(lex);
671 lex->token_type = JSON_TOKEN_STRING;
674 /* Negative number. */
675 json_lex_number(lex, s + 1, NULL);
676 lex->token_type = JSON_TOKEN_NUMBER;
688 /* Positive number. */
689 json_lex_number(lex, s, NULL);
690 lex->token_type = JSON_TOKEN_NUMBER;
697 * We're not dealing with a string, number, legal
698 * punctuation mark, or end of string. The only legal
699 * tokens we might find here are true, false, and null,
700 * but for error reporting purposes we scan until we see a
701 * non-alphanumeric character. That way, we can report
702 * the whole word as an unexpected token, rather than just
703 * some unintuitive prefix thereof.
705 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
709 * We got some sort of unexpected punctuation or an
710 * otherwise unexpected character, so just complain about
711 * that one character.
715 lex->prev_token_terminator = lex->token_terminator;
716 lex->token_terminator = s + 1;
717 report_invalid_token(lex);
721 * We've got a real alphanumeric token here. If it
722 * happens to be true, false, or null, all is well. If
725 lex->prev_token_terminator = lex->token_terminator;
726 lex->token_terminator = p;
729 if (memcmp(s, "true", 4) == 0)
730 lex->token_type = JSON_TOKEN_TRUE;
731 else if (memcmp(s, "null", 4) == 0)
732 lex->token_type = JSON_TOKEN_NULL;
734 report_invalid_token(lex);
736 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
737 lex->token_type = JSON_TOKEN_FALSE;
739 report_invalid_token(lex);
742 } /* end of switch */
746 * The next token in the input stream is known to be a string; lex it.
749 json_lex_string(JsonLexContext *lex)
753 int hi_surrogate = -1;
755 if (lex->strval != NULL)
756 resetStringInfo(lex->strval);
758 Assert(lex->input_length > 0);
759 s = lex->token_start;
760 len = lex->token_start - lex->input;
765 /* Premature end of the string. */
766 if (len >= lex->input_length)
768 lex->token_terminator = s;
769 report_invalid_token(lex);
773 else if ((unsigned char) *s < 32)
775 /* Per RFC4627, these characters MUST be escaped. */
776 /* Since *s isn't printable, exclude it from the context string */
777 lex->token_terminator = s;
779 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
780 errmsg("invalid input syntax for type json"),
781 errdetail("Character with value 0x%02x must be escaped.",
783 report_json_context(lex)));
787 /* OK, we have an escape character. */
790 if (len >= lex->input_length)
792 lex->token_terminator = s;
793 report_invalid_token(lex);
800 for (i = 1; i <= 4; i++)
804 if (len >= lex->input_length)
806 lex->token_terminator = s;
807 report_invalid_token(lex);
809 else if (*s >= '0' && *s <= '9')
810 ch = (ch * 16) + (*s - '0');
811 else if (*s >= 'a' && *s <= 'f')
812 ch = (ch * 16) + (*s - 'a') + 10;
813 else if (*s >= 'A' && *s <= 'F')
814 ch = (ch * 16) + (*s - 'A') + 10;
817 lex->token_terminator = s + pg_mblen(s);
819 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
820 errmsg("invalid input syntax for type json"),
821 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
822 report_json_context(lex)));
825 if (lex->strval != NULL)
830 if (ch >= 0xd800 && ch <= 0xdbff)
832 if (hi_surrogate != -1)
834 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
835 errmsg("invalid input syntax for type json"),
836 errdetail("Unicode high surrogate must not follow a high surrogate."),
837 report_json_context(lex)));
838 hi_surrogate = (ch & 0x3ff) << 10;
841 else if (ch >= 0xdc00 && ch <= 0xdfff)
843 if (hi_surrogate == -1)
845 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
846 errmsg("invalid input syntax for type json"),
847 errdetail("Unicode low surrogate must follow a high surrogate."),
848 report_json_context(lex)));
849 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
853 if (hi_surrogate != -1)
855 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
856 errmsg("invalid input syntax for type json"),
857 errdetail("Unicode low surrogate must follow a high surrogate."),
858 report_json_context(lex)));
861 * For UTF8, replace the escape sequence by the actual
862 * utf8 character in lex->strval. Do this also for other
863 * encodings if the escape designates an ASCII character,
864 * otherwise raise an error.
869 /* We can't allow this, since our TEXT type doesn't */
871 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
872 errmsg("unsupported Unicode escape sequence"),
873 errdetail("\\u0000 cannot be converted to text."),
874 report_json_context(lex)));
876 else if (GetDatabaseEncoding() == PG_UTF8)
878 unicode_to_utf8(ch, (unsigned char *) utf8str);
879 utf8len = pg_utf_mblen((unsigned char *) utf8str);
880 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
882 else if (ch <= 0x007f)
885 * This is the only way to designate things like a
886 * form feed character in JSON, so it's useful in all
889 appendStringInfoChar(lex->strval, (char) ch);
894 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
895 errmsg("unsupported Unicode escape sequence"),
896 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
897 report_json_context(lex)));
902 else if (lex->strval != NULL)
904 if (hi_surrogate != -1)
906 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
907 errmsg("invalid input syntax for type json"),
908 errdetail("Unicode low surrogate must follow a high surrogate."),
909 report_json_context(lex)));
916 appendStringInfoChar(lex->strval, *s);
919 appendStringInfoChar(lex->strval, '\b');
922 appendStringInfoChar(lex->strval, '\f');
925 appendStringInfoChar(lex->strval, '\n');
928 appendStringInfoChar(lex->strval, '\r');
931 appendStringInfoChar(lex->strval, '\t');
934 /* Not a valid string escape, so error out. */
935 lex->token_terminator = s + pg_mblen(s);
937 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
938 errmsg("invalid input syntax for type json"),
939 errdetail("Escape sequence \"\\%s\" is invalid.",
941 report_json_context(lex)));
944 else if (strchr("\"\\/bfnrt", *s) == NULL)
947 * Simpler processing if we're not bothered about de-escaping
949 * It's very tempting to remove the strchr() call here and
950 * replace it with a switch statement, but testing so far has
951 * shown it's not a performance win.
953 lex->token_terminator = s + pg_mblen(s);
955 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
956 errmsg("invalid input syntax for type json"),
957 errdetail("Escape sequence \"\\%s\" is invalid.",
959 report_json_context(lex)));
963 else if (lex->strval != NULL)
965 if (hi_surrogate != -1)
967 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
968 errmsg("invalid input syntax for type json"),
969 errdetail("Unicode low surrogate must follow a high surrogate."),
970 report_json_context(lex)));
972 appendStringInfoChar(lex->strval, *s);
977 if (hi_surrogate != -1)
979 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
980 errmsg("invalid input syntax for type json"),
981 errdetail("Unicode low surrogate must follow a high surrogate."),
982 report_json_context(lex)));
984 /* Hooray, we found the end of the string! */
985 lex->prev_token_terminator = lex->token_terminator;
986 lex->token_terminator = s + 1;
989 /*-------------------------------------------------------------------------
990 * The next token in the input stream is known to be a number; lex it.
992 * In JSON, a number consists of four parts:
994 * (1) An optional minus sign ('-').
996 * (2) Either a single '0', or a string of one or more digits that does not
999 * (3) An optional decimal part, consisting of a period ('.') followed by
1000 * one or more digits. (Note: While this part can be omitted
1001 * completely, it's not OK to have only the decimal point without
1002 * any digits afterwards.)
1004 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
1005 * followed by '+' or '-', followed by one or more digits. (Note:
1006 * As with the decimal part, if 'e' or 'E' is present, it must be
1007 * followed by at least one digit.)
1009 * The 's' argument to this function points to the ostensible beginning
1010 * of part 2 - i.e. the character after any optional minus sign, and the
1011 * first character of the string if there is none.
1013 *-------------------------------------------------------------------------
1016 json_lex_number(JsonLexContext *lex, char *s, bool *num_err)
1022 len = s - lex->input;
1023 /* Part (1): leading sign indicator. */
1024 /* Caller already did this for us; so do nothing. */
1026 /* Part (2): parse main digit string. */
1032 else if (*s >= '1' && *s <= '9')
1038 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1043 /* Part (3): parse optional decimal portion. */
1044 if (len < lex->input_length && *s == '.')
1048 if (len == lex->input_length || *s < '0' || *s > '9')
1056 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1060 /* Part (4): parse optional exponent. */
1061 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
1065 if (len < lex->input_length && (*s == '+' || *s == '-'))
1070 if (len == lex->input_length || *s < '0' || *s > '9')
1078 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1083 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
1084 * here should be considered part of the token for error-reporting
1087 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
1090 if (num_err != NULL)
1092 /* let the caller handle the error */
1097 lex->prev_token_terminator = lex->token_terminator;
1098 lex->token_terminator = p;
1100 report_invalid_token(lex);
1105 * Report a parse error.
1107 * lex->token_start and lex->token_terminator must identify the current token.
1110 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1115 /* Handle case where the input ended prematurely. */
1116 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1118 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1119 errmsg("invalid input syntax for type json"),
1120 errdetail("The input string ended unexpectedly."),
1121 report_json_context(lex)));
1123 /* Separate out the current token. */
1124 toklen = lex->token_terminator - lex->token_start;
1125 token = palloc(toklen + 1);
1126 memcpy(token, lex->token_start, toklen);
1127 token[toklen] = '\0';
1129 /* Complain, with the appropriate detail message. */
1130 if (ctx == JSON_PARSE_END)
1132 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1133 errmsg("invalid input syntax for type json"),
1134 errdetail("Expected end of input, but found \"%s\".",
1136 report_json_context(lex)));
1141 case JSON_PARSE_VALUE:
1143 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1144 errmsg("invalid input syntax for type json"),
1145 errdetail("Expected JSON value, but found \"%s\".",
1147 report_json_context(lex)));
1149 case JSON_PARSE_STRING:
1151 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1152 errmsg("invalid input syntax for type json"),
1153 errdetail("Expected string, but found \"%s\".",
1155 report_json_context(lex)));
1157 case JSON_PARSE_ARRAY_START:
1159 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1160 errmsg("invalid input syntax for type json"),
1161 errdetail("Expected array element or \"]\", but found \"%s\".",
1163 report_json_context(lex)));
1165 case JSON_PARSE_ARRAY_NEXT:
1167 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1168 errmsg("invalid input syntax for type json"),
1169 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1171 report_json_context(lex)));
1173 case JSON_PARSE_OBJECT_START:
1175 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1176 errmsg("invalid input syntax for type json"),
1177 errdetail("Expected string or \"}\", but found \"%s\".",
1179 report_json_context(lex)));
1181 case JSON_PARSE_OBJECT_LABEL:
1183 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1184 errmsg("invalid input syntax for type json"),
1185 errdetail("Expected \":\", but found \"%s\".",
1187 report_json_context(lex)));
1189 case JSON_PARSE_OBJECT_NEXT:
1191 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1192 errmsg("invalid input syntax for type json"),
1193 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1195 report_json_context(lex)));
1197 case JSON_PARSE_OBJECT_COMMA:
1199 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1200 errmsg("invalid input syntax for type json"),
1201 errdetail("Expected string, but found \"%s\".",
1203 report_json_context(lex)));
1206 elog(ERROR, "unexpected json parse state: %d", ctx);
1212 * Report an invalid input token.
1214 * lex->token_start and lex->token_terminator must identify the token.
1217 report_invalid_token(JsonLexContext *lex)
1222 /* Separate out the offending token. */
1223 toklen = lex->token_terminator - lex->token_start;
1224 token = palloc(toklen + 1);
1225 memcpy(token, lex->token_start, toklen);
1226 token[toklen] = '\0';
1229 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1230 errmsg("invalid input syntax for type json"),
1231 errdetail("Token \"%s\" is invalid.", token),
1232 report_json_context(lex)));
1236 * Report a CONTEXT line for bogus JSON input.
1238 * lex->token_terminator must be set to identify the spot where we detected
1239 * the error. Note that lex->token_start might be NULL, in case we recognized
1242 * The return value isn't meaningful, but we make it non-void so that this
1243 * can be invoked inside ereport().
1246 report_json_context(JsonLexContext *lex)
1248 const char *context_start;
1249 const char *context_end;
1250 const char *line_start;
1257 /* Choose boundaries for the part of the input we will display */
1258 context_start = lex->input;
1259 context_end = lex->token_terminator;
1260 line_start = context_start;
1264 /* Always advance over newlines */
1265 if (context_start < context_end && *context_start == '\n')
1268 line_start = context_start;
1272 /* Otherwise, done as soon as we are close enough to context_end */
1273 if (context_end - context_start < 50)
1275 /* Advance to next multibyte character */
1276 if (IS_HIGHBIT_SET(*context_start))
1277 context_start += pg_mblen(context_start);
1283 * We add "..." to indicate that the excerpt doesn't start at the
1284 * beginning of the line ... but if we're within 3 characters of the
1285 * beginning of the line, we might as well just show the whole line.
1287 if (context_start - line_start <= 3)
1288 context_start = line_start;
1290 /* Get a null-terminated copy of the data to present */
1291 ctxtlen = context_end - context_start;
1292 ctxt = palloc(ctxtlen + 1);
1293 memcpy(ctxt, context_start, ctxtlen);
1294 ctxt[ctxtlen] = '\0';
1297 * Show the context, prefixing "..." if not starting at start of line, and
1298 * suffixing "..." if not ending at end of line.
1300 prefix = (context_start > line_start) ? "..." : "";
1301 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1303 return errcontext("JSON data, line %d: %s%s%s",
1304 line_number, prefix, ctxt, suffix);
1308 * Extract a single, possibly multi-byte char from the input string.
1311 extract_mb_char(char *s)
1317 res = palloc(len + 1);
1318 memcpy(res, s, len);
1325 * Determine how we want to print values of a given type in datum_to_json.
1327 * Given the datatype OID, return its JsonTypeCategory, as well as the type's
1328 * output function OID. If the returned category is JSONTYPE_CAST, we
1329 * return the OID of the type->JSON cast function instead.
1332 json_categorize_type(Oid typoid,
1333 JsonTypeCategory *tcategory,
1338 /* Look through any domain */
1339 typoid = getBaseType(typoid);
1341 *outfuncoid = InvalidOid;
1344 * We need to get the output function for everything except date and
1345 * timestamp types, array and composite types, booleans, and non-builtin
1346 * types where there's a cast to json.
1352 *tcategory = JSONTYPE_BOOL;
1361 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1362 *tcategory = JSONTYPE_NUMERIC;
1366 *tcategory = JSONTYPE_DATE;
1370 *tcategory = JSONTYPE_TIMESTAMP;
1373 case TIMESTAMPTZOID:
1374 *tcategory = JSONTYPE_TIMESTAMPTZ;
1379 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1380 *tcategory = JSONTYPE_JSON;
1384 /* Check for arrays and composites */
1385 if (OidIsValid(get_element_type(typoid)))
1386 *tcategory = JSONTYPE_ARRAY;
1387 else if (type_is_rowtype(typoid))
1388 *tcategory = JSONTYPE_COMPOSITE;
1391 /* It's probably the general case ... */
1392 *tcategory = JSONTYPE_OTHER;
1393 /* but let's look for a cast to json, if it's not built-in */
1394 if (typoid >= FirstNormalObjectId)
1397 CoercionPathType ctype;
1399 ctype = find_coercion_pathway(JSONOID, typoid,
1402 if (ctype == COERCION_PATH_FUNC && OidIsValid(castfunc))
1404 *tcategory = JSONTYPE_CAST;
1405 *outfuncoid = castfunc;
1409 /* non builtin type with no cast */
1410 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1415 /* any other builtin type */
1416 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1424 * Turn a Datum into JSON text, appending the string to "result".
1426 * tcategory and outfuncoid are from a previous call to json_categorize_type,
1427 * except that if is_null is true then they can be invalid.
1429 * If key_scalar is true, the value is being printed as a key, so insist
1430 * it's of an acceptable type, and force it to be quoted.
1433 datum_to_json(Datum val, bool is_null, StringInfo result,
1434 JsonTypeCategory tcategory, Oid outfuncoid,
1440 check_stack_depth();
1442 /* callers are expected to ensure that null keys are not passed in */
1443 Assert(!(key_scalar && is_null));
1447 appendStringInfoString(result, "null");
1452 (tcategory == JSONTYPE_ARRAY ||
1453 tcategory == JSONTYPE_COMPOSITE ||
1454 tcategory == JSONTYPE_JSON ||
1455 tcategory == JSONTYPE_CAST))
1457 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1458 errmsg("key value must be scalar, not array, composite, or json")));
1462 case JSONTYPE_ARRAY:
1463 array_to_json_internal(val, result, false);
1465 case JSONTYPE_COMPOSITE:
1466 composite_to_json(val, result, false);
1469 outputstr = DatumGetBool(val) ? "true" : "false";
1471 escape_json(result, outputstr);
1473 appendStringInfoString(result, outputstr);
1475 case JSONTYPE_NUMERIC:
1476 outputstr = OidOutputFunctionCall(outfuncoid, val);
1479 * Don't call escape_json for a non-key if it's a valid JSON
1482 if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
1483 appendStringInfoString(result, outputstr);
1485 escape_json(result, outputstr);
1492 char buf[MAXDATELEN + 1];
1494 date = DatumGetDateADT(val);
1496 if (DATE_NOT_FINITE(date))
1498 /* we have to format infinity ourselves */
1499 appendStringInfoString(result, DT_INFINITY);
1503 j2date(date + POSTGRES_EPOCH_JDATE,
1504 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1505 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1506 appendStringInfo(result, "\"%s\"", buf);
1510 case JSONTYPE_TIMESTAMP:
1512 Timestamp timestamp;
1515 char buf[MAXDATELEN + 1];
1517 timestamp = DatumGetTimestamp(val);
1519 if (TIMESTAMP_NOT_FINITE(timestamp))
1521 /* we have to format infinity ourselves */
1522 appendStringInfoString(result, DT_INFINITY);
1524 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1526 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
1527 appendStringInfo(result, "\"%s\"", buf);
1531 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1532 errmsg("timestamp out of range")));
1535 case JSONTYPE_TIMESTAMPTZ:
1537 TimestampTz timestamp;
1541 const char *tzn = NULL;
1542 char buf[MAXDATELEN + 1];
1544 timestamp = DatumGetTimestamp(val);
1546 if (TIMESTAMP_NOT_FINITE(timestamp))
1548 /* we have to format infinity ourselves */
1549 appendStringInfoString(result, DT_INFINITY);
1551 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1553 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
1554 appendStringInfo(result, "\"%s\"", buf);
1558 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1559 errmsg("timestamp out of range")));
1563 /* JSON and JSONB output will already be escaped */
1564 outputstr = OidOutputFunctionCall(outfuncoid, val);
1565 appendStringInfoString(result, outputstr);
1569 /* outfuncoid refers to a cast function, not an output function */
1570 jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
1571 outputstr = text_to_cstring(jsontext);
1572 appendStringInfoString(result, outputstr);
1577 outputstr = OidOutputFunctionCall(outfuncoid, val);
1578 escape_json(result, outputstr);
1585 * Process a single dimension of an array.
1586 * If it's the innermost dimension, output the values, otherwise call
1587 * ourselves recursively to process the next dimension.
1590 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1591 bool *nulls, int *valcount, JsonTypeCategory tcategory,
1592 Oid outfuncoid, bool use_line_feeds)
1597 Assert(dim < ndims);
1599 sep = use_line_feeds ? ",\n " : ",";
1601 appendStringInfoChar(result, '[');
1603 for (i = 1; i <= dims[dim]; i++)
1606 appendStringInfoString(result, sep);
1608 if (dim + 1 == ndims)
1610 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1617 * Do we want line feeds on inner dimensions of arrays? For now
1620 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1621 valcount, tcategory, outfuncoid, false);
1625 appendStringInfoChar(result, ']');
1629 * Turn an array into JSON.
1632 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1634 ArrayType *v = DatumGetArrayTypeP(array);
1635 Oid element_type = ARR_ELEMTYPE(v);
1645 JsonTypeCategory tcategory;
1650 nitems = ArrayGetNItems(ndim, dim);
1654 appendStringInfoString(result, "[]");
1658 get_typlenbyvalalign(element_type,
1659 &typlen, &typbyval, &typalign);
1661 json_categorize_type(element_type,
1662 &tcategory, &outfuncoid);
1664 deconstruct_array(v, element_type, typlen, typbyval,
1665 typalign, &elements, &nulls,
1668 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1669 outfuncoid, use_line_feeds);
1676 * Turn a composite / record into JSON.
1679 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1685 HeapTupleData tmptup,
1688 bool needsep = false;
1691 sep = use_line_feeds ? ",\n " : ",";
1693 td = DatumGetHeapTupleHeader(composite);
1695 /* Extract rowtype info and find a tupdesc */
1696 tupType = HeapTupleHeaderGetTypeId(td);
1697 tupTypmod = HeapTupleHeaderGetTypMod(td);
1698 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1700 /* Build a temporary HeapTuple control structure */
1701 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1705 appendStringInfoChar(result, '{');
1707 for (i = 0; i < tupdesc->natts; i++)
1712 JsonTypeCategory tcategory;
1715 if (tupdesc->attrs[i]->attisdropped)
1719 appendStringInfoString(result, sep);
1722 attname = NameStr(tupdesc->attrs[i]->attname);
1723 escape_json(result, attname);
1724 appendStringInfoChar(result, ':');
1726 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1730 tcategory = JSONTYPE_NULL;
1731 outfuncoid = InvalidOid;
1734 json_categorize_type(tupdesc->attrs[i]->atttypid,
1735 &tcategory, &outfuncoid);
1737 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1740 appendStringInfoChar(result, '}');
1741 ReleaseTupleDesc(tupdesc);
1745 * Append JSON text for "val" to "result".
1747 * This is just a thin wrapper around datum_to_json. If the same type will be
1748 * printed many times, avoid using this; better to do the json_categorize_type
1749 * lookups only once.
1752 add_json(Datum val, bool is_null, StringInfo result,
1753 Oid val_type, bool key_scalar)
1755 JsonTypeCategory tcategory;
1758 if (val_type == InvalidOid)
1760 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1761 errmsg("could not determine input data type")));
1765 tcategory = JSONTYPE_NULL;
1766 outfuncoid = InvalidOid;
1769 json_categorize_type(val_type,
1770 &tcategory, &outfuncoid);
1772 datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1776 * SQL function array_to_json(row)
1779 array_to_json(PG_FUNCTION_ARGS)
1781 Datum array = PG_GETARG_DATUM(0);
1784 result = makeStringInfo();
1786 array_to_json_internal(array, result, false);
1788 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1792 * SQL function array_to_json(row, prettybool)
1795 array_to_json_pretty(PG_FUNCTION_ARGS)
1797 Datum array = PG_GETARG_DATUM(0);
1798 bool use_line_feeds = PG_GETARG_BOOL(1);
1801 result = makeStringInfo();
1803 array_to_json_internal(array, result, use_line_feeds);
1805 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1809 * SQL function row_to_json(row)
1812 row_to_json(PG_FUNCTION_ARGS)
1814 Datum array = PG_GETARG_DATUM(0);
1817 result = makeStringInfo();
1819 composite_to_json(array, result, false);
1821 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1825 * SQL function row_to_json(row, prettybool)
1828 row_to_json_pretty(PG_FUNCTION_ARGS)
1830 Datum array = PG_GETARG_DATUM(0);
1831 bool use_line_feeds = PG_GETARG_BOOL(1);
1834 result = makeStringInfo();
1836 composite_to_json(array, result, use_line_feeds);
1838 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1842 * SQL function to_json(anyvalue)
1845 to_json(PG_FUNCTION_ARGS)
1847 Datum val = PG_GETARG_DATUM(0);
1848 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1850 JsonTypeCategory tcategory;
1853 if (val_type == InvalidOid)
1855 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1856 errmsg("could not determine input data type")));
1858 json_categorize_type(val_type,
1859 &tcategory, &outfuncoid);
1861 result = makeStringInfo();
1863 datum_to_json(val, false, result, tcategory, outfuncoid, false);
1865 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1869 * json_agg transition function
1871 * aggregate input column as a json array value.
1874 json_agg_transfn(PG_FUNCTION_ARGS)
1876 MemoryContext aggcontext,
1878 JsonAggState *state;
1881 if (!AggCheckCallContext(fcinfo, &aggcontext))
1883 /* cannot be called directly because of internal-type argument */
1884 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1887 if (PG_ARGISNULL(0))
1889 Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1891 if (arg_type == InvalidOid)
1893 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1894 errmsg("could not determine input data type")));
1897 * Make this state object in a context where it will persist for the
1898 * duration of the aggregate call. MemoryContextSwitchTo is only
1899 * needed the first time, as the StringInfo routines make sure they
1900 * use the right context to enlarge the object if necessary.
1902 oldcontext = MemoryContextSwitchTo(aggcontext);
1903 state = (JsonAggState *) palloc(sizeof(JsonAggState));
1904 state->str = makeStringInfo();
1905 MemoryContextSwitchTo(oldcontext);
1907 appendStringInfoChar(state->str, '[');
1908 json_categorize_type(arg_type,&state->val_category,
1909 &state->val_output_func);
1913 state = (JsonAggState *) PG_GETARG_POINTER(0);
1914 appendStringInfoString(state->str, ", ");
1917 /* fast path for NULLs */
1918 if (PG_ARGISNULL(1))
1920 datum_to_json((Datum) 0, true, state->str, JSONTYPE_NULL,
1922 PG_RETURN_POINTER(state);
1925 val = PG_GETARG_DATUM(1);
1927 /* add some whitespace if structured type and not first item */
1928 if (!PG_ARGISNULL(0) &&
1929 (state->val_category == JSONTYPE_ARRAY ||
1930 state->val_category == JSONTYPE_COMPOSITE))
1932 appendStringInfoString(state->str, "\n ");
1935 datum_to_json(val, false, state->str, state->val_category,
1936 state->val_output_func, false);
1939 * The transition type for array_agg() is declared to be "internal", which
1940 * is a pass-by-value type the same size as a pointer. So we can safely
1941 * pass the JsonAggState pointer through nodeAgg.c's machinations.
1943 PG_RETURN_POINTER(state);
1947 * json_agg final function
1950 json_agg_finalfn(PG_FUNCTION_ARGS)
1952 JsonAggState *state;
1954 /* cannot be called directly because of internal-type argument */
1955 Assert(AggCheckCallContext(fcinfo, NULL));
1957 state = PG_ARGISNULL(0) ?
1959 (JsonAggState *) PG_GETARG_POINTER(0);
1961 /* NULL result for no rows in, as is standard with aggregates */
1965 /* Else return state with appropriate array terminator added */
1966 PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, "]"));
1970 * json_object_agg transition function.
1972 * aggregate two input columns as a single json object value.
1975 json_object_agg_transfn(PG_FUNCTION_ARGS)
1977 MemoryContext aggcontext,
1979 JsonAggState *state;
1982 if (!AggCheckCallContext(fcinfo, &aggcontext))
1984 /* cannot be called directly because of internal-type argument */
1985 elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
1988 if (PG_ARGISNULL(0))
1993 * Make the StringInfo in a context where it will persist for the
1994 * duration of the aggregate call. Switching context is only needed
1995 * for this initial step, as the StringInfo routines make sure they
1996 * use the right context to enlarge the object if necessary.
1998 oldcontext = MemoryContextSwitchTo(aggcontext);
1999 state = (JsonAggState *) palloc(sizeof(JsonAggState));
2000 state->str = makeStringInfo();
2001 MemoryContextSwitchTo(oldcontext);
2003 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
2005 if (arg_type == InvalidOid)
2007 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2008 errmsg("could not determine data type for argument 1")));
2010 json_categorize_type(arg_type,&state->key_category,
2011 &state->key_output_func);
2013 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
2015 if (arg_type == InvalidOid)
2017 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2018 errmsg("could not determine data type for argument 2")));
2020 json_categorize_type(arg_type,&state->val_category,
2021 &state->val_output_func);
2023 appendStringInfoString(state->str, "{ ");
2027 state = (JsonAggState *) PG_GETARG_POINTER(0);
2028 appendStringInfoString(state->str, ", ");
2032 * Note: since json_object_agg() is declared as taking type "any", the
2033 * parser will not do any type conversion on unknown-type literals (that
2034 * is, undecorated strings or NULLs). Such values will arrive here as
2035 * type UNKNOWN, which fortunately does not matter to us, since
2036 * unknownout() works fine.
2039 if (PG_ARGISNULL(1))
2041 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2042 errmsg("field name must not be null")));
2044 arg = PG_GETARG_DATUM(1);
2046 datum_to_json(arg, false, state->str, state->key_category,
2047 state->key_output_func, true);
2049 appendStringInfoString(state->str, " : ");
2051 if (PG_ARGISNULL(2))
2054 arg = PG_GETARG_DATUM(2);
2056 datum_to_json(arg, PG_ARGISNULL(2), state->str, state->val_category,
2057 state->val_output_func, false);
2059 PG_RETURN_POINTER(state);
2063 * json_object_agg final function.
2066 json_object_agg_finalfn(PG_FUNCTION_ARGS)
2068 JsonAggState *state;
2070 /* cannot be called directly because of internal-type argument */
2071 Assert(AggCheckCallContext(fcinfo, NULL));
2073 state = PG_ARGISNULL(0) ? NULL : (JsonAggState *) PG_GETARG_POINTER(0);
2075 /* NULL result for no rows in, as is standard with aggregates */
2079 /* Else return state with appropriate object terminator added */
2080 PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, " }"));
2084 * Helper function for aggregates: return given StringInfo's contents plus
2085 * specified trailing string, as a text datum. We need this because aggregate
2086 * final functions are not allowed to modify the aggregate state.
2089 catenate_stringinfo_string(StringInfo buffer, const char *addon)
2091 /* custom version of cstring_to_text_with_len */
2092 int buflen = buffer->len;
2093 int addlen = strlen(addon);
2094 text *result = (text *) palloc(buflen + addlen + VARHDRSZ);
2096 SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
2097 memcpy(VARDATA(result), buffer->data, buflen);
2098 memcpy(VARDATA(result) + buflen, addon, addlen);
2104 * SQL function json_build_object(variadic "any")
2107 json_build_object(PG_FUNCTION_ARGS)
2109 int nargs = PG_NARGS();
2112 const char *sep = "";
2118 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2119 errmsg("argument list must have even number of elements"),
2120 errhint("The arguments of json_build_object() must consist of alternating keys and values.")));
2122 result = makeStringInfo();
2124 appendStringInfoChar(result, '{');
2126 for (i = 0; i < nargs; i += 2)
2129 * Note: since json_build_object() is declared as taking type "any",
2130 * the parser will not do any type conversion on unknown-type literals
2131 * (that is, undecorated strings or NULLs). Such values will arrive
2132 * here as type UNKNOWN, which fortunately does not matter to us,
2133 * since unknownout() works fine.
2135 appendStringInfoString(result, sep);
2139 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2141 if (val_type == InvalidOid)
2143 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2144 errmsg("could not determine data type for argument %d",
2147 if (PG_ARGISNULL(i))
2149 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2150 errmsg("argument %d cannot be null", i + 1),
2151 errhint("Object keys should be text.")));
2153 arg = PG_GETARG_DATUM(i);
2155 add_json(arg, false, result, val_type, true);
2157 appendStringInfoString(result, " : ");
2160 val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
2162 if (val_type == InvalidOid)
2164 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2165 errmsg("could not determine data type for argument %d",
2168 if (PG_ARGISNULL(i + 1))
2171 arg = PG_GETARG_DATUM(i + 1);
2173 add_json(arg, PG_ARGISNULL(i + 1), result, val_type, false);
2176 appendStringInfoChar(result, '}');
2178 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2182 * degenerate case of json_build_object where it gets 0 arguments.
2185 json_build_object_noargs(PG_FUNCTION_ARGS)
2187 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2191 * SQL function json_build_array(variadic "any")
2194 json_build_array(PG_FUNCTION_ARGS)
2196 int nargs = PG_NARGS();
2199 const char *sep = "";
2203 result = makeStringInfo();
2205 appendStringInfoChar(result, '[');
2207 for (i = 0; i < nargs; i++)
2210 * Note: since json_build_array() is declared as taking type "any",
2211 * the parser will not do any type conversion on unknown-type literals
2212 * (that is, undecorated strings or NULLs). Such values will arrive
2213 * here as type UNKNOWN, which fortunately does not matter to us,
2214 * since unknownout() works fine.
2216 appendStringInfoString(result, sep);
2219 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2221 if (val_type == InvalidOid)
2223 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2224 errmsg("could not determine data type for argument %d",
2227 if (PG_ARGISNULL(i))
2230 arg = PG_GETARG_DATUM(i);
2232 add_json(arg, PG_ARGISNULL(i), result, val_type, false);
2235 appendStringInfoChar(result, ']');
2237 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2241 * degenerate case of json_build_array where it gets 0 arguments.
2244 json_build_array_noargs(PG_FUNCTION_ARGS)
2246 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2250 * SQL function json_object(text[])
2252 * take a one or two dimensional array of text as key/value pairs
2253 * for a json object.
2256 json_object(PG_FUNCTION_ARGS)
2258 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2259 int ndims = ARR_NDIM(in_array);
2260 StringInfoData result;
2272 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2276 if ((ARR_DIMS(in_array)[0]) % 2)
2278 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2279 errmsg("array must have even number of elements")));
2283 if ((ARR_DIMS(in_array)[1]) != 2)
2285 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2286 errmsg("array must have two columns")));
2291 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2292 errmsg("wrong number of array subscripts")));
2295 deconstruct_array(in_array,
2296 TEXTOID, -1, false, 'i',
2297 &in_datums, &in_nulls, &in_count);
2299 count = in_count / 2;
2301 initStringInfo(&result);
2303 appendStringInfoChar(&result, '{');
2305 for (i = 0; i < count; ++i)
2307 if (in_nulls[i * 2])
2309 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2310 errmsg("null value not allowed for object key")));
2312 v = TextDatumGetCString(in_datums[i * 2]);
2314 appendStringInfoString(&result, ", ");
2315 escape_json(&result, v);
2316 appendStringInfoString(&result, " : ");
2318 if (in_nulls[i * 2 + 1])
2319 appendStringInfoString(&result, "null");
2322 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2323 escape_json(&result, v);
2328 appendStringInfoChar(&result, '}');
2333 rval = cstring_to_text_with_len(result.data, result.len);
2336 PG_RETURN_TEXT_P(rval);
2341 * SQL function json_object(text[], text[])
2343 * take separate key and value arrays of text to construct a json object
2347 json_object_two_arg(PG_FUNCTION_ARGS)
2349 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2350 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2351 int nkdims = ARR_NDIM(key_array);
2352 int nvdims = ARR_NDIM(val_array);
2353 StringInfoData result;
2364 if (nkdims > 1 || nkdims != nvdims)
2366 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2367 errmsg("wrong number of array subscripts")));
2370 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2372 deconstruct_array(key_array,
2373 TEXTOID, -1, false, 'i',
2374 &key_datums, &key_nulls, &key_count);
2376 deconstruct_array(val_array,
2377 TEXTOID, -1, false, 'i',
2378 &val_datums, &val_nulls, &val_count);
2380 if (key_count != val_count)
2382 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2383 errmsg("mismatched array dimensions")));
2385 initStringInfo(&result);
2387 appendStringInfoChar(&result, '{');
2389 for (i = 0; i < key_count; ++i)
2393 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2394 errmsg("null value not allowed for object key")));
2396 v = TextDatumGetCString(key_datums[i]);
2398 appendStringInfoString(&result, ", ");
2399 escape_json(&result, v);
2400 appendStringInfoString(&result, " : ");
2403 appendStringInfoString(&result, "null");
2406 v = TextDatumGetCString(val_datums[i]);
2407 escape_json(&result, v);
2412 appendStringInfoChar(&result, '}');
2419 rval = cstring_to_text_with_len(result.data, result.len);
2422 PG_RETURN_TEXT_P(rval);
2427 * Produce a JSON string literal, properly escaping characters in the text.
2430 escape_json(StringInfo buf, const char *str)
2434 appendStringInfoCharMacro(buf, '\"');
2435 for (p = str; *p; p++)
2440 appendStringInfoString(buf, "\\b");
2443 appendStringInfoString(buf, "\\f");
2446 appendStringInfoString(buf, "\\n");
2449 appendStringInfoString(buf, "\\r");
2452 appendStringInfoString(buf, "\\t");
2455 appendStringInfoString(buf, "\\\"");
2458 appendStringInfoString(buf, "\\\\");
2461 if ((unsigned char) *p < ' ')
2462 appendStringInfo(buf, "\\u%04x", (int) *p);
2464 appendStringInfoCharMacro(buf, *p);
2468 appendStringInfoCharMacro(buf, '\"');
2472 * SQL function json_typeof(json) -> text
2474 * Returns the type of the outermost JSON value as TEXT. Possible types are
2475 * "object", "array", "string", "number", "boolean", and "null".
2477 * Performs a single call to json_lex() to get the first token of the supplied
2478 * value. This initial token uniquely determines the value's type. As our
2479 * input must already have been validated by json_in() or json_recv(), the
2480 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2481 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2484 json_typeof(PG_FUNCTION_ARGS)
2488 JsonLexContext *lex;
2492 json = PG_GETARG_TEXT_P(0);
2493 lex = makeJsonLexContext(json, false);
2495 /* Lex exactly one token from the input and check its type. */
2497 tok = lex_peek(lex);
2500 case JSON_TOKEN_OBJECT_START:
2503 case JSON_TOKEN_ARRAY_START:
2506 case JSON_TOKEN_STRING:
2509 case JSON_TOKEN_NUMBER:
2512 case JSON_TOKEN_TRUE:
2513 case JSON_TOKEN_FALSE:
2516 case JSON_TOKEN_NULL:
2520 elog(ERROR, "unexpected json token: %d", tok);
2523 PG_RETURN_TEXT_P(cstring_to_text(type));