1 /*-------------------------------------------------------------------------
4 * JSON data type support.
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/utils/adt/json.c
12 *-------------------------------------------------------------------------
16 #include "access/htup_details.h"
17 #include "access/transam.h"
18 #include "catalog/pg_cast.h"
19 #include "catalog/pg_type.h"
20 #include "executor/spi.h"
21 #include "lib/stringinfo.h"
22 #include "libpq/pqformat.h"
23 #include "mb/pg_wchar.h"
24 #include "parser/parse_coerce.h"
25 #include "utils/array.h"
26 #include "utils/builtins.h"
27 #include "utils/lsyscache.h"
28 #include "utils/json.h"
29 #include "utils/jsonapi.h"
30 #include "utils/typcache.h"
31 #include "utils/syscache.h"
34 * The context of the parser is maintained by the recursive descent
35 * mechanism, but is passed explicitly to the error reporting routine
36 * for better diagnostics.
38 typedef enum /* contexts of JSON parser */
40 JSON_PARSE_VALUE, /* expecting a value */
41 JSON_PARSE_STRING, /* expecting a string (for a field name) */
42 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
43 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
44 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
45 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
46 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
47 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
48 JSON_PARSE_END /* saw the end of a document, expect nothing */
51 static inline void json_lex(JsonLexContext *lex);
52 static inline void json_lex_string(JsonLexContext *lex);
53 static inline void json_lex_number(JsonLexContext *lex, char *s, bool *num_err);
54 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
55 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
56 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
57 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
58 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
59 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
60 static void report_invalid_token(JsonLexContext *lex);
61 static int report_json_context(JsonLexContext *lex);
62 static char *extract_mb_char(char *s);
63 static void composite_to_json(Datum composite, StringInfo result,
65 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
66 Datum *vals, bool *nulls, int *valcount,
67 TYPCATEGORY tcategory, Oid typoutputfunc,
69 static void array_to_json_internal(Datum array, StringInfo result,
71 static void datum_to_json(Datum val, bool is_null, StringInfo result,
72 TYPCATEGORY tcategory, Oid typoutputfunc, bool key_scalar);
73 static void add_json(Datum val, bool is_null, StringInfo result,
74 Oid val_type, bool key_scalar);
76 /* the null action object used for pure validation */
77 static JsonSemAction nullSemAction =
79 NULL, NULL, NULL, NULL, NULL,
80 NULL, NULL, NULL, NULL, NULL
83 /* Recursive Descent parser support routines */
88 * what is the current look_ahead token?
90 static inline JsonTokenType
91 lex_peek(JsonLexContext *lex)
93 return lex->token_type;
99 * accept the look_ahead token and move the lexer to the next token if the
100 * look_ahead token matches the token parameter. In that case, and if required,
101 * also hand back the de-escaped lexeme.
103 * returns true if the token matched, false otherwise.
106 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
108 if (lex->token_type == token)
112 if (lex->token_type == JSON_TOKEN_STRING)
114 if (lex->strval != NULL)
115 *lexeme = pstrdup(lex->strval->data);
119 int len = (lex->token_terminator - lex->token_start);
120 char *tokstr = palloc(len + 1);
122 memcpy(tokstr, lex->token_start, len);
136 * move the lexer to the next token if the current look_ahead token matches
137 * the parameter token. Otherwise, report an error.
140 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
142 if (!lex_accept(lex, token, NULL))
143 report_parse_error(ctx, lex);;
147 * All the defined type categories are upper case , so use lower case here
148 * so we avoid any possible clash.
150 /* fake type category for JSON so we can distinguish it in datum_to_json */
151 #define TYPCATEGORY_JSON 'j'
152 /* fake category for types that have a cast to json */
153 #define TYPCATEGORY_JSON_CAST 'c'
154 /* chars to consider as part of an alphanumeric token */
155 #define JSON_ALPHANUMERIC_CHAR(c) \
156 (((c) >= 'a' && (c) <= 'z') || \
157 ((c) >= 'A' && (c) <= 'Z') || \
158 ((c) >= '0' && (c) <= '9') || \
166 json_in(PG_FUNCTION_ARGS)
168 char *json = PG_GETARG_CSTRING(0);
169 text *result = cstring_to_text(json);
173 lex = makeJsonLexContext(result, false);
174 pg_parse_json(lex, &nullSemAction);
176 /* Internal representation is the same as text, for now */
177 PG_RETURN_TEXT_P(result);
184 json_out(PG_FUNCTION_ARGS)
186 /* we needn't detoast because text_to_cstring will handle that */
187 Datum txt = PG_GETARG_DATUM(0);
189 PG_RETURN_CSTRING(TextDatumGetCString(txt));
196 json_send(PG_FUNCTION_ARGS)
198 text *t = PG_GETARG_TEXT_PP(0);
201 pq_begintypsend(&buf);
202 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
203 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
210 json_recv(PG_FUNCTION_ARGS)
212 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
218 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
220 result = palloc(nbytes + VARHDRSZ);
221 SET_VARSIZE(result, nbytes + VARHDRSZ);
222 memcpy(VARDATA(result), str, nbytes);
225 lex = makeJsonLexContext(result, false);
226 pg_parse_json(lex, &nullSemAction);
228 PG_RETURN_TEXT_P(result);
234 * lex constructor, with or without StringInfo object
235 * for de-escaped lexemes.
237 * Without is better as it makes the processing faster, so only make one
238 * if really required.
241 makeJsonLexContext(text *json, bool need_escapes)
243 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
245 lex->input = lex->token_terminator = lex->line_start = VARDATA(json);
246 lex->line_number = 1;
247 lex->input_length = VARSIZE(json) - VARHDRSZ;
249 lex->strval = makeStringInfo();
256 * Publicly visible entry point for the JSON parser.
258 * lex is a lexing context, set up for the json to be processed by calling
259 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
260 * action routines to be called at appropriate spots during parsing, and a
261 * pointer to a state object to be passed to those routines.
264 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
268 /* get the initial token */
273 /* parse by recursive descent */
276 case JSON_TOKEN_OBJECT_START:
277 parse_object(lex, sem);
279 case JSON_TOKEN_ARRAY_START:
280 parse_array(lex, sem);
283 parse_scalar(lex, sem); /* json can be a bare scalar */
286 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
291 * Recursive Descent parse routines. There is one for each structural
292 * element in a json document:
293 * - scalar (string, number, true, false, null)
300 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
303 json_scalar_action sfunc = sem->scalar;
305 JsonTokenType tok = lex_peek(lex);
307 valaddr = sfunc == NULL ? NULL : &val;
309 /* a scalar must be a string, a number, true, false, or null */
312 case JSON_TOKEN_TRUE:
313 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
315 case JSON_TOKEN_FALSE:
316 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
318 case JSON_TOKEN_NULL:
319 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
321 case JSON_TOKEN_NUMBER:
322 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
324 case JSON_TOKEN_STRING:
325 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
328 report_parse_error(JSON_PARSE_VALUE, lex);
332 (*sfunc) (sem->semstate, val, tok);
336 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
339 * an object field is "fieldname" : value where value can be a scalar,
343 char *fname = NULL; /* keep compiler quiet */
344 json_ofield_action ostart = sem->object_field_start;
345 json_ofield_action oend = sem->object_field_end;
347 char **fnameaddr = NULL;
350 if (ostart != NULL || oend != NULL)
353 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
354 report_parse_error(JSON_PARSE_STRING, lex);
356 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
359 isnull = tok == JSON_TOKEN_NULL;
362 (*ostart) (sem->semstate, fname, isnull);
366 case JSON_TOKEN_OBJECT_START:
367 parse_object(lex, sem);
369 case JSON_TOKEN_ARRAY_START:
370 parse_array(lex, sem);
373 parse_scalar(lex, sem);
377 (*oend) (sem->semstate, fname, isnull);
384 parse_object(JsonLexContext *lex, JsonSemAction *sem)
387 * an object is a possibly empty sequence of object fields, separated by
388 * commas and surrounde by curly braces.
390 json_struct_action ostart = sem->object_start;
391 json_struct_action oend = sem->object_end;
395 (*ostart) (sem->semstate);
398 * Data inside an object at at a higher nesting level than the object
399 * itself. Note that we increment this after we call the semantic routine
400 * for the object start and restore it before we call the routine for the
405 /* we know this will succeeed, just clearing the token */
406 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
411 case JSON_TOKEN_STRING:
412 parse_object_field(lex, sem);
413 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
414 parse_object_field(lex, sem);
416 case JSON_TOKEN_OBJECT_END:
419 /* case of an invalid initial token inside the object */
420 report_parse_error(JSON_PARSE_OBJECT_START, lex);
423 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
428 (*oend) (sem->semstate);
432 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
434 json_aelem_action astart = sem->array_element_start;
435 json_aelem_action aend = sem->array_element_end;
436 JsonTokenType tok = lex_peek(lex);
440 isnull = tok == JSON_TOKEN_NULL;
443 (*astart) (sem->semstate, isnull);
445 /* an array element is any object, array or scalar */
448 case JSON_TOKEN_OBJECT_START:
449 parse_object(lex, sem);
451 case JSON_TOKEN_ARRAY_START:
452 parse_array(lex, sem);
455 parse_scalar(lex, sem);
459 (*aend) (sem->semstate, isnull);
463 parse_array(JsonLexContext *lex, JsonSemAction *sem)
466 * an array is a possibly empty sequence of array elements, separated by
467 * commas and surrounded by square brackets.
469 json_struct_action astart = sem->array_start;
470 json_struct_action aend = sem->array_end;
473 (*astart) (sem->semstate);
476 * Data inside an array at at a higher nesting level than the array
477 * itself. Note that we increment this after we call the semantic routine
478 * for the array start and restore it before we call the routine for the
483 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
484 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
487 parse_array_element(lex, sem);
489 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
490 parse_array_element(lex, sem);
493 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
498 (*aend) (sem->semstate);
502 * Lex one token from the input stream.
505 json_lex(JsonLexContext *lex)
510 /* Skip leading whitespace. */
511 s = lex->token_terminator;
512 len = s - lex->input;
513 while (len < lex->input_length &&
514 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
521 lex->token_start = s;
523 /* Determine token type. */
524 if (len >= lex->input_length)
526 lex->token_start = NULL;
527 lex->prev_token_terminator = lex->token_terminator;
528 lex->token_terminator = s;
529 lex->token_type = JSON_TOKEN_END;
534 /* Single-character token, some kind of punctuation mark. */
536 lex->prev_token_terminator = lex->token_terminator;
537 lex->token_terminator = s + 1;
538 lex->token_type = JSON_TOKEN_OBJECT_START;
541 lex->prev_token_terminator = lex->token_terminator;
542 lex->token_terminator = s + 1;
543 lex->token_type = JSON_TOKEN_OBJECT_END;
546 lex->prev_token_terminator = lex->token_terminator;
547 lex->token_terminator = s + 1;
548 lex->token_type = JSON_TOKEN_ARRAY_START;
551 lex->prev_token_terminator = lex->token_terminator;
552 lex->token_terminator = s + 1;
553 lex->token_type = JSON_TOKEN_ARRAY_END;
556 lex->prev_token_terminator = lex->token_terminator;
557 lex->token_terminator = s + 1;
558 lex->token_type = JSON_TOKEN_COMMA;
561 lex->prev_token_terminator = lex->token_terminator;
562 lex->token_terminator = s + 1;
563 lex->token_type = JSON_TOKEN_COLON;
567 json_lex_string(lex);
568 lex->token_type = JSON_TOKEN_STRING;
571 /* Negative number. */
572 json_lex_number(lex, s + 1, NULL);
573 lex->token_type = JSON_TOKEN_NUMBER;
585 /* Positive number. */
586 json_lex_number(lex, s, NULL);
587 lex->token_type = JSON_TOKEN_NUMBER;
594 * We're not dealing with a string, number, legal
595 * punctuation mark, or end of string. The only legal
596 * tokens we might find here are true, false, and null,
597 * but for error reporting purposes we scan until we see a
598 * non-alphanumeric character. That way, we can report
599 * the whole word as an unexpected token, rather than just
600 * some unintuitive prefix thereof.
602 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
606 * We got some sort of unexpected punctuation or an
607 * otherwise unexpected character, so just complain about
608 * that one character.
612 lex->prev_token_terminator = lex->token_terminator;
613 lex->token_terminator = s + 1;
614 report_invalid_token(lex);
618 * We've got a real alphanumeric token here. If it
619 * happens to be true, false, or null, all is well. If
622 lex->prev_token_terminator = lex->token_terminator;
623 lex->token_terminator = p;
626 if (memcmp(s, "true", 4) == 0)
627 lex->token_type = JSON_TOKEN_TRUE;
628 else if (memcmp(s, "null", 4) == 0)
629 lex->token_type = JSON_TOKEN_NULL;
631 report_invalid_token(lex);
633 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
634 lex->token_type = JSON_TOKEN_FALSE;
636 report_invalid_token(lex);
639 } /* end of switch */
643 * The next token in the input stream is known to be a string; lex it.
646 json_lex_string(JsonLexContext *lex)
650 int hi_surrogate = -1;
652 if (lex->strval != NULL)
653 resetStringInfo(lex->strval);
655 Assert(lex->input_length > 0);
656 s = lex->token_start;
657 len = lex->token_start - lex->input;
662 /* Premature end of the string. */
663 if (len >= lex->input_length)
665 lex->token_terminator = s;
666 report_invalid_token(lex);
670 else if ((unsigned char) *s < 32)
672 /* Per RFC4627, these characters MUST be escaped. */
673 /* Since *s isn't printable, exclude it from the context string */
674 lex->token_terminator = s;
676 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
677 errmsg("invalid input syntax for type json"),
678 errdetail("Character with value 0x%02x must be escaped.",
680 report_json_context(lex)));
684 /* OK, we have an escape character. */
687 if (len >= lex->input_length)
689 lex->token_terminator = s;
690 report_invalid_token(lex);
697 for (i = 1; i <= 4; i++)
701 if (len >= lex->input_length)
703 lex->token_terminator = s;
704 report_invalid_token(lex);
706 else if (*s >= '0' && *s <= '9')
707 ch = (ch * 16) + (*s - '0');
708 else if (*s >= 'a' && *s <= 'f')
709 ch = (ch * 16) + (*s - 'a') + 10;
710 else if (*s >= 'A' && *s <= 'F')
711 ch = (ch * 16) + (*s - 'A') + 10;
714 lex->token_terminator = s + pg_mblen(s);
716 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
717 errmsg("invalid input syntax for type json"),
718 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
719 report_json_context(lex)));
722 if (lex->strval != NULL)
727 if (ch >= 0xd800 && ch <= 0xdbff)
729 if (hi_surrogate != -1)
731 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
732 errmsg("invalid input syntax for type json"),
733 errdetail("Unicode high surrogate must not follow a high surrogate."),
734 report_json_context(lex)));
735 hi_surrogate = (ch & 0x3ff) << 10;
738 else if (ch >= 0xdc00 && ch <= 0xdfff)
740 if (hi_surrogate == -1)
742 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
743 errmsg("invalid input syntax for type json"),
744 errdetail("Unicode low surrogate must follow a high surrogate."),
745 report_json_context(lex)));
746 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
750 if (hi_surrogate != -1)
752 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
753 errmsg("invalid input syntax for type json"),
754 errdetail("Unicode low surrogate must follow a high surrogate."),
755 report_json_context(lex)));
758 * For UTF8, replace the escape sequence by the actual
759 * utf8 character in lex->strval. Do this also for other
760 * encodings if the escape designates an ASCII character,
761 * otherwise raise an error. We don't ever unescape a
762 * \u0000, since that would result in an impermissible nul
768 appendStringInfoString(lex->strval, "\\u0000");
770 else if (GetDatabaseEncoding() == PG_UTF8)
772 unicode_to_utf8(ch, (unsigned char *) utf8str);
773 utf8len = pg_utf_mblen((unsigned char *) utf8str);
774 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
776 else if (ch <= 0x007f)
779 * This is the only way to designate things like a
780 * form feed character in JSON, so it's useful in all
783 appendStringInfoChar(lex->strval, (char) ch);
788 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
789 errmsg("invalid input syntax for type json"),
790 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
791 report_json_context(lex)));
796 else if (lex->strval != NULL)
798 if (hi_surrogate != -1)
800 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
801 errmsg("invalid input syntax for type json"),
802 errdetail("Unicode low surrogate must follow a high surrogate."),
803 report_json_context(lex)));
810 appendStringInfoChar(lex->strval, *s);
813 appendStringInfoChar(lex->strval, '\b');
816 appendStringInfoChar(lex->strval, '\f');
819 appendStringInfoChar(lex->strval, '\n');
822 appendStringInfoChar(lex->strval, '\r');
825 appendStringInfoChar(lex->strval, '\t');
828 /* Not a valid string escape, so error out. */
829 lex->token_terminator = s + pg_mblen(s);
831 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
832 errmsg("invalid input syntax for type json"),
833 errdetail("Escape sequence \"\\%s\" is invalid.",
835 report_json_context(lex)));
838 else if (strchr("\"\\/bfnrt", *s) == NULL)
841 * Simpler processing if we're not bothered about de-escaping
843 * It's very tempting to remove the strchr() call here and
844 * replace it with a switch statement, but testing so far has
845 * shown it's not a performance win.
847 lex->token_terminator = s + pg_mblen(s);
849 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
850 errmsg("invalid input syntax for type json"),
851 errdetail("Escape sequence \"\\%s\" is invalid.",
853 report_json_context(lex)));
857 else if (lex->strval != NULL)
859 if (hi_surrogate != -1)
861 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
862 errmsg("invalid input syntax for type json"),
863 errdetail("Unicode low surrogate must follow a high surrogate."),
864 report_json_context(lex)));
866 appendStringInfoChar(lex->strval, *s);
871 if (hi_surrogate != -1)
873 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
874 errmsg("invalid input syntax for type json"),
875 errdetail("Unicode low surrogate must follow a high surrogate."),
876 report_json_context(lex)));
878 /* Hooray, we found the end of the string! */
879 lex->prev_token_terminator = lex->token_terminator;
880 lex->token_terminator = s + 1;
883 /*-------------------------------------------------------------------------
884 * The next token in the input stream is known to be a number; lex it.
886 * In JSON, a number consists of four parts:
888 * (1) An optional minus sign ('-').
890 * (2) Either a single '0', or a string of one or more digits that does not
893 * (3) An optional decimal part, consisting of a period ('.') followed by
894 * one or more digits. (Note: While this part can be omitted
895 * completely, it's not OK to have only the decimal point without
896 * any digits afterwards.)
898 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
899 * followed by '+' or '-', followed by one or more digits. (Note:
900 * As with the decimal part, if 'e' or 'E' is present, it must be
901 * followed by at least one digit.)
903 * The 's' argument to this function points to the ostensible beginning
904 * of part 2 - i.e. the character after any optional minus sign, and the
905 * first character of the string if there is none.
907 *-------------------------------------------------------------------------
910 json_lex_number(JsonLexContext *lex, char *s, bool *num_err)
916 len = s - lex->input;
917 /* Part (1): leading sign indicator. */
918 /* Caller already did this for us; so do nothing. */
920 /* Part (2): parse main digit string. */
926 else if (*s >= '1' && *s <= '9')
932 } while (len < lex->input_length && *s >= '0' && *s <= '9');
937 /* Part (3): parse optional decimal portion. */
938 if (len < lex->input_length && *s == '.')
942 if (len == lex->input_length || *s < '0' || *s > '9')
950 } while (len < lex->input_length && *s >= '0' && *s <= '9');
954 /* Part (4): parse optional exponent. */
955 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
959 if (len < lex->input_length && (*s == '+' || *s == '-'))
964 if (len == lex->input_length || *s < '0' || *s > '9')
972 } while (len < lex->input_length && *s >= '0' && *s <= '9');
977 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
978 * here should be considered part of the token for error-reporting
981 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
986 /* let the caller handle the error */
991 lex->prev_token_terminator = lex->token_terminator;
992 lex->token_terminator = p;
994 report_invalid_token(lex);
999 * Report a parse error.
1001 * lex->token_start and lex->token_terminator must identify the current token.
1004 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1009 /* Handle case where the input ended prematurely. */
1010 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1012 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1013 errmsg("invalid input syntax for type json"),
1014 errdetail("The input string ended unexpectedly."),
1015 report_json_context(lex)));
1017 /* Separate out the current token. */
1018 toklen = lex->token_terminator - lex->token_start;
1019 token = palloc(toklen + 1);
1020 memcpy(token, lex->token_start, toklen);
1021 token[toklen] = '\0';
1023 /* Complain, with the appropriate detail message. */
1024 if (ctx == JSON_PARSE_END)
1026 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1027 errmsg("invalid input syntax for type json"),
1028 errdetail("Expected end of input, but found \"%s\".",
1030 report_json_context(lex)));
1035 case JSON_PARSE_VALUE:
1037 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1038 errmsg("invalid input syntax for type json"),
1039 errdetail("Expected JSON value, but found \"%s\".",
1041 report_json_context(lex)));
1043 case JSON_PARSE_STRING:
1045 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1046 errmsg("invalid input syntax for type json"),
1047 errdetail("Expected string, but found \"%s\".",
1049 report_json_context(lex)));
1051 case JSON_PARSE_ARRAY_START:
1053 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1054 errmsg("invalid input syntax for type json"),
1055 errdetail("Expected array element or \"]\", but found \"%s\".",
1057 report_json_context(lex)));
1059 case JSON_PARSE_ARRAY_NEXT:
1061 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1062 errmsg("invalid input syntax for type json"),
1063 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1065 report_json_context(lex)));
1067 case JSON_PARSE_OBJECT_START:
1069 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1070 errmsg("invalid input syntax for type json"),
1071 errdetail("Expected string or \"}\", but found \"%s\".",
1073 report_json_context(lex)));
1075 case JSON_PARSE_OBJECT_LABEL:
1077 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1078 errmsg("invalid input syntax for type json"),
1079 errdetail("Expected \":\", but found \"%s\".",
1081 report_json_context(lex)));
1083 case JSON_PARSE_OBJECT_NEXT:
1085 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1086 errmsg("invalid input syntax for type json"),
1087 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1089 report_json_context(lex)));
1091 case JSON_PARSE_OBJECT_COMMA:
1093 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1094 errmsg("invalid input syntax for type json"),
1095 errdetail("Expected string, but found \"%s\".",
1097 report_json_context(lex)));
1100 elog(ERROR, "unexpected json parse state: %d", ctx);
1106 * Report an invalid input token.
1108 * lex->token_start and lex->token_terminator must identify the token.
1111 report_invalid_token(JsonLexContext *lex)
1116 /* Separate out the offending token. */
1117 toklen = lex->token_terminator - lex->token_start;
1118 token = palloc(toklen + 1);
1119 memcpy(token, lex->token_start, toklen);
1120 token[toklen] = '\0';
1123 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1124 errmsg("invalid input syntax for type json"),
1125 errdetail("Token \"%s\" is invalid.", token),
1126 report_json_context(lex)));
1130 * Report a CONTEXT line for bogus JSON input.
1132 * lex->token_terminator must be set to identify the spot where we detected
1133 * the error. Note that lex->token_start might be NULL, in case we recognized
1136 * The return value isn't meaningful, but we make it non-void so that this
1137 * can be invoked inside ereport().
1140 report_json_context(JsonLexContext *lex)
1142 const char *context_start;
1143 const char *context_end;
1144 const char *line_start;
1151 /* Choose boundaries for the part of the input we will display */
1152 context_start = lex->input;
1153 context_end = lex->token_terminator;
1154 line_start = context_start;
1158 /* Always advance over newlines */
1159 if (context_start < context_end && *context_start == '\n')
1162 line_start = context_start;
1166 /* Otherwise, done as soon as we are close enough to context_end */
1167 if (context_end - context_start < 50)
1169 /* Advance to next multibyte character */
1170 if (IS_HIGHBIT_SET(*context_start))
1171 context_start += pg_mblen(context_start);
1177 * We add "..." to indicate that the excerpt doesn't start at the
1178 * beginning of the line ... but if we're within 3 characters of the
1179 * beginning of the line, we might as well just show the whole line.
1181 if (context_start - line_start <= 3)
1182 context_start = line_start;
1184 /* Get a null-terminated copy of the data to present */
1185 ctxtlen = context_end - context_start;
1186 ctxt = palloc(ctxtlen + 1);
1187 memcpy(ctxt, context_start, ctxtlen);
1188 ctxt[ctxtlen] = '\0';
1191 * Show the context, prefixing "..." if not starting at start of line, and
1192 * suffixing "..." if not ending at end of line.
1194 prefix = (context_start > line_start) ? "..." : "";
1195 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1197 return errcontext("JSON data, line %d: %s%s%s",
1198 line_number, prefix, ctxt, suffix);
1202 * Extract a single, possibly multi-byte char from the input string.
1205 extract_mb_char(char *s)
1211 res = palloc(len + 1);
1212 memcpy(res, s, len);
1219 * Turn a scalar Datum into JSON, appending the string to "result".
1221 * Hand off a non-scalar datum to composite_to_json or array_to_json_internal
1225 datum_to_json(Datum val, bool is_null, StringInfo result,
1226 TYPCATEGORY tcategory, Oid typoutputfunc, bool key_scalar)
1231 JsonLexContext dummy_lex;
1235 appendStringInfoString(result, "null");
1241 case TYPCATEGORY_ARRAY:
1242 array_to_json_internal(val, result, false);
1244 case TYPCATEGORY_COMPOSITE:
1245 composite_to_json(val, result, false);
1247 case TYPCATEGORY_BOOLEAN:
1249 appendStringInfoString(result, DatumGetBool(val) ? "true" : "false");
1251 escape_json(result, DatumGetBool(val) ? "true" : "false");
1253 case TYPCATEGORY_NUMERIC:
1254 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1257 /* always quote keys */
1258 escape_json(result, outputstr);
1263 * Don't call escape_json for a non-key if it's a valid JSON
1266 dummy_lex.input = *outputstr == '-' ? outputstr + 1 : outputstr;
1267 dummy_lex.input_length = strlen(dummy_lex.input);
1268 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
1270 appendStringInfoString(result, outputstr);
1272 escape_json(result, outputstr);
1276 case TYPCATEGORY_JSON:
1277 /* JSON will already be escaped */
1278 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1279 appendStringInfoString(result, outputstr);
1282 case TYPCATEGORY_JSON_CAST:
1283 jsontext = DatumGetTextP(OidFunctionCall1(typoutputfunc, val));
1284 outputstr = text_to_cstring(jsontext);
1285 appendStringInfoString(result, outputstr);
1290 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1291 if (key_scalar && *outputstr == '\0')
1293 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1294 errmsg("key value must not be empty")));
1295 escape_json(result, outputstr);
1302 * Process a single dimension of an array.
1303 * If it's the innermost dimension, output the values, otherwise call
1304 * ourselves recursively to process the next dimension.
1307 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1308 bool *nulls, int *valcount, TYPCATEGORY tcategory,
1309 Oid typoutputfunc, bool use_line_feeds)
1314 Assert(dim < ndims);
1316 sep = use_line_feeds ? ",\n " : ",";
1318 appendStringInfoChar(result, '[');
1320 for (i = 1; i <= dims[dim]; i++)
1323 appendStringInfoString(result, sep);
1325 if (dim + 1 == ndims)
1327 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1328 typoutputfunc, false);
1334 * Do we want line feeds on inner dimensions of arrays? For now
1337 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1338 valcount, tcategory, typoutputfunc, false);
1342 appendStringInfoChar(result, ']');
1346 * Turn an array into JSON.
1349 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1351 ArrayType *v = DatumGetArrayTypeP(array);
1352 Oid element_type = ARR_ELEMTYPE(v);
1365 TYPCATEGORY tcategory;
1366 Oid castfunc = InvalidOid;
1370 nitems = ArrayGetNItems(ndim, dim);
1374 appendStringInfoString(result, "[]");
1378 get_type_io_data(element_type, IOFunc_output,
1379 &typlen, &typbyval, &typalign,
1380 &typdelim, &typioparam, &typoutputfunc);
1382 if (element_type > FirstNormalObjectId)
1385 Form_pg_cast castForm;
1387 tuple = SearchSysCache2(CASTSOURCETARGET,
1388 ObjectIdGetDatum(element_type),
1389 ObjectIdGetDatum(JSONOID));
1390 if (HeapTupleIsValid(tuple))
1392 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1394 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1395 castfunc = typoutputfunc = castForm->castfunc;
1397 ReleaseSysCache(tuple);
1401 deconstruct_array(v, element_type, typlen, typbyval,
1402 typalign, &elements, &nulls,
1405 if (castfunc != InvalidOid)
1406 tcategory = TYPCATEGORY_JSON_CAST;
1407 else if (element_type == RECORDOID)
1408 tcategory = TYPCATEGORY_COMPOSITE;
1409 else if (element_type == JSONOID)
1410 tcategory = TYPCATEGORY_JSON;
1412 tcategory = TypeCategory(element_type);
1414 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1415 typoutputfunc, use_line_feeds);
1422 * Turn a composite / record into JSON.
1425 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1431 HeapTupleData tmptup,
1434 bool needsep = false;
1437 sep = use_line_feeds ? ",\n " : ",";
1439 td = DatumGetHeapTupleHeader(composite);
1441 /* Extract rowtype info and find a tupdesc */
1442 tupType = HeapTupleHeaderGetTypeId(td);
1443 tupTypmod = HeapTupleHeaderGetTypMod(td);
1444 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1446 /* Build a temporary HeapTuple control structure */
1447 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1451 appendStringInfoChar(result, '{');
1453 for (i = 0; i < tupdesc->natts; i++)
1458 TYPCATEGORY tcategory;
1461 Oid castfunc = InvalidOid;
1463 if (tupdesc->attrs[i]->attisdropped)
1467 appendStringInfoString(result, sep);
1470 attname = NameStr(tupdesc->attrs[i]->attname);
1471 escape_json(result, attname);
1472 appendStringInfoChar(result, ':');
1474 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1476 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1477 &typoutput, &typisvarlena);
1479 if (tupdesc->attrs[i]->atttypid > FirstNormalObjectId)
1481 HeapTuple cast_tuple;
1482 Form_pg_cast castForm;
1484 cast_tuple = SearchSysCache2(CASTSOURCETARGET,
1485 ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),
1486 ObjectIdGetDatum(JSONOID));
1487 if (HeapTupleIsValid(cast_tuple))
1489 castForm = (Form_pg_cast) GETSTRUCT(cast_tuple);
1491 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1492 castfunc = typoutput = castForm->castfunc;
1494 ReleaseSysCache(cast_tuple);
1498 if (castfunc != InvalidOid)
1499 tcategory = TYPCATEGORY_JSON_CAST;
1500 else if (tupdesc->attrs[i]->atttypid == RECORDARRAYOID)
1501 tcategory = TYPCATEGORY_ARRAY;
1502 else if (tupdesc->attrs[i]->atttypid == RECORDOID)
1503 tcategory = TYPCATEGORY_COMPOSITE;
1504 else if (tupdesc->attrs[i]->atttypid == JSONOID)
1505 tcategory = TYPCATEGORY_JSON;
1507 tcategory = TypeCategory(tupdesc->attrs[i]->atttypid);
1509 datum_to_json(val, isnull, result, tcategory, typoutput, false);
1512 appendStringInfoChar(result, '}');
1513 ReleaseTupleDesc(tupdesc);
1517 * append Json for orig_val to result. If it's a field key, make sure it's
1518 * of an acceptable type and is quoted.
1521 add_json(Datum val, bool is_null, StringInfo result, Oid val_type, bool key_scalar)
1523 TYPCATEGORY tcategory;
1526 Oid castfunc = InvalidOid;
1528 if (val_type == InvalidOid)
1530 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1531 errmsg("could not determine input data type")));
1534 getTypeOutputInfo(val_type, &typoutput, &typisvarlena);
1536 if (val_type > FirstNormalObjectId)
1539 Form_pg_cast castForm;
1541 tuple = SearchSysCache2(CASTSOURCETARGET,
1542 ObjectIdGetDatum(val_type),
1543 ObjectIdGetDatum(JSONOID));
1544 if (HeapTupleIsValid(tuple))
1546 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1548 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1549 castfunc = typoutput = castForm->castfunc;
1551 ReleaseSysCache(tuple);
1555 if (castfunc != InvalidOid)
1556 tcategory = TYPCATEGORY_JSON_CAST;
1557 else if (val_type == RECORDARRAYOID)
1558 tcategory = TYPCATEGORY_ARRAY;
1559 else if (val_type == RECORDOID)
1560 tcategory = TYPCATEGORY_COMPOSITE;
1561 else if (val_type == JSONOID)
1562 tcategory = TYPCATEGORY_JSON;
1564 tcategory = TypeCategory(val_type);
1567 (tcategory == TYPCATEGORY_ARRAY ||
1568 tcategory == TYPCATEGORY_COMPOSITE ||
1569 tcategory == TYPCATEGORY_JSON ||
1570 tcategory == TYPCATEGORY_JSON_CAST))
1572 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1573 errmsg("key value must be scalar, not array, composite or json")));
1575 datum_to_json(val, is_null, result, tcategory, typoutput, key_scalar);
1579 * SQL function array_to_json(row)
1582 array_to_json(PG_FUNCTION_ARGS)
1584 Datum array = PG_GETARG_DATUM(0);
1587 result = makeStringInfo();
1589 array_to_json_internal(array, result, false);
1591 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1595 * SQL function array_to_json(row, prettybool)
1598 array_to_json_pretty(PG_FUNCTION_ARGS)
1600 Datum array = PG_GETARG_DATUM(0);
1601 bool use_line_feeds = PG_GETARG_BOOL(1);
1604 result = makeStringInfo();
1606 array_to_json_internal(array, result, use_line_feeds);
1608 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1612 * SQL function row_to_json(row)
1615 row_to_json(PG_FUNCTION_ARGS)
1617 Datum array = PG_GETARG_DATUM(0);
1620 result = makeStringInfo();
1622 composite_to_json(array, result, false);
1624 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1628 * SQL function row_to_json(row, prettybool)
1631 row_to_json_pretty(PG_FUNCTION_ARGS)
1633 Datum array = PG_GETARG_DATUM(0);
1634 bool use_line_feeds = PG_GETARG_BOOL(1);
1637 result = makeStringInfo();
1639 composite_to_json(array, result, use_line_feeds);
1641 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1645 * SQL function to_json(anyvalue)
1648 to_json(PG_FUNCTION_ARGS)
1650 Datum val = PG_GETARG_DATUM(0);
1651 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1653 TYPCATEGORY tcategory;
1656 Oid castfunc = InvalidOid;
1658 if (val_type == InvalidOid)
1660 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1661 errmsg("could not determine input data type")));
1663 result = makeStringInfo();
1665 getTypeOutputInfo(val_type, &typoutput, &typisvarlena);
1667 if (val_type > FirstNormalObjectId)
1670 Form_pg_cast castForm;
1672 tuple = SearchSysCache2(CASTSOURCETARGET,
1673 ObjectIdGetDatum(val_type),
1674 ObjectIdGetDatum(JSONOID));
1675 if (HeapTupleIsValid(tuple))
1677 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1679 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1680 castfunc = typoutput = castForm->castfunc;
1682 ReleaseSysCache(tuple);
1686 if (castfunc != InvalidOid)
1687 tcategory = TYPCATEGORY_JSON_CAST;
1688 else if (val_type == RECORDARRAYOID)
1689 tcategory = TYPCATEGORY_ARRAY;
1690 else if (val_type == RECORDOID)
1691 tcategory = TYPCATEGORY_COMPOSITE;
1692 else if (val_type == JSONOID)
1693 tcategory = TYPCATEGORY_JSON;
1695 tcategory = TypeCategory(val_type);
1697 datum_to_json(val, false, result, tcategory, typoutput, false);
1699 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1703 * json_agg transition function
1706 json_agg_transfn(PG_FUNCTION_ARGS)
1708 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1709 MemoryContext aggcontext,
1713 TYPCATEGORY tcategory;
1716 Oid castfunc = InvalidOid;
1718 if (val_type == InvalidOid)
1720 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1721 errmsg("could not determine input data type")));
1723 if (!AggCheckCallContext(fcinfo, &aggcontext))
1725 /* cannot be called directly because of internal-type argument */
1726 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1729 if (PG_ARGISNULL(0))
1732 * Make this StringInfo in a context where it will persist for the
1733 * duration off the aggregate call. It's only needed for this initial
1734 * piece, as the StringInfo routines make sure they use the right
1735 * context to enlarge the object if necessary.
1737 oldcontext = MemoryContextSwitchTo(aggcontext);
1738 state = makeStringInfo();
1739 MemoryContextSwitchTo(oldcontext);
1741 appendStringInfoChar(state, '[');
1745 state = (StringInfo) PG_GETARG_POINTER(0);
1746 appendStringInfoString(state, ", ");
1749 /* fast path for NULLs */
1750 if (PG_ARGISNULL(1))
1753 datum_to_json(val, true, state, 0, InvalidOid, false);
1754 PG_RETURN_POINTER(state);
1757 val = PG_GETARG_DATUM(1);
1759 getTypeOutputInfo(val_type, &typoutput, &typisvarlena);
1761 if (val_type > FirstNormalObjectId)
1764 Form_pg_cast castForm;
1766 tuple = SearchSysCache2(CASTSOURCETARGET,
1767 ObjectIdGetDatum(val_type),
1768 ObjectIdGetDatum(JSONOID));
1769 if (HeapTupleIsValid(tuple))
1771 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1773 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1774 castfunc = typoutput = castForm->castfunc;
1776 ReleaseSysCache(tuple);
1780 if (castfunc != InvalidOid)
1781 tcategory = TYPCATEGORY_JSON_CAST;
1782 else if (val_type == RECORDARRAYOID)
1783 tcategory = TYPCATEGORY_ARRAY;
1784 else if (val_type == RECORDOID)
1785 tcategory = TYPCATEGORY_COMPOSITE;
1786 else if (val_type == JSONOID)
1787 tcategory = TYPCATEGORY_JSON;
1789 tcategory = TypeCategory(val_type);
1791 if (!PG_ARGISNULL(0) &&
1792 (tcategory == TYPCATEGORY_ARRAY || tcategory == TYPCATEGORY_COMPOSITE))
1794 appendStringInfoString(state, "\n ");
1797 datum_to_json(val, false, state, tcategory, typoutput, false);
1800 * The transition type for array_agg() is declared to be "internal", which
1801 * is a pass-by-value type the same size as a pointer. So we can safely
1802 * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
1804 PG_RETURN_POINTER(state);
1808 * json_agg final function
1811 json_agg_finalfn(PG_FUNCTION_ARGS)
1815 /* cannot be called directly because of internal-type argument */
1816 Assert(AggCheckCallContext(fcinfo, NULL));
1818 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1823 appendStringInfoChar(state, ']');
1825 PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
1829 * json_object_agg transition function.
1831 * aggregate two input columns as a single json value.
1834 json_object_agg_transfn(PG_FUNCTION_ARGS)
1837 MemoryContext aggcontext,
1842 if (!AggCheckCallContext(fcinfo, &aggcontext))
1844 /* cannot be called directly because of internal-type argument */
1845 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1848 if (PG_ARGISNULL(0))
1851 * Make this StringInfo in a context where it will persist for the
1852 * duration off the aggregate call. It's only needed for this initial
1853 * piece, as the StringInfo routines make sure they use the right
1854 * context to enlarge the object if necessary.
1856 oldcontext = MemoryContextSwitchTo(aggcontext);
1857 state = makeStringInfo();
1858 MemoryContextSwitchTo(oldcontext);
1860 appendStringInfoString(state, "{ ");
1864 state = (StringInfo) PG_GETARG_POINTER(0);
1865 appendStringInfoString(state, ", ");
1868 if (PG_ARGISNULL(1))
1870 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1871 errmsg("field name must not be null")));
1874 val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1877 * turn a constant (more or less literal) value that's of unknown type
1878 * into text. Unknowns come in as a cstring pointer.
1880 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, 1))
1883 arg = CStringGetTextDatum(PG_GETARG_POINTER(1));
1887 arg = PG_GETARG_DATUM(1);
1890 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1892 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1893 errmsg("arg 1: could not determine data type")));
1895 add_json(arg, false, state, val_type, true);
1897 appendStringInfoString(state, " : ");
1899 val_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1900 /* see comments above */
1901 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, 2))
1904 if (PG_ARGISNULL(2))
1907 arg = CStringGetTextDatum(PG_GETARG_POINTER(2));
1911 arg = PG_GETARG_DATUM(2);
1914 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1916 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1917 errmsg("arg 2: could not determine data type")));
1919 add_json(arg, PG_ARGISNULL(2), state, val_type, false);
1921 PG_RETURN_POINTER(state);
1925 * json_object_agg final function.
1929 json_object_agg_finalfn(PG_FUNCTION_ARGS)
1933 /* cannot be called directly because of internal-type argument */
1934 Assert(AggCheckCallContext(fcinfo, NULL));
1936 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1939 PG_RETURN_TEXT_P(cstring_to_text("{}"));
1941 appendStringInfoString(state, " }");
1943 PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
1947 * SQL function json_build_object(variadic "any")
1950 json_build_object(PG_FUNCTION_ARGS)
1952 int nargs = PG_NARGS();
1962 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1963 errmsg("invalid number or arguments: object must be matched key value pairs")));
1965 result = makeStringInfo();
1967 appendStringInfoChar(result, '{');
1969 for (i = 0; i < nargs; i += 2)
1974 if (PG_ARGISNULL(i))
1976 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1977 errmsg("arg %d: key cannot be null", i + 1)));
1978 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
1981 * turn a constant (more or less literal) value that's of unknown type
1982 * into text. Unknowns come in as a cstring pointer.
1984 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
1987 if (PG_ARGISNULL(i))
1990 arg = CStringGetTextDatum(PG_GETARG_POINTER(i));
1994 arg = PG_GETARG_DATUM(i);
1996 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1998 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1999 errmsg("arg %d: could not determine data type", i + 1)));
2000 appendStringInfoString(result, sep);
2002 add_json(arg, false, result, val_type, true);
2004 appendStringInfoString(result, " : ");
2008 val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
2009 /* see comments above */
2010 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i + 1))
2013 if (PG_ARGISNULL(i + 1))
2016 arg = CStringGetTextDatum(PG_GETARG_POINTER(i + 1));
2020 arg = PG_GETARG_DATUM(i + 1);
2022 if (val_type == InvalidOid || val_type == UNKNOWNOID)
2024 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2025 errmsg("arg %d: could not determine data type", i + 2)));
2026 add_json(arg, PG_ARGISNULL(i + 1), result, val_type, false);
2029 appendStringInfoChar(result, '}');
2031 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2036 * degenerate case of json_build_object where it gets 0 arguments.
2039 json_build_object_noargs(PG_FUNCTION_ARGS)
2041 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2045 * SQL function json_build_array(variadic "any")
2048 json_build_array(PG_FUNCTION_ARGS)
2050 int nargs = PG_NARGS();
2058 result = makeStringInfo();
2060 appendStringInfoChar(result, '[');
2062 for (i = 0; i < nargs; i++)
2064 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2065 arg = PG_GETARG_DATUM(i + 1);
2066 /* see comments in json_build_object above */
2067 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
2070 if (PG_ARGISNULL(i))
2073 arg = CStringGetTextDatum(PG_GETARG_POINTER(i));
2077 arg = PG_GETARG_DATUM(i);
2079 if (val_type == InvalidOid || val_type == UNKNOWNOID)
2081 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2082 errmsg("arg %d: could not determine data type", i + 1)));
2083 appendStringInfoString(result, sep);
2085 add_json(arg, PG_ARGISNULL(i), result, val_type, false);
2087 appendStringInfoChar(result, ']');
2089 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2094 * degenerate case of json_build_array where it gets 0 arguments.
2097 json_build_array_noargs(PG_FUNCTION_ARGS)
2099 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2103 * SQL function json_object(text[])
2105 * take a one or two dimensional array of text as name vale pairs
2106 * for a json object.
2110 json_object(PG_FUNCTION_ARGS)
2112 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2113 int ndims = ARR_NDIM(in_array);
2114 StringInfoData result;
2126 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2130 if ((ARR_DIMS(in_array)[0]) % 2)
2132 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2133 errmsg("array must have even number of elements")));
2137 if ((ARR_DIMS(in_array)[1]) != 2)
2139 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2140 errmsg("array must have two columns")));
2145 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2146 errmsg("wrong number of array subscripts")));
2149 deconstruct_array(in_array,
2150 TEXTOID, -1, false, 'i',
2151 &in_datums, &in_nulls, &in_count);
2153 count = in_count / 2;
2155 initStringInfo(&result);
2157 appendStringInfoChar(&result, '{');
2159 for (i = 0; i < count; ++i)
2161 if (in_nulls[i * 2])
2163 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2164 errmsg("null value not allowed for object key")));
2166 v = TextDatumGetCString(in_datums[i * 2]);
2169 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2170 errmsg("empty value not allowed for object key")));
2172 appendStringInfoString(&result, ", ");
2173 escape_json(&result, v);
2174 appendStringInfoString(&result, " : ");
2176 if (in_nulls[i * 2 + 1])
2177 appendStringInfoString(&result, "null");
2180 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2181 escape_json(&result, v);
2186 appendStringInfoChar(&result, '}');
2191 rval = cstring_to_text_with_len(result.data, result.len);
2194 PG_RETURN_TEXT_P(rval);
2199 * SQL function json_object(text[], text[])
2201 * take separate name and value arrays of text to construct a json object
2205 json_object_two_arg(PG_FUNCTION_ARGS)
2207 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2208 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2209 int nkdims = ARR_NDIM(key_array);
2210 int nvdims = ARR_NDIM(val_array);
2211 StringInfoData result;
2222 if (nkdims > 1 || nkdims != nvdims)
2224 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2225 errmsg("wrong number of array subscripts")));
2228 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2230 deconstruct_array(key_array,
2231 TEXTOID, -1, false, 'i',
2232 &key_datums, &key_nulls, &key_count);
2234 deconstruct_array(val_array,
2235 TEXTOID, -1, false, 'i',
2236 &val_datums, &val_nulls, &val_count);
2238 if (key_count != val_count)
2240 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2241 errmsg("mismatched array dimensions")));
2243 initStringInfo(&result);
2245 appendStringInfoChar(&result, '{');
2247 for (i = 0; i < key_count; ++i)
2251 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2252 errmsg("null value not allowed for object key")));
2254 v = TextDatumGetCString(key_datums[i]);
2257 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2258 errmsg("empty value not allowed for object key")));
2260 appendStringInfoString(&result, ", ");
2261 escape_json(&result, v);
2262 appendStringInfoString(&result, " : ");
2265 appendStringInfoString(&result, "null");
2268 v = TextDatumGetCString(val_datums[i]);
2269 escape_json(&result, v);
2274 appendStringInfoChar(&result, '}');
2281 rval = cstring_to_text_with_len(result.data, result.len);
2284 PG_RETURN_TEXT_P(rval);
2290 * Produce a JSON string literal, properly escaping characters in the text.
2293 escape_json(StringInfo buf, const char *str)
2297 appendStringInfoCharMacro(buf, '\"');
2298 for (p = str; *p; p++)
2303 appendStringInfoString(buf, "\\b");
2306 appendStringInfoString(buf, "\\f");
2309 appendStringInfoString(buf, "\\n");
2312 appendStringInfoString(buf, "\\r");
2315 appendStringInfoString(buf, "\\t");
2318 appendStringInfoString(buf, "\\\"");
2321 appendStringInfoString(buf, "\\\\");
2324 if ((unsigned char) *p < ' ')
2325 appendStringInfo(buf, "\\u%04x", (int) *p);
2327 appendStringInfoCharMacro(buf, *p);
2331 appendStringInfoCharMacro(buf, '\"');
2335 * SQL function json_typeof(json) -> text
2337 * Returns the type of the outermost JSON value as TEXT. Possible types are
2338 * "object", "array", "string", "number", "boolean", and "null".
2340 * Performs a single call to json_lex() to get the first token of the supplied
2341 * value. This initial token uniquely determines the value's type. As our
2342 * input must already have been validated by json_in() or json_recv(), the
2343 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2344 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2347 json_typeof(PG_FUNCTION_ARGS)
2349 text *json = PG_GETARG_TEXT_P(0);
2351 JsonLexContext *lex = makeJsonLexContext(json, false);
2355 /* Lex exactly one token from the input and check its type. */
2357 tok = lex_peek(lex);
2360 case JSON_TOKEN_OBJECT_START:
2363 case JSON_TOKEN_ARRAY_START:
2366 case JSON_TOKEN_STRING:
2369 case JSON_TOKEN_NUMBER:
2372 case JSON_TOKEN_TRUE:
2373 case JSON_TOKEN_FALSE:
2376 case JSON_TOKEN_NULL:
2380 elog(ERROR, "unexpected json token: %d", tok);
2383 PG_RETURN_TEXT_P(cstring_to_text(type));