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 static inline void json_lex(JsonLexContext *lex);
72 static inline void json_lex_string(JsonLexContext *lex);
73 static inline void json_lex_number(JsonLexContext *lex, char *s, bool *num_err);
74 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
75 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
76 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
77 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
78 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
79 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
80 static void report_invalid_token(JsonLexContext *lex);
81 static int report_json_context(JsonLexContext *lex);
82 static char *extract_mb_char(char *s);
83 static void composite_to_json(Datum composite, StringInfo result,
85 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
86 Datum *vals, bool *nulls, int *valcount,
87 JsonTypeCategory tcategory, Oid outfuncoid,
89 static void array_to_json_internal(Datum array, StringInfo result,
91 static void json_categorize_type(Oid typoid,
92 JsonTypeCategory *tcategory,
94 static void datum_to_json(Datum val, bool is_null, StringInfo result,
95 JsonTypeCategory tcategory, Oid outfuncoid,
97 static void add_json(Datum val, bool is_null, StringInfo result,
98 Oid val_type, bool key_scalar);
99 static text *catenate_stringinfo_string(StringInfo buffer, const char *addon);
101 /* the null action object used for pure validation */
102 static JsonSemAction nullSemAction =
104 NULL, NULL, NULL, NULL, NULL,
105 NULL, NULL, NULL, NULL, NULL
108 /* Recursive Descent parser support routines */
113 * what is the current look_ahead token?
115 static inline JsonTokenType
116 lex_peek(JsonLexContext *lex)
118 return lex->token_type;
124 * accept the look_ahead token and move the lexer to the next token if the
125 * look_ahead token matches the token parameter. In that case, and if required,
126 * also hand back the de-escaped lexeme.
128 * returns true if the token matched, false otherwise.
131 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
133 if (lex->token_type == token)
137 if (lex->token_type == JSON_TOKEN_STRING)
139 if (lex->strval != NULL)
140 *lexeme = pstrdup(lex->strval->data);
144 int len = (lex->token_terminator - lex->token_start);
145 char *tokstr = palloc(len + 1);
147 memcpy(tokstr, lex->token_start, len);
161 * move the lexer to the next token if the current look_ahead token matches
162 * the parameter token. Otherwise, report an error.
165 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
167 if (!lex_accept(lex, token, NULL))
168 report_parse_error(ctx, lex);
171 /* chars to consider as part of an alphanumeric token */
172 #define JSON_ALPHANUMERIC_CHAR(c) \
173 (((c) >= 'a' && (c) <= 'z') || \
174 ((c) >= 'A' && (c) <= 'Z') || \
175 ((c) >= '0' && (c) <= '9') || \
179 /* utility function to check if a string is a valid JSON number */
181 IsValidJsonNumber(const char *str, int len)
184 JsonLexContext dummy_lex;
188 * json_lex_number expects a leading '-' to have been eaten already.
190 * having to cast away the constness of str is ugly, but there's not much
195 dummy_lex.input = (char *) str + 1;
196 dummy_lex.input_length = len - 1;
200 dummy_lex.input = (char *) str;
201 dummy_lex.input_length = len;
204 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
206 return !numeric_error;
213 json_in(PG_FUNCTION_ARGS)
215 char *json = PG_GETARG_CSTRING(0);
216 text *result = cstring_to_text(json);
220 lex = makeJsonLexContext(result, false);
221 pg_parse_json(lex, &nullSemAction);
223 /* Internal representation is the same as text, for now */
224 PG_RETURN_TEXT_P(result);
231 json_out(PG_FUNCTION_ARGS)
233 /* we needn't detoast because text_to_cstring will handle that */
234 Datum txt = PG_GETARG_DATUM(0);
236 PG_RETURN_CSTRING(TextDatumGetCString(txt));
243 json_send(PG_FUNCTION_ARGS)
245 text *t = PG_GETARG_TEXT_PP(0);
248 pq_begintypsend(&buf);
249 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
250 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
257 json_recv(PG_FUNCTION_ARGS)
259 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
264 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
267 lex = makeJsonLexContextCstringLen(str, nbytes, false);
268 pg_parse_json(lex, &nullSemAction);
270 PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
276 * lex constructor, with or without StringInfo object
277 * for de-escaped lexemes.
279 * Without is better as it makes the processing faster, so only make one
280 * if really required.
282 * If you already have the json as a text* value, use the first of these
283 * functions, otherwise use makeJsonLexContextCstringLen().
286 makeJsonLexContext(text *json, bool need_escapes)
288 return makeJsonLexContextCstringLen(VARDATA(json),
289 VARSIZE(json) - VARHDRSZ,
294 makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
296 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
298 lex->input = lex->token_terminator = lex->line_start = json;
299 lex->line_number = 1;
300 lex->input_length = len;
302 lex->strval = makeStringInfo();
309 * Publicly visible entry point for the JSON parser.
311 * lex is a lexing context, set up for the json to be processed by calling
312 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
313 * action routines to be called at appropriate spots during parsing, and a
314 * pointer to a state object to be passed to those routines.
317 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
321 /* get the initial token */
326 /* parse by recursive descent */
329 case JSON_TOKEN_OBJECT_START:
330 parse_object(lex, sem);
332 case JSON_TOKEN_ARRAY_START:
333 parse_array(lex, sem);
336 parse_scalar(lex, sem); /* json can be a bare scalar */
339 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
344 * json_count_array_elements
346 * Returns number of array elements in lex context at start of array token
347 * until end of array token at same nesting level.
349 * Designed to be called from array_start routines.
352 json_count_array_elements(JsonLexContext *lex)
354 JsonLexContext copylex;
358 * It's safe to do this with a shallow copy because the lexical routines
359 * don't scribble on the input. They do scribble on the other pointers etc,
360 * so doing this with a copy makes that safe.
362 memcpy(©lex, lex, sizeof(JsonLexContext));
363 copylex.strval = NULL; /* not interested in values here */
367 lex_expect(JSON_PARSE_ARRAY_START, ©lex, JSON_TOKEN_ARRAY_START);
368 if (lex_peek(©lex) != JSON_TOKEN_ARRAY_END)
373 parse_array_element(©lex, &nullSemAction);
375 while (lex_accept(©lex, JSON_TOKEN_COMMA, NULL));
377 lex_expect(JSON_PARSE_ARRAY_NEXT, ©lex, JSON_TOKEN_ARRAY_END);
383 * Recursive Descent parse routines. There is one for each structural
384 * element in a json document:
385 * - scalar (string, number, true, false, null)
392 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
395 json_scalar_action sfunc = sem->scalar;
397 JsonTokenType tok = lex_peek(lex);
399 valaddr = sfunc == NULL ? NULL : &val;
401 /* a scalar must be a string, a number, true, false, or null */
404 case JSON_TOKEN_TRUE:
405 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
407 case JSON_TOKEN_FALSE:
408 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
410 case JSON_TOKEN_NULL:
411 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
413 case JSON_TOKEN_NUMBER:
414 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
416 case JSON_TOKEN_STRING:
417 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
420 report_parse_error(JSON_PARSE_VALUE, lex);
424 (*sfunc) (sem->semstate, val, tok);
428 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
431 * An object field is "fieldname" : value where value can be a scalar,
432 * object or array. Note: in user-facing docs and error messages, we
433 * generally call a field name a "key".
436 char *fname = NULL; /* keep compiler quiet */
437 json_ofield_action ostart = sem->object_field_start;
438 json_ofield_action oend = sem->object_field_end;
440 char **fnameaddr = NULL;
443 if (ostart != NULL || oend != NULL)
446 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
447 report_parse_error(JSON_PARSE_STRING, lex);
449 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
452 isnull = tok == JSON_TOKEN_NULL;
455 (*ostart) (sem->semstate, fname, isnull);
459 case JSON_TOKEN_OBJECT_START:
460 parse_object(lex, sem);
462 case JSON_TOKEN_ARRAY_START:
463 parse_array(lex, sem);
466 parse_scalar(lex, sem);
470 (*oend) (sem->semstate, fname, isnull);
474 parse_object(JsonLexContext *lex, JsonSemAction *sem)
477 * an object is a possibly empty sequence of object fields, separated by
478 * commas and surrounded by curly braces.
480 json_struct_action ostart = sem->object_start;
481 json_struct_action oend = sem->object_end;
485 (*ostart) (sem->semstate);
488 * Data inside an object is at a higher nesting level than the object
489 * itself. Note that we increment this after we call the semantic routine
490 * for the object start and restore it before we call the routine for the
495 /* we know this will succeeed, just clearing the token */
496 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
501 case JSON_TOKEN_STRING:
502 parse_object_field(lex, sem);
503 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
504 parse_object_field(lex, sem);
506 case JSON_TOKEN_OBJECT_END:
509 /* case of an invalid initial token inside the object */
510 report_parse_error(JSON_PARSE_OBJECT_START, lex);
513 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
518 (*oend) (sem->semstate);
522 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
524 json_aelem_action astart = sem->array_element_start;
525 json_aelem_action aend = sem->array_element_end;
526 JsonTokenType tok = lex_peek(lex);
530 isnull = tok == JSON_TOKEN_NULL;
533 (*astart) (sem->semstate, isnull);
535 /* an array element is any object, array or scalar */
538 case JSON_TOKEN_OBJECT_START:
539 parse_object(lex, sem);
541 case JSON_TOKEN_ARRAY_START:
542 parse_array(lex, sem);
545 parse_scalar(lex, sem);
549 (*aend) (sem->semstate, isnull);
553 parse_array(JsonLexContext *lex, JsonSemAction *sem)
556 * an array is a possibly empty sequence of array elements, separated by
557 * commas and surrounded by square brackets.
559 json_struct_action astart = sem->array_start;
560 json_struct_action aend = sem->array_end;
563 (*astart) (sem->semstate);
566 * Data inside an array is at a higher nesting level than the array
567 * itself. Note that we increment this after we call the semantic routine
568 * for the array start and restore it before we call the routine for the
573 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
574 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
577 parse_array_element(lex, sem);
579 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
580 parse_array_element(lex, sem);
583 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
588 (*aend) (sem->semstate);
592 * Lex one token from the input stream.
595 json_lex(JsonLexContext *lex)
600 /* Skip leading whitespace. */
601 s = lex->token_terminator;
602 len = s - lex->input;
603 while (len < lex->input_length &&
604 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
611 lex->token_start = s;
613 /* Determine token type. */
614 if (len >= lex->input_length)
616 lex->token_start = NULL;
617 lex->prev_token_terminator = lex->token_terminator;
618 lex->token_terminator = s;
619 lex->token_type = JSON_TOKEN_END;
624 /* Single-character token, some kind of punctuation mark. */
626 lex->prev_token_terminator = lex->token_terminator;
627 lex->token_terminator = s + 1;
628 lex->token_type = JSON_TOKEN_OBJECT_START;
631 lex->prev_token_terminator = lex->token_terminator;
632 lex->token_terminator = s + 1;
633 lex->token_type = JSON_TOKEN_OBJECT_END;
636 lex->prev_token_terminator = lex->token_terminator;
637 lex->token_terminator = s + 1;
638 lex->token_type = JSON_TOKEN_ARRAY_START;
641 lex->prev_token_terminator = lex->token_terminator;
642 lex->token_terminator = s + 1;
643 lex->token_type = JSON_TOKEN_ARRAY_END;
646 lex->prev_token_terminator = lex->token_terminator;
647 lex->token_terminator = s + 1;
648 lex->token_type = JSON_TOKEN_COMMA;
651 lex->prev_token_terminator = lex->token_terminator;
652 lex->token_terminator = s + 1;
653 lex->token_type = JSON_TOKEN_COLON;
657 json_lex_string(lex);
658 lex->token_type = JSON_TOKEN_STRING;
661 /* Negative number. */
662 json_lex_number(lex, s + 1, NULL);
663 lex->token_type = JSON_TOKEN_NUMBER;
675 /* Positive number. */
676 json_lex_number(lex, s, NULL);
677 lex->token_type = JSON_TOKEN_NUMBER;
684 * We're not dealing with a string, number, legal
685 * punctuation mark, or end of string. The only legal
686 * tokens we might find here are true, false, and null,
687 * but for error reporting purposes we scan until we see a
688 * non-alphanumeric character. That way, we can report
689 * the whole word as an unexpected token, rather than just
690 * some unintuitive prefix thereof.
692 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
696 * We got some sort of unexpected punctuation or an
697 * otherwise unexpected character, so just complain about
698 * that one character.
702 lex->prev_token_terminator = lex->token_terminator;
703 lex->token_terminator = s + 1;
704 report_invalid_token(lex);
708 * We've got a real alphanumeric token here. If it
709 * happens to be true, false, or null, all is well. If
712 lex->prev_token_terminator = lex->token_terminator;
713 lex->token_terminator = p;
716 if (memcmp(s, "true", 4) == 0)
717 lex->token_type = JSON_TOKEN_TRUE;
718 else if (memcmp(s, "null", 4) == 0)
719 lex->token_type = JSON_TOKEN_NULL;
721 report_invalid_token(lex);
723 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
724 lex->token_type = JSON_TOKEN_FALSE;
726 report_invalid_token(lex);
729 } /* end of switch */
733 * The next token in the input stream is known to be a string; lex it.
736 json_lex_string(JsonLexContext *lex)
740 int hi_surrogate = -1;
742 if (lex->strval != NULL)
743 resetStringInfo(lex->strval);
745 Assert(lex->input_length > 0);
746 s = lex->token_start;
747 len = lex->token_start - lex->input;
752 /* Premature end of the string. */
753 if (len >= lex->input_length)
755 lex->token_terminator = s;
756 report_invalid_token(lex);
760 else if ((unsigned char) *s < 32)
762 /* Per RFC4627, these characters MUST be escaped. */
763 /* Since *s isn't printable, exclude it from the context string */
764 lex->token_terminator = s;
766 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
767 errmsg("invalid input syntax for type json"),
768 errdetail("Character with value 0x%02x must be escaped.",
770 report_json_context(lex)));
774 /* OK, we have an escape character. */
777 if (len >= lex->input_length)
779 lex->token_terminator = s;
780 report_invalid_token(lex);
787 for (i = 1; i <= 4; i++)
791 if (len >= lex->input_length)
793 lex->token_terminator = s;
794 report_invalid_token(lex);
796 else if (*s >= '0' && *s <= '9')
797 ch = (ch * 16) + (*s - '0');
798 else if (*s >= 'a' && *s <= 'f')
799 ch = (ch * 16) + (*s - 'a') + 10;
800 else if (*s >= 'A' && *s <= 'F')
801 ch = (ch * 16) + (*s - 'A') + 10;
804 lex->token_terminator = s + pg_mblen(s);
806 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
807 errmsg("invalid input syntax for type json"),
808 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
809 report_json_context(lex)));
812 if (lex->strval != NULL)
817 if (ch >= 0xd800 && ch <= 0xdbff)
819 if (hi_surrogate != -1)
821 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
822 errmsg("invalid input syntax for type json"),
823 errdetail("Unicode high surrogate must not follow a high surrogate."),
824 report_json_context(lex)));
825 hi_surrogate = (ch & 0x3ff) << 10;
828 else if (ch >= 0xdc00 && ch <= 0xdfff)
830 if (hi_surrogate == -1)
832 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
833 errmsg("invalid input syntax for type json"),
834 errdetail("Unicode low surrogate must follow a high surrogate."),
835 report_json_context(lex)));
836 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
840 if (hi_surrogate != -1)
842 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
843 errmsg("invalid input syntax for type json"),
844 errdetail("Unicode low surrogate must follow a high surrogate."),
845 report_json_context(lex)));
848 * For UTF8, replace the escape sequence by the actual
849 * utf8 character in lex->strval. Do this also for other
850 * encodings if the escape designates an ASCII character,
851 * otherwise raise an error.
856 /* We can't allow this, since our TEXT type doesn't */
858 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
859 errmsg("unsupported Unicode escape sequence"),
860 errdetail("\\u0000 cannot be converted to text."),
861 report_json_context(lex)));
863 else if (GetDatabaseEncoding() == PG_UTF8)
865 unicode_to_utf8(ch, (unsigned char *) utf8str);
866 utf8len = pg_utf_mblen((unsigned char *) utf8str);
867 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
869 else if (ch <= 0x007f)
872 * This is the only way to designate things like a
873 * form feed character in JSON, so it's useful in all
876 appendStringInfoChar(lex->strval, (char) ch);
881 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
882 errmsg("unsupported Unicode escape sequence"),
883 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
884 report_json_context(lex)));
889 else if (lex->strval != NULL)
891 if (hi_surrogate != -1)
893 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
894 errmsg("invalid input syntax for type json"),
895 errdetail("Unicode low surrogate must follow a high surrogate."),
896 report_json_context(lex)));
903 appendStringInfoChar(lex->strval, *s);
906 appendStringInfoChar(lex->strval, '\b');
909 appendStringInfoChar(lex->strval, '\f');
912 appendStringInfoChar(lex->strval, '\n');
915 appendStringInfoChar(lex->strval, '\r');
918 appendStringInfoChar(lex->strval, '\t');
921 /* Not a valid string escape, so error out. */
922 lex->token_terminator = s + pg_mblen(s);
924 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
925 errmsg("invalid input syntax for type json"),
926 errdetail("Escape sequence \"\\%s\" is invalid.",
928 report_json_context(lex)));
931 else if (strchr("\"\\/bfnrt", *s) == NULL)
934 * Simpler processing if we're not bothered about de-escaping
936 * It's very tempting to remove the strchr() call here and
937 * replace it with a switch statement, but testing so far has
938 * shown it's not a performance win.
940 lex->token_terminator = s + pg_mblen(s);
942 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
943 errmsg("invalid input syntax for type json"),
944 errdetail("Escape sequence \"\\%s\" is invalid.",
946 report_json_context(lex)));
950 else if (lex->strval != NULL)
952 if (hi_surrogate != -1)
954 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
955 errmsg("invalid input syntax for type json"),
956 errdetail("Unicode low surrogate must follow a high surrogate."),
957 report_json_context(lex)));
959 appendStringInfoChar(lex->strval, *s);
964 if (hi_surrogate != -1)
966 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
967 errmsg("invalid input syntax for type json"),
968 errdetail("Unicode low surrogate must follow a high surrogate."),
969 report_json_context(lex)));
971 /* Hooray, we found the end of the string! */
972 lex->prev_token_terminator = lex->token_terminator;
973 lex->token_terminator = s + 1;
976 /*-------------------------------------------------------------------------
977 * The next token in the input stream is known to be a number; lex it.
979 * In JSON, a number consists of four parts:
981 * (1) An optional minus sign ('-').
983 * (2) Either a single '0', or a string of one or more digits that does not
986 * (3) An optional decimal part, consisting of a period ('.') followed by
987 * one or more digits. (Note: While this part can be omitted
988 * completely, it's not OK to have only the decimal point without
989 * any digits afterwards.)
991 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
992 * followed by '+' or '-', followed by one or more digits. (Note:
993 * As with the decimal part, if 'e' or 'E' is present, it must be
994 * followed by at least one digit.)
996 * The 's' argument to this function points to the ostensible beginning
997 * of part 2 - i.e. the character after any optional minus sign, and the
998 * first character of the string if there is none.
1000 *-------------------------------------------------------------------------
1003 json_lex_number(JsonLexContext *lex, char *s, bool *num_err)
1009 len = s - lex->input;
1010 /* Part (1): leading sign indicator. */
1011 /* Caller already did this for us; so do nothing. */
1013 /* Part (2): parse main digit string. */
1019 else if (*s >= '1' && *s <= '9')
1025 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1030 /* Part (3): parse optional decimal portion. */
1031 if (len < lex->input_length && *s == '.')
1035 if (len == lex->input_length || *s < '0' || *s > '9')
1043 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1047 /* Part (4): parse optional exponent. */
1048 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
1052 if (len < lex->input_length && (*s == '+' || *s == '-'))
1057 if (len == lex->input_length || *s < '0' || *s > '9')
1065 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1070 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
1071 * here should be considered part of the token for error-reporting
1074 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
1077 if (num_err != NULL)
1079 /* let the caller handle the error */
1084 lex->prev_token_terminator = lex->token_terminator;
1085 lex->token_terminator = p;
1087 report_invalid_token(lex);
1092 * Report a parse error.
1094 * lex->token_start and lex->token_terminator must identify the current token.
1097 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1102 /* Handle case where the input ended prematurely. */
1103 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1105 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1106 errmsg("invalid input syntax for type json"),
1107 errdetail("The input string ended unexpectedly."),
1108 report_json_context(lex)));
1110 /* Separate out the current token. */
1111 toklen = lex->token_terminator - lex->token_start;
1112 token = palloc(toklen + 1);
1113 memcpy(token, lex->token_start, toklen);
1114 token[toklen] = '\0';
1116 /* Complain, with the appropriate detail message. */
1117 if (ctx == JSON_PARSE_END)
1119 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1120 errmsg("invalid input syntax for type json"),
1121 errdetail("Expected end of input, but found \"%s\".",
1123 report_json_context(lex)));
1128 case JSON_PARSE_VALUE:
1130 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1131 errmsg("invalid input syntax for type json"),
1132 errdetail("Expected JSON value, but found \"%s\".",
1134 report_json_context(lex)));
1136 case JSON_PARSE_STRING:
1138 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1139 errmsg("invalid input syntax for type json"),
1140 errdetail("Expected string, but found \"%s\".",
1142 report_json_context(lex)));
1144 case JSON_PARSE_ARRAY_START:
1146 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1147 errmsg("invalid input syntax for type json"),
1148 errdetail("Expected array element or \"]\", but found \"%s\".",
1150 report_json_context(lex)));
1152 case JSON_PARSE_ARRAY_NEXT:
1154 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1155 errmsg("invalid input syntax for type json"),
1156 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1158 report_json_context(lex)));
1160 case JSON_PARSE_OBJECT_START:
1162 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1163 errmsg("invalid input syntax for type json"),
1164 errdetail("Expected string or \"}\", but found \"%s\".",
1166 report_json_context(lex)));
1168 case JSON_PARSE_OBJECT_LABEL:
1170 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1171 errmsg("invalid input syntax for type json"),
1172 errdetail("Expected \":\", but found \"%s\".",
1174 report_json_context(lex)));
1176 case JSON_PARSE_OBJECT_NEXT:
1178 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1179 errmsg("invalid input syntax for type json"),
1180 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1182 report_json_context(lex)));
1184 case JSON_PARSE_OBJECT_COMMA:
1186 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1187 errmsg("invalid input syntax for type json"),
1188 errdetail("Expected string, but found \"%s\".",
1190 report_json_context(lex)));
1193 elog(ERROR, "unexpected json parse state: %d", ctx);
1199 * Report an invalid input token.
1201 * lex->token_start and lex->token_terminator must identify the token.
1204 report_invalid_token(JsonLexContext *lex)
1209 /* Separate out the offending token. */
1210 toklen = lex->token_terminator - lex->token_start;
1211 token = palloc(toklen + 1);
1212 memcpy(token, lex->token_start, toklen);
1213 token[toklen] = '\0';
1216 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1217 errmsg("invalid input syntax for type json"),
1218 errdetail("Token \"%s\" is invalid.", token),
1219 report_json_context(lex)));
1223 * Report a CONTEXT line for bogus JSON input.
1225 * lex->token_terminator must be set to identify the spot where we detected
1226 * the error. Note that lex->token_start might be NULL, in case we recognized
1229 * The return value isn't meaningful, but we make it non-void so that this
1230 * can be invoked inside ereport().
1233 report_json_context(JsonLexContext *lex)
1235 const char *context_start;
1236 const char *context_end;
1237 const char *line_start;
1244 /* Choose boundaries for the part of the input we will display */
1245 context_start = lex->input;
1246 context_end = lex->token_terminator;
1247 line_start = context_start;
1251 /* Always advance over newlines */
1252 if (context_start < context_end && *context_start == '\n')
1255 line_start = context_start;
1259 /* Otherwise, done as soon as we are close enough to context_end */
1260 if (context_end - context_start < 50)
1262 /* Advance to next multibyte character */
1263 if (IS_HIGHBIT_SET(*context_start))
1264 context_start += pg_mblen(context_start);
1270 * We add "..." to indicate that the excerpt doesn't start at the
1271 * beginning of the line ... but if we're within 3 characters of the
1272 * beginning of the line, we might as well just show the whole line.
1274 if (context_start - line_start <= 3)
1275 context_start = line_start;
1277 /* Get a null-terminated copy of the data to present */
1278 ctxtlen = context_end - context_start;
1279 ctxt = palloc(ctxtlen + 1);
1280 memcpy(ctxt, context_start, ctxtlen);
1281 ctxt[ctxtlen] = '\0';
1284 * Show the context, prefixing "..." if not starting at start of line, and
1285 * suffixing "..." if not ending at end of line.
1287 prefix = (context_start > line_start) ? "..." : "";
1288 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1290 return errcontext("JSON data, line %d: %s%s%s",
1291 line_number, prefix, ctxt, suffix);
1295 * Extract a single, possibly multi-byte char from the input string.
1298 extract_mb_char(char *s)
1304 res = palloc(len + 1);
1305 memcpy(res, s, len);
1312 * Determine how we want to print values of a given type in datum_to_json.
1314 * Given the datatype OID, return its JsonTypeCategory, as well as the type's
1315 * output function OID. If the returned category is JSONTYPE_CAST, we
1316 * return the OID of the type->JSON cast function instead.
1319 json_categorize_type(Oid typoid,
1320 JsonTypeCategory *tcategory,
1325 /* Look through any domain */
1326 typoid = getBaseType(typoid);
1328 *outfuncoid = InvalidOid;
1331 * We need to get the output function for everything except date and
1332 * timestamp types, array and composite types, booleans, and non-builtin
1333 * types where there's a cast to json.
1339 *tcategory = JSONTYPE_BOOL;
1348 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1349 *tcategory = JSONTYPE_NUMERIC;
1353 *tcategory = JSONTYPE_DATE;
1357 *tcategory = JSONTYPE_TIMESTAMP;
1360 case TIMESTAMPTZOID:
1361 *tcategory = JSONTYPE_TIMESTAMPTZ;
1366 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1367 *tcategory = JSONTYPE_JSON;
1371 /* Check for arrays and composites */
1372 if (OidIsValid(get_element_type(typoid)))
1373 *tcategory = JSONTYPE_ARRAY;
1374 else if (type_is_rowtype(typoid))
1375 *tcategory = JSONTYPE_COMPOSITE;
1378 /* It's probably the general case ... */
1379 *tcategory = JSONTYPE_OTHER;
1380 /* but let's look for a cast to json, if it's not built-in */
1381 if (typoid >= FirstNormalObjectId)
1384 CoercionPathType ctype;
1386 ctype = find_coercion_pathway(JSONOID, typoid,
1389 if (ctype == COERCION_PATH_FUNC && OidIsValid(castfunc))
1391 *tcategory = JSONTYPE_CAST;
1392 *outfuncoid = castfunc;
1396 /* non builtin type with no cast */
1397 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1402 /* any other builtin type */
1403 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1411 * Turn a Datum into JSON text, appending the string to "result".
1413 * tcategory and outfuncoid are from a previous call to json_categorize_type,
1414 * except that if is_null is true then they can be invalid.
1416 * If key_scalar is true, the value is being printed as a key, so insist
1417 * it's of an acceptable type, and force it to be quoted.
1420 datum_to_json(Datum val, bool is_null, StringInfo result,
1421 JsonTypeCategory tcategory, Oid outfuncoid,
1427 /* callers are expected to ensure that null keys are not passed in */
1428 Assert(!(key_scalar && is_null));
1432 appendStringInfoString(result, "null");
1437 (tcategory == JSONTYPE_ARRAY ||
1438 tcategory == JSONTYPE_COMPOSITE ||
1439 tcategory == JSONTYPE_JSON ||
1440 tcategory == JSONTYPE_CAST))
1442 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1443 errmsg("key value must be scalar, not array, composite, or json")));
1447 case JSONTYPE_ARRAY:
1448 array_to_json_internal(val, result, false);
1450 case JSONTYPE_COMPOSITE:
1451 composite_to_json(val, result, false);
1454 outputstr = DatumGetBool(val) ? "true" : "false";
1456 escape_json(result, outputstr);
1458 appendStringInfoString(result, outputstr);
1460 case JSONTYPE_NUMERIC:
1461 outputstr = OidOutputFunctionCall(outfuncoid, val);
1464 * Don't call escape_json for a non-key if it's a valid JSON
1467 if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
1468 appendStringInfoString(result, outputstr);
1470 escape_json(result, outputstr);
1477 char buf[MAXDATELEN + 1];
1479 date = DatumGetDateADT(val);
1481 if (DATE_NOT_FINITE(date))
1483 /* we have to format infinity ourselves */
1484 appendStringInfoString(result, DT_INFINITY);
1488 j2date(date + POSTGRES_EPOCH_JDATE,
1489 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1490 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1491 appendStringInfo(result, "\"%s\"", buf);
1495 case JSONTYPE_TIMESTAMP:
1497 Timestamp timestamp;
1500 char buf[MAXDATELEN + 1];
1502 timestamp = DatumGetTimestamp(val);
1504 if (TIMESTAMP_NOT_FINITE(timestamp))
1506 /* we have to format infinity ourselves */
1507 appendStringInfoString(result, DT_INFINITY);
1509 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1511 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
1512 appendStringInfo(result, "\"%s\"", buf);
1516 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1517 errmsg("timestamp out of range")));
1520 case JSONTYPE_TIMESTAMPTZ:
1522 TimestampTz timestamp;
1526 const char *tzn = NULL;
1527 char buf[MAXDATELEN + 1];
1529 timestamp = DatumGetTimestamp(val);
1531 if (TIMESTAMP_NOT_FINITE(timestamp))
1533 /* we have to format infinity ourselves */
1534 appendStringInfoString(result, DT_INFINITY);
1536 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1538 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
1539 appendStringInfo(result, "\"%s\"", buf);
1543 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1544 errmsg("timestamp out of range")));
1548 /* JSON and JSONB output will already be escaped */
1549 outputstr = OidOutputFunctionCall(outfuncoid, val);
1550 appendStringInfoString(result, outputstr);
1554 /* outfuncoid refers to a cast function, not an output function */
1555 jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
1556 outputstr = text_to_cstring(jsontext);
1557 appendStringInfoString(result, outputstr);
1562 outputstr = OidOutputFunctionCall(outfuncoid, val);
1563 escape_json(result, outputstr);
1570 * Process a single dimension of an array.
1571 * If it's the innermost dimension, output the values, otherwise call
1572 * ourselves recursively to process the next dimension.
1575 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1576 bool *nulls, int *valcount, JsonTypeCategory tcategory,
1577 Oid outfuncoid, bool use_line_feeds)
1582 Assert(dim < ndims);
1584 sep = use_line_feeds ? ",\n " : ",";
1586 appendStringInfoChar(result, '[');
1588 for (i = 1; i <= dims[dim]; i++)
1591 appendStringInfoString(result, sep);
1593 if (dim + 1 == ndims)
1595 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1602 * Do we want line feeds on inner dimensions of arrays? For now
1605 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1606 valcount, tcategory, outfuncoid, false);
1610 appendStringInfoChar(result, ']');
1614 * Turn an array into JSON.
1617 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1619 ArrayType *v = DatumGetArrayTypeP(array);
1620 Oid element_type = ARR_ELEMTYPE(v);
1630 JsonTypeCategory tcategory;
1635 nitems = ArrayGetNItems(ndim, dim);
1639 appendStringInfoString(result, "[]");
1643 get_typlenbyvalalign(element_type,
1644 &typlen, &typbyval, &typalign);
1646 json_categorize_type(element_type,
1647 &tcategory, &outfuncoid);
1649 deconstruct_array(v, element_type, typlen, typbyval,
1650 typalign, &elements, &nulls,
1653 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1654 outfuncoid, use_line_feeds);
1661 * Turn a composite / record into JSON.
1664 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1670 HeapTupleData tmptup,
1673 bool needsep = false;
1676 sep = use_line_feeds ? ",\n " : ",";
1678 td = DatumGetHeapTupleHeader(composite);
1680 /* Extract rowtype info and find a tupdesc */
1681 tupType = HeapTupleHeaderGetTypeId(td);
1682 tupTypmod = HeapTupleHeaderGetTypMod(td);
1683 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1685 /* Build a temporary HeapTuple control structure */
1686 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1690 appendStringInfoChar(result, '{');
1692 for (i = 0; i < tupdesc->natts; i++)
1697 JsonTypeCategory tcategory;
1700 if (tupdesc->attrs[i]->attisdropped)
1704 appendStringInfoString(result, sep);
1707 attname = NameStr(tupdesc->attrs[i]->attname);
1708 escape_json(result, attname);
1709 appendStringInfoChar(result, ':');
1711 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1715 tcategory = JSONTYPE_NULL;
1716 outfuncoid = InvalidOid;
1719 json_categorize_type(tupdesc->attrs[i]->atttypid,
1720 &tcategory, &outfuncoid);
1722 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1725 appendStringInfoChar(result, '}');
1726 ReleaseTupleDesc(tupdesc);
1730 * Append JSON text for "val" to "result".
1732 * This is just a thin wrapper around datum_to_json. If the same type will be
1733 * printed many times, avoid using this; better to do the json_categorize_type
1734 * lookups only once.
1737 add_json(Datum val, bool is_null, StringInfo result,
1738 Oid val_type, bool key_scalar)
1740 JsonTypeCategory tcategory;
1743 if (val_type == InvalidOid)
1745 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1746 errmsg("could not determine input data type")));
1750 tcategory = JSONTYPE_NULL;
1751 outfuncoid = InvalidOid;
1754 json_categorize_type(val_type,
1755 &tcategory, &outfuncoid);
1757 datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1761 * SQL function array_to_json(row)
1764 array_to_json(PG_FUNCTION_ARGS)
1766 Datum array = PG_GETARG_DATUM(0);
1769 result = makeStringInfo();
1771 array_to_json_internal(array, result, false);
1773 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1777 * SQL function array_to_json(row, prettybool)
1780 array_to_json_pretty(PG_FUNCTION_ARGS)
1782 Datum array = PG_GETARG_DATUM(0);
1783 bool use_line_feeds = PG_GETARG_BOOL(1);
1786 result = makeStringInfo();
1788 array_to_json_internal(array, result, use_line_feeds);
1790 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1794 * SQL function row_to_json(row)
1797 row_to_json(PG_FUNCTION_ARGS)
1799 Datum array = PG_GETARG_DATUM(0);
1802 result = makeStringInfo();
1804 composite_to_json(array, result, false);
1806 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1810 * SQL function row_to_json(row, prettybool)
1813 row_to_json_pretty(PG_FUNCTION_ARGS)
1815 Datum array = PG_GETARG_DATUM(0);
1816 bool use_line_feeds = PG_GETARG_BOOL(1);
1819 result = makeStringInfo();
1821 composite_to_json(array, result, use_line_feeds);
1823 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1827 * SQL function to_json(anyvalue)
1830 to_json(PG_FUNCTION_ARGS)
1832 Datum val = PG_GETARG_DATUM(0);
1833 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1835 JsonTypeCategory tcategory;
1838 if (val_type == InvalidOid)
1840 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1841 errmsg("could not determine input data type")));
1843 json_categorize_type(val_type,
1844 &tcategory, &outfuncoid);
1846 result = makeStringInfo();
1848 datum_to_json(val, false, result, tcategory, outfuncoid, false);
1850 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1854 * json_agg transition function
1856 * aggregate input column as a json array value.
1859 json_agg_transfn(PG_FUNCTION_ARGS)
1861 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1862 MemoryContext aggcontext,
1866 JsonTypeCategory tcategory;
1869 if (val_type == InvalidOid)
1871 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1872 errmsg("could not determine input data type")));
1874 if (!AggCheckCallContext(fcinfo, &aggcontext))
1876 /* cannot be called directly because of internal-type argument */
1877 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1880 if (PG_ARGISNULL(0))
1883 * Make this StringInfo in a context where it will persist for the
1884 * duration of the aggregate call. MemoryContextSwitchTo is only
1885 * needed the first time, as the StringInfo routines make sure they
1886 * use the right context to enlarge the object if necessary.
1888 oldcontext = MemoryContextSwitchTo(aggcontext);
1889 state = makeStringInfo();
1890 MemoryContextSwitchTo(oldcontext);
1892 appendStringInfoChar(state, '[');
1896 state = (StringInfo) PG_GETARG_POINTER(0);
1897 appendStringInfoString(state, ", ");
1900 /* fast path for NULLs */
1901 if (PG_ARGISNULL(1))
1903 datum_to_json((Datum) 0, true, state, JSONTYPE_NULL, InvalidOid, false);
1904 PG_RETURN_POINTER(state);
1907 val = PG_GETARG_DATUM(1);
1909 /* XXX we do this every time?? */
1910 json_categorize_type(val_type,
1911 &tcategory, &outfuncoid);
1913 /* add some whitespace if structured type and not first item */
1914 if (!PG_ARGISNULL(0) &&
1915 (tcategory == JSONTYPE_ARRAY || tcategory == JSONTYPE_COMPOSITE))
1917 appendStringInfoString(state, "\n ");
1920 datum_to_json(val, false, state, tcategory, outfuncoid, false);
1923 * The transition type for array_agg() is declared to be "internal", which
1924 * is a pass-by-value type the same size as a pointer. So we can safely
1925 * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
1927 PG_RETURN_POINTER(state);
1931 * json_agg final function
1934 json_agg_finalfn(PG_FUNCTION_ARGS)
1938 /* cannot be called directly because of internal-type argument */
1939 Assert(AggCheckCallContext(fcinfo, NULL));
1941 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1943 /* NULL result for no rows in, as is standard with aggregates */
1947 /* Else return state with appropriate array terminator added */
1948 PG_RETURN_TEXT_P(catenate_stringinfo_string(state, "]"));
1952 * json_object_agg transition function.
1954 * aggregate two input columns as a single json object value.
1957 json_object_agg_transfn(PG_FUNCTION_ARGS)
1960 MemoryContext aggcontext,
1965 if (!AggCheckCallContext(fcinfo, &aggcontext))
1967 /* cannot be called directly because of internal-type argument */
1968 elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
1971 if (PG_ARGISNULL(0))
1974 * Make the StringInfo in a context where it will persist for the
1975 * duration of the aggregate call. Switching context is only needed
1976 * for this initial step, as the StringInfo routines make sure they
1977 * use the right context to enlarge the object if necessary.
1979 oldcontext = MemoryContextSwitchTo(aggcontext);
1980 state = makeStringInfo();
1981 MemoryContextSwitchTo(oldcontext);
1983 appendStringInfoString(state, "{ ");
1987 state = (StringInfo) PG_GETARG_POINTER(0);
1988 appendStringInfoString(state, ", ");
1992 * Note: since json_object_agg() is declared as taking type "any", the
1993 * parser will not do any type conversion on unknown-type literals (that
1994 * is, undecorated strings or NULLs). Such values will arrive here as
1995 * type UNKNOWN, which fortunately does not matter to us, since
1996 * unknownout() works fine.
1998 val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
2000 if (val_type == InvalidOid)
2002 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2003 errmsg("could not determine data type for argument %d", 1)));
2005 if (PG_ARGISNULL(1))
2007 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2008 errmsg("field name must not be null")));
2010 arg = PG_GETARG_DATUM(1);
2012 add_json(arg, false, state, val_type, true);
2014 appendStringInfoString(state, " : ");
2016 val_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
2018 if (val_type == InvalidOid)
2020 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2021 errmsg("could not determine data type for argument %d", 2)));
2023 if (PG_ARGISNULL(2))
2026 arg = PG_GETARG_DATUM(2);
2028 add_json(arg, PG_ARGISNULL(2), state, val_type, false);
2030 PG_RETURN_POINTER(state);
2034 * json_object_agg final function.
2037 json_object_agg_finalfn(PG_FUNCTION_ARGS)
2041 /* cannot be called directly because of internal-type argument */
2042 Assert(AggCheckCallContext(fcinfo, NULL));
2044 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
2046 /* NULL result for no rows in, as is standard with aggregates */
2050 /* Else return state with appropriate object terminator added */
2051 PG_RETURN_TEXT_P(catenate_stringinfo_string(state, " }"));
2055 * Helper function for aggregates: return given StringInfo's contents plus
2056 * specified trailing string, as a text datum. We need this because aggregate
2057 * final functions are not allowed to modify the aggregate state.
2060 catenate_stringinfo_string(StringInfo buffer, const char *addon)
2062 /* custom version of cstring_to_text_with_len */
2063 int buflen = buffer->len;
2064 int addlen = strlen(addon);
2065 text *result = (text *) palloc(buflen + addlen + VARHDRSZ);
2067 SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
2068 memcpy(VARDATA(result), buffer->data, buflen);
2069 memcpy(VARDATA(result) + buflen, addon, addlen);
2075 * SQL function json_build_object(variadic "any")
2078 json_build_object(PG_FUNCTION_ARGS)
2080 int nargs = PG_NARGS();
2083 const char *sep = "";
2089 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2090 errmsg("argument list must have even number of elements"),
2091 errhint("The arguments of json_build_object() must consist of alternating keys and values.")));
2093 result = makeStringInfo();
2095 appendStringInfoChar(result, '{');
2097 for (i = 0; i < nargs; i += 2)
2100 * Note: since json_build_object() is declared as taking type "any",
2101 * the parser will not do any type conversion on unknown-type literals
2102 * (that is, undecorated strings or NULLs). Such values will arrive
2103 * here as type UNKNOWN, which fortunately does not matter to us,
2104 * since unknownout() works fine.
2106 appendStringInfoString(result, sep);
2110 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2112 if (val_type == InvalidOid)
2114 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2115 errmsg("could not determine data type for argument %d",
2118 if (PG_ARGISNULL(i))
2120 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2121 errmsg("argument %d cannot be null", i + 1),
2122 errhint("Object keys should be text.")));
2124 arg = PG_GETARG_DATUM(i);
2126 add_json(arg, false, result, val_type, true);
2128 appendStringInfoString(result, " : ");
2131 val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
2133 if (val_type == InvalidOid)
2135 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2136 errmsg("could not determine data type for argument %d",
2139 if (PG_ARGISNULL(i + 1))
2142 arg = PG_GETARG_DATUM(i + 1);
2144 add_json(arg, PG_ARGISNULL(i + 1), result, val_type, false);
2147 appendStringInfoChar(result, '}');
2149 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2153 * degenerate case of json_build_object where it gets 0 arguments.
2156 json_build_object_noargs(PG_FUNCTION_ARGS)
2158 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2162 * SQL function json_build_array(variadic "any")
2165 json_build_array(PG_FUNCTION_ARGS)
2167 int nargs = PG_NARGS();
2170 const char *sep = "";
2174 result = makeStringInfo();
2176 appendStringInfoChar(result, '[');
2178 for (i = 0; i < nargs; i++)
2181 * Note: since json_build_array() is declared as taking type "any",
2182 * the parser will not do any type conversion on unknown-type literals
2183 * (that is, undecorated strings or NULLs). Such values will arrive
2184 * here as type UNKNOWN, which fortunately does not matter to us,
2185 * since unknownout() works fine.
2187 appendStringInfoString(result, sep);
2190 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2192 if (val_type == InvalidOid)
2194 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2195 errmsg("could not determine data type for argument %d",
2198 if (PG_ARGISNULL(i))
2201 arg = PG_GETARG_DATUM(i);
2203 add_json(arg, PG_ARGISNULL(i), result, val_type, false);
2206 appendStringInfoChar(result, ']');
2208 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2212 * degenerate case of json_build_array where it gets 0 arguments.
2215 json_build_array_noargs(PG_FUNCTION_ARGS)
2217 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2221 * SQL function json_object(text[])
2223 * take a one or two dimensional array of text as key/value pairs
2224 * for a json object.
2227 json_object(PG_FUNCTION_ARGS)
2229 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2230 int ndims = ARR_NDIM(in_array);
2231 StringInfoData result;
2243 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2247 if ((ARR_DIMS(in_array)[0]) % 2)
2249 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2250 errmsg("array must have even number of elements")));
2254 if ((ARR_DIMS(in_array)[1]) != 2)
2256 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2257 errmsg("array must have two columns")));
2262 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2263 errmsg("wrong number of array subscripts")));
2266 deconstruct_array(in_array,
2267 TEXTOID, -1, false, 'i',
2268 &in_datums, &in_nulls, &in_count);
2270 count = in_count / 2;
2272 initStringInfo(&result);
2274 appendStringInfoChar(&result, '{');
2276 for (i = 0; i < count; ++i)
2278 if (in_nulls[i * 2])
2280 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2281 errmsg("null value not allowed for object key")));
2283 v = TextDatumGetCString(in_datums[i * 2]);
2285 appendStringInfoString(&result, ", ");
2286 escape_json(&result, v);
2287 appendStringInfoString(&result, " : ");
2289 if (in_nulls[i * 2 + 1])
2290 appendStringInfoString(&result, "null");
2293 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2294 escape_json(&result, v);
2299 appendStringInfoChar(&result, '}');
2304 rval = cstring_to_text_with_len(result.data, result.len);
2307 PG_RETURN_TEXT_P(rval);
2312 * SQL function json_object(text[], text[])
2314 * take separate key and value arrays of text to construct a json object
2318 json_object_two_arg(PG_FUNCTION_ARGS)
2320 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2321 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2322 int nkdims = ARR_NDIM(key_array);
2323 int nvdims = ARR_NDIM(val_array);
2324 StringInfoData result;
2335 if (nkdims > 1 || nkdims != nvdims)
2337 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2338 errmsg("wrong number of array subscripts")));
2341 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2343 deconstruct_array(key_array,
2344 TEXTOID, -1, false, 'i',
2345 &key_datums, &key_nulls, &key_count);
2347 deconstruct_array(val_array,
2348 TEXTOID, -1, false, 'i',
2349 &val_datums, &val_nulls, &val_count);
2351 if (key_count != val_count)
2353 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2354 errmsg("mismatched array dimensions")));
2356 initStringInfo(&result);
2358 appendStringInfoChar(&result, '{');
2360 for (i = 0; i < key_count; ++i)
2364 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2365 errmsg("null value not allowed for object key")));
2367 v = TextDatumGetCString(key_datums[i]);
2369 appendStringInfoString(&result, ", ");
2370 escape_json(&result, v);
2371 appendStringInfoString(&result, " : ");
2374 appendStringInfoString(&result, "null");
2377 v = TextDatumGetCString(val_datums[i]);
2378 escape_json(&result, v);
2383 appendStringInfoChar(&result, '}');
2390 rval = cstring_to_text_with_len(result.data, result.len);
2393 PG_RETURN_TEXT_P(rval);
2398 * Produce a JSON string literal, properly escaping characters in the text.
2401 escape_json(StringInfo buf, const char *str)
2405 appendStringInfoCharMacro(buf, '\"');
2406 for (p = str; *p; p++)
2411 appendStringInfoString(buf, "\\b");
2414 appendStringInfoString(buf, "\\f");
2417 appendStringInfoString(buf, "\\n");
2420 appendStringInfoString(buf, "\\r");
2423 appendStringInfoString(buf, "\\t");
2426 appendStringInfoString(buf, "\\\"");
2429 appendStringInfoString(buf, "\\\\");
2432 if ((unsigned char) *p < ' ')
2433 appendStringInfo(buf, "\\u%04x", (int) *p);
2435 appendStringInfoCharMacro(buf, *p);
2439 appendStringInfoCharMacro(buf, '\"');
2443 * SQL function json_typeof(json) -> text
2445 * Returns the type of the outermost JSON value as TEXT. Possible types are
2446 * "object", "array", "string", "number", "boolean", and "null".
2448 * Performs a single call to json_lex() to get the first token of the supplied
2449 * value. This initial token uniquely determines the value's type. As our
2450 * input must already have been validated by json_in() or json_recv(), the
2451 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2452 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2455 json_typeof(PG_FUNCTION_ARGS)
2459 JsonLexContext *lex;
2463 json = PG_GETARG_TEXT_P(0);
2464 lex = makeJsonLexContext(json, false);
2466 /* Lex exactly one token from the input and check its type. */
2468 tok = lex_peek(lex);
2471 case JSON_TOKEN_OBJECT_START:
2474 case JSON_TOKEN_ARRAY_START:
2477 case JSON_TOKEN_STRING:
2480 case JSON_TOKEN_NUMBER:
2483 case JSON_TOKEN_TRUE:
2484 case JSON_TOKEN_FALSE:
2487 case JSON_TOKEN_NULL:
2491 elog(ERROR, "unexpected json token: %d", tok);
2494 PG_RETURN_TEXT_P(cstring_to_text(type));