]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/json.c
Fix IsValidJsonNumber() to notice trailing non-alphanumeric garbage.
[postgresql] / src / backend / utils / adt / json.c
1 /*-------------------------------------------------------------------------
2  *
3  * json.c
4  *              JSON data type support.
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        src/backend/utils/adt/json.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15
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"
34
35 /*
36  * The context of the parser is maintained by the recursive descent
37  * mechanism, but is passed explicitly to the error reporting routine
38  * for better diagnostics.
39  */
40 typedef enum                                    /* contexts of JSON parser */
41 {
42         JSON_PARSE_VALUE,                       /* expecting a value */
43         JSON_PARSE_STRING,                      /* expecting a string (for a field name) */
44         JSON_PARSE_ARRAY_START,         /* saw '[', expecting value or ']' */
45         JSON_PARSE_ARRAY_NEXT,          /* saw array element, expecting ',' or ']' */
46         JSON_PARSE_OBJECT_START,        /* saw '{', expecting label or '}' */
47         JSON_PARSE_OBJECT_LABEL,        /* saw object label, expecting ':' */
48         JSON_PARSE_OBJECT_NEXT,         /* saw object value, expecting ',' or '}' */
49         JSON_PARSE_OBJECT_COMMA,        /* saw object ',', expecting next label */
50         JSON_PARSE_END                          /* saw the end of a document, expect nothing */
51 } JsonParseContext;
52
53 typedef enum                                    /* type categories for datum_to_json */
54 {
55         JSONTYPE_NULL,                          /* null, so we didn't bother to identify */
56         JSONTYPE_BOOL,                          /* boolean (built-in types only) */
57         JSONTYPE_NUMERIC,                       /* numeric (ditto) */
58         JSONTYPE_DATE,                          /* we use special formatting for datetimes */
59         JSONTYPE_TIMESTAMP,
60         JSONTYPE_TIMESTAMPTZ,
61         JSONTYPE_JSON,                          /* JSON itself (and JSONB) */
62         JSONTYPE_ARRAY,                         /* array */
63         JSONTYPE_COMPOSITE,                     /* composite */
64         JSONTYPE_CAST,                          /* something with an explicit cast to JSON */
65         JSONTYPE_OTHER                          /* all else */
66 } JsonTypeCategory;
67
68 typedef struct JsonAggState
69 {
70         StringInfo      str;
71         JsonTypeCategory key_category;
72         Oid                     key_output_func;
73         JsonTypeCategory val_category;
74         Oid                     val_output_func;
75 } JsonAggState;
76
77 static inline void json_lex(JsonLexContext *lex);
78 static inline void json_lex_string(JsonLexContext *lex);
79 static inline void json_lex_number(JsonLexContext *lex, char *s,
80                                 bool *num_err, int *total_len);
81 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
82 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
83 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
84 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
85 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
86 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
87 static void report_invalid_token(JsonLexContext *lex);
88 static int      report_json_context(JsonLexContext *lex);
89 static char *extract_mb_char(char *s);
90 static void composite_to_json(Datum composite, StringInfo result,
91                                   bool use_line_feeds);
92 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
93                                   Datum *vals, bool *nulls, int *valcount,
94                                   JsonTypeCategory tcategory, Oid outfuncoid,
95                                   bool use_line_feeds);
96 static void array_to_json_internal(Datum array, StringInfo result,
97                                            bool use_line_feeds);
98 static void json_categorize_type(Oid typoid,
99                                          JsonTypeCategory *tcategory,
100                                          Oid *outfuncoid);
101 static void datum_to_json(Datum val, bool is_null, StringInfo result,
102                           JsonTypeCategory tcategory, Oid outfuncoid,
103                           bool key_scalar);
104 static void add_json(Datum val, bool is_null, StringInfo result,
105                  Oid val_type, bool key_scalar);
106 static text *catenate_stringinfo_string(StringInfo buffer, const char *addon);
107
108 /* the null action object used for pure validation */
109 static JsonSemAction nullSemAction =
110 {
111         NULL, NULL, NULL, NULL, NULL,
112         NULL, NULL, NULL, NULL, NULL
113 };
114
115 /* Recursive Descent parser support routines */
116
117 /*
118  * lex_peek
119  *
120  * what is the current look_ahead token?
121 */
122 static inline JsonTokenType
123 lex_peek(JsonLexContext *lex)
124 {
125         return lex->token_type;
126 }
127
128 /*
129  * lex_accept
130  *
131  * accept the look_ahead token and move the lexer to the next token if the
132  * look_ahead token matches the token parameter. In that case, and if required,
133  * also hand back the de-escaped lexeme.
134  *
135  * returns true if the token matched, false otherwise.
136  */
137 static inline bool
138 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
139 {
140         if (lex->token_type == token)
141         {
142                 if (lexeme != NULL)
143                 {
144                         if (lex->token_type == JSON_TOKEN_STRING)
145                         {
146                                 if (lex->strval != NULL)
147                                         *lexeme = pstrdup(lex->strval->data);
148                         }
149                         else
150                         {
151                                 int                     len = (lex->token_terminator - lex->token_start);
152                                 char       *tokstr = palloc(len + 1);
153
154                                 memcpy(tokstr, lex->token_start, len);
155                                 tokstr[len] = '\0';
156                                 *lexeme = tokstr;
157                         }
158                 }
159                 json_lex(lex);
160                 return true;
161         }
162         return false;
163 }
164
165 /*
166  * lex_accept
167  *
168  * move the lexer to the next token if the current look_ahead token matches
169  * the parameter token. Otherwise, report an error.
170  */
171 static inline void
172 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
173 {
174         if (!lex_accept(lex, token, NULL))
175                 report_parse_error(ctx, lex);
176 }
177
178 /* chars to consider as part of an alphanumeric token */
179 #define JSON_ALPHANUMERIC_CHAR(c)  \
180         (((c) >= 'a' && (c) <= 'z') || \
181          ((c) >= 'A' && (c) <= 'Z') || \
182          ((c) >= '0' && (c) <= '9') || \
183          (c) == '_' || \
184          IS_HIGHBIT_SET(c))
185
186 /*
187  * Utility function to check if a string is a valid JSON number.
188  *
189  * str is of length len, and need not be null-terminated.
190  */
191 bool
192 IsValidJsonNumber(const char *str, int len)
193 {
194         bool            numeric_error;
195         int                     total_len;
196         JsonLexContext dummy_lex;
197
198         if (len <= 0)
199                 return false;
200
201         /*
202          * json_lex_number expects a leading  '-' to have been eaten already.
203          *
204          * having to cast away the constness of str is ugly, but there's not much
205          * easy alternative.
206          */
207         if (*str == '-')
208         {
209                 dummy_lex.input = (char *) str + 1;
210                 dummy_lex.input_length = len - 1;
211         }
212         else
213         {
214                 dummy_lex.input = (char *) str;
215                 dummy_lex.input_length = len;
216         }
217
218         json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error, &total_len);
219
220         return (!numeric_error) && (total_len == dummy_lex.input_length);
221 }
222
223 /*
224  * Input.
225  */
226 Datum
227 json_in(PG_FUNCTION_ARGS)
228 {
229         char       *json = PG_GETARG_CSTRING(0);
230         text       *result = cstring_to_text(json);
231         JsonLexContext *lex;
232
233         /* validate it */
234         lex = makeJsonLexContext(result, false);
235         pg_parse_json(lex, &nullSemAction);
236
237         /* Internal representation is the same as text, for now */
238         PG_RETURN_TEXT_P(result);
239 }
240
241 /*
242  * Output.
243  */
244 Datum
245 json_out(PG_FUNCTION_ARGS)
246 {
247         /* we needn't detoast because text_to_cstring will handle that */
248         Datum           txt = PG_GETARG_DATUM(0);
249
250         PG_RETURN_CSTRING(TextDatumGetCString(txt));
251 }
252
253 /*
254  * Binary send.
255  */
256 Datum
257 json_send(PG_FUNCTION_ARGS)
258 {
259         text       *t = PG_GETARG_TEXT_PP(0);
260         StringInfoData buf;
261
262         pq_begintypsend(&buf);
263         pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
264         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
265 }
266
267 /*
268  * Binary receive.
269  */
270 Datum
271 json_recv(PG_FUNCTION_ARGS)
272 {
273         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
274         char       *str;
275         int                     nbytes;
276         JsonLexContext *lex;
277
278         str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
279
280         /* Validate it. */
281         lex = makeJsonLexContextCstringLen(str, nbytes, false);
282         pg_parse_json(lex, &nullSemAction);
283
284         PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
285 }
286
287 /*
288  * makeJsonLexContext
289  *
290  * lex constructor, with or without StringInfo object
291  * for de-escaped lexemes.
292  *
293  * Without is better as it makes the processing faster, so only make one
294  * if really required.
295  *
296  * If you already have the json as a text* value, use the first of these
297  * functions, otherwise use  makeJsonLexContextCstringLen().
298  */
299 JsonLexContext *
300 makeJsonLexContext(text *json, bool need_escapes)
301 {
302         return makeJsonLexContextCstringLen(VARDATA(json),
303                                                                                 VARSIZE(json) - VARHDRSZ,
304                                                                                 need_escapes);
305 }
306
307 JsonLexContext *
308 makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
309 {
310         JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
311
312         lex->input = lex->token_terminator = lex->line_start = json;
313         lex->line_number = 1;
314         lex->input_length = len;
315         if (need_escapes)
316                 lex->strval = makeStringInfo();
317         return lex;
318 }
319
320 /*
321  * pg_parse_json
322  *
323  * Publicly visible entry point for the JSON parser.
324  *
325  * lex is a lexing context, set up for the json to be processed by calling
326  * makeJsonLexContext(). sem is a strucure of function pointers to semantic
327  * action routines to be called at appropriate spots during parsing, and a
328  * pointer to a state object to be passed to those routines.
329  */
330 void
331 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
332 {
333         JsonTokenType tok;
334
335         /* get the initial token */
336         json_lex(lex);
337
338         tok = lex_peek(lex);
339
340         /* parse by recursive descent */
341         switch (tok)
342         {
343                 case JSON_TOKEN_OBJECT_START:
344                         parse_object(lex, sem);
345                         break;
346                 case JSON_TOKEN_ARRAY_START:
347                         parse_array(lex, sem);
348                         break;
349                 default:
350                         parse_scalar(lex, sem);         /* json can be a bare scalar */
351         }
352
353         lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
354
355 }
356
357 /*
358  * json_count_array_elements
359  *
360  * Returns number of array elements in lex context at start of array token
361  * until end of array token at same nesting level.
362  *
363  * Designed to be called from array_start routines.
364  */
365 int
366 json_count_array_elements(JsonLexContext *lex)
367 {
368         JsonLexContext copylex;
369         int                     count;
370
371         /*
372          * It's safe to do this with a shallow copy because the lexical routines
373          * don't scribble on the input. They do scribble on the other pointers
374          * etc, so doing this with a copy makes that safe.
375          */
376         memcpy(&copylex, lex, sizeof(JsonLexContext));
377         copylex.strval = NULL;          /* not interested in values here */
378         copylex.lex_level++;
379
380         count = 0;
381         lex_expect(JSON_PARSE_ARRAY_START, &copylex, JSON_TOKEN_ARRAY_START);
382         if (lex_peek(&copylex) != JSON_TOKEN_ARRAY_END)
383         {
384                 do
385                 {
386                         count++;
387                         parse_array_element(&copylex, &nullSemAction);
388                 }
389                 while (lex_accept(&copylex, JSON_TOKEN_COMMA, NULL));
390         }
391         lex_expect(JSON_PARSE_ARRAY_NEXT, &copylex, JSON_TOKEN_ARRAY_END);
392
393         return count;
394 }
395
396 /*
397  *      Recursive Descent parse routines. There is one for each structural
398  *      element in a json document:
399  *        - scalar (string, number, true, false, null)
400  *        - array  ( [ ] )
401  *        - array element
402  *        - object ( { } )
403  *        - object field
404  */
405 static inline void
406 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
407 {
408         char       *val = NULL;
409         json_scalar_action sfunc = sem->scalar;
410         char      **valaddr;
411         JsonTokenType tok = lex_peek(lex);
412
413         valaddr = sfunc == NULL ? NULL : &val;
414
415         /* a scalar must be a string, a number, true, false, or null */
416         switch (tok)
417         {
418                 case JSON_TOKEN_TRUE:
419                         lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
420                         break;
421                 case JSON_TOKEN_FALSE:
422                         lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
423                         break;
424                 case JSON_TOKEN_NULL:
425                         lex_accept(lex, JSON_TOKEN_NULL, valaddr);
426                         break;
427                 case JSON_TOKEN_NUMBER:
428                         lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
429                         break;
430                 case JSON_TOKEN_STRING:
431                         lex_accept(lex, JSON_TOKEN_STRING, valaddr);
432                         break;
433                 default:
434                         report_parse_error(JSON_PARSE_VALUE, lex);
435         }
436
437         if (sfunc != NULL)
438                 (*sfunc) (sem->semstate, val, tok);
439 }
440
441 static void
442 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
443 {
444         /*
445          * An object field is "fieldname" : value where value can be a scalar,
446          * object or array.  Note: in user-facing docs and error messages, we
447          * generally call a field name a "key".
448          */
449
450         char       *fname = NULL;       /* keep compiler quiet */
451         json_ofield_action ostart = sem->object_field_start;
452         json_ofield_action oend = sem->object_field_end;
453         bool            isnull;
454         char      **fnameaddr = NULL;
455         JsonTokenType tok;
456
457         if (ostart != NULL || oend != NULL)
458                 fnameaddr = &fname;
459
460         if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
461                 report_parse_error(JSON_PARSE_STRING, lex);
462
463         lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
464
465         tok = lex_peek(lex);
466         isnull = tok == JSON_TOKEN_NULL;
467
468         if (ostart != NULL)
469                 (*ostart) (sem->semstate, fname, isnull);
470
471         switch (tok)
472         {
473                 case JSON_TOKEN_OBJECT_START:
474                         parse_object(lex, sem);
475                         break;
476                 case JSON_TOKEN_ARRAY_START:
477                         parse_array(lex, sem);
478                         break;
479                 default:
480                         parse_scalar(lex, sem);
481         }
482
483         if (oend != NULL)
484                 (*oend) (sem->semstate, fname, isnull);
485 }
486
487 static void
488 parse_object(JsonLexContext *lex, JsonSemAction *sem)
489 {
490         /*
491          * an object is a possibly empty sequence of object fields, separated by
492          * commas and surrounded by curly braces.
493          */
494         json_struct_action ostart = sem->object_start;
495         json_struct_action oend = sem->object_end;
496         JsonTokenType tok;
497
498         check_stack_depth();
499
500         if (ostart != NULL)
501                 (*ostart) (sem->semstate);
502
503         /*
504          * Data inside an object is at a higher nesting level than the object
505          * itself. Note that we increment this after we call the semantic routine
506          * for the object start and restore it before we call the routine for the
507          * object end.
508          */
509         lex->lex_level++;
510
511         /* we know this will succeeed, just clearing the token */
512         lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
513
514         tok = lex_peek(lex);
515         switch (tok)
516         {
517                 case JSON_TOKEN_STRING:
518                         parse_object_field(lex, sem);
519                         while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
520                                 parse_object_field(lex, sem);
521                         break;
522                 case JSON_TOKEN_OBJECT_END:
523                         break;
524                 default:
525                         /* case of an invalid initial token inside the object */
526                         report_parse_error(JSON_PARSE_OBJECT_START, lex);
527         }
528
529         lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
530
531         lex->lex_level--;
532
533         if (oend != NULL)
534                 (*oend) (sem->semstate);
535 }
536
537 static void
538 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
539 {
540         json_aelem_action astart = sem->array_element_start;
541         json_aelem_action aend = sem->array_element_end;
542         JsonTokenType tok = lex_peek(lex);
543
544         bool            isnull;
545
546         isnull = tok == JSON_TOKEN_NULL;
547
548         if (astart != NULL)
549                 (*astart) (sem->semstate, isnull);
550
551         /* an array element is any object, array or scalar */
552         switch (tok)
553         {
554                 case JSON_TOKEN_OBJECT_START:
555                         parse_object(lex, sem);
556                         break;
557                 case JSON_TOKEN_ARRAY_START:
558                         parse_array(lex, sem);
559                         break;
560                 default:
561                         parse_scalar(lex, sem);
562         }
563
564         if (aend != NULL)
565                 (*aend) (sem->semstate, isnull);
566 }
567
568 static void
569 parse_array(JsonLexContext *lex, JsonSemAction *sem)
570 {
571         /*
572          * an array is a possibly empty sequence of array elements, separated by
573          * commas and surrounded by square brackets.
574          */
575         json_struct_action astart = sem->array_start;
576         json_struct_action aend = sem->array_end;
577
578         check_stack_depth();
579
580         if (astart != NULL)
581                 (*astart) (sem->semstate);
582
583         /*
584          * Data inside an array is at a higher nesting level than the array
585          * itself. Note that we increment this after we call the semantic routine
586          * for the array start and restore it before we call the routine for the
587          * array end.
588          */
589         lex->lex_level++;
590
591         lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
592         if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
593         {
594
595                 parse_array_element(lex, sem);
596
597                 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
598                         parse_array_element(lex, sem);
599         }
600
601         lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
602
603         lex->lex_level--;
604
605         if (aend != NULL)
606                 (*aend) (sem->semstate);
607 }
608
609 /*
610  * Lex one token from the input stream.
611  */
612 static inline void
613 json_lex(JsonLexContext *lex)
614 {
615         char       *s;
616         int                     len;
617
618         /* Skip leading whitespace. */
619         s = lex->token_terminator;
620         len = s - lex->input;
621         while (len < lex->input_length &&
622                    (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
623         {
624                 if (*s == '\n')
625                         ++lex->line_number;
626                 ++s;
627                 ++len;
628         }
629         lex->token_start = s;
630
631         /* Determine token type. */
632         if (len >= lex->input_length)
633         {
634                 lex->token_start = NULL;
635                 lex->prev_token_terminator = lex->token_terminator;
636                 lex->token_terminator = s;
637                 lex->token_type = JSON_TOKEN_END;
638         }
639         else
640                 switch (*s)
641                 {
642                                 /* Single-character token, some kind of punctuation mark. */
643                         case '{':
644                                 lex->prev_token_terminator = lex->token_terminator;
645                                 lex->token_terminator = s + 1;
646                                 lex->token_type = JSON_TOKEN_OBJECT_START;
647                                 break;
648                         case '}':
649                                 lex->prev_token_terminator = lex->token_terminator;
650                                 lex->token_terminator = s + 1;
651                                 lex->token_type = JSON_TOKEN_OBJECT_END;
652                                 break;
653                         case '[':
654                                 lex->prev_token_terminator = lex->token_terminator;
655                                 lex->token_terminator = s + 1;
656                                 lex->token_type = JSON_TOKEN_ARRAY_START;
657                                 break;
658                         case ']':
659                                 lex->prev_token_terminator = lex->token_terminator;
660                                 lex->token_terminator = s + 1;
661                                 lex->token_type = JSON_TOKEN_ARRAY_END;
662                                 break;
663                         case ',':
664                                 lex->prev_token_terminator = lex->token_terminator;
665                                 lex->token_terminator = s + 1;
666                                 lex->token_type = JSON_TOKEN_COMMA;
667                                 break;
668                         case ':':
669                                 lex->prev_token_terminator = lex->token_terminator;
670                                 lex->token_terminator = s + 1;
671                                 lex->token_type = JSON_TOKEN_COLON;
672                                 break;
673                         case '"':
674                                 /* string */
675                                 json_lex_string(lex);
676                                 lex->token_type = JSON_TOKEN_STRING;
677                                 break;
678                         case '-':
679                                 /* Negative number. */
680                                 json_lex_number(lex, s + 1, NULL, NULL);
681                                 lex->token_type = JSON_TOKEN_NUMBER;
682                                 break;
683                         case '0':
684                         case '1':
685                         case '2':
686                         case '3':
687                         case '4':
688                         case '5':
689                         case '6':
690                         case '7':
691                         case '8':
692                         case '9':
693                                 /* Positive number. */
694                                 json_lex_number(lex, s, NULL, NULL);
695                                 lex->token_type = JSON_TOKEN_NUMBER;
696                                 break;
697                         default:
698                                 {
699                                         char       *p;
700
701                                         /*
702                                          * We're not dealing with a string, number, legal
703                                          * punctuation mark, or end of string.  The only legal
704                                          * tokens we might find here are true, false, and null,
705                                          * but for error reporting purposes we scan until we see a
706                                          * non-alphanumeric character.  That way, we can report
707                                          * the whole word as an unexpected token, rather than just
708                                          * some unintuitive prefix thereof.
709                                          */
710                                         for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
711                                                  /* skip */ ;
712
713                                         /*
714                                          * We got some sort of unexpected punctuation or an
715                                          * otherwise unexpected character, so just complain about
716                                          * that one character.
717                                          */
718                                         if (p == s)
719                                         {
720                                                 lex->prev_token_terminator = lex->token_terminator;
721                                                 lex->token_terminator = s + 1;
722                                                 report_invalid_token(lex);
723                                         }
724
725                                         /*
726                                          * We've got a real alphanumeric token here.  If it
727                                          * happens to be true, false, or null, all is well.  If
728                                          * not, error out.
729                                          */
730                                         lex->prev_token_terminator = lex->token_terminator;
731                                         lex->token_terminator = p;
732                                         if (p - s == 4)
733                                         {
734                                                 if (memcmp(s, "true", 4) == 0)
735                                                         lex->token_type = JSON_TOKEN_TRUE;
736                                                 else if (memcmp(s, "null", 4) == 0)
737                                                         lex->token_type = JSON_TOKEN_NULL;
738                                                 else
739                                                         report_invalid_token(lex);
740                                         }
741                                         else if (p - s == 5 && memcmp(s, "false", 5) == 0)
742                                                 lex->token_type = JSON_TOKEN_FALSE;
743                                         else
744                                                 report_invalid_token(lex);
745
746                                 }
747                 }                                               /* end of switch */
748 }
749
750 /*
751  * The next token in the input stream is known to be a string; lex it.
752  */
753 static inline void
754 json_lex_string(JsonLexContext *lex)
755 {
756         char       *s;
757         int                     len;
758         int                     hi_surrogate = -1;
759
760         if (lex->strval != NULL)
761                 resetStringInfo(lex->strval);
762
763         Assert(lex->input_length > 0);
764         s = lex->token_start;
765         len = lex->token_start - lex->input;
766         for (;;)
767         {
768                 s++;
769                 len++;
770                 /* Premature end of the string. */
771                 if (len >= lex->input_length)
772                 {
773                         lex->token_terminator = s;
774                         report_invalid_token(lex);
775                 }
776                 else if (*s == '"')
777                         break;
778                 else if ((unsigned char) *s < 32)
779                 {
780                         /* Per RFC4627, these characters MUST be escaped. */
781                         /* Since *s isn't printable, exclude it from the context string */
782                         lex->token_terminator = s;
783                         ereport(ERROR,
784                                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
785                                          errmsg("invalid input syntax for type json"),
786                                          errdetail("Character with value 0x%02x must be escaped.",
787                                                            (unsigned char) *s),
788                                          report_json_context(lex)));
789                 }
790                 else if (*s == '\\')
791                 {
792                         /* OK, we have an escape character. */
793                         s++;
794                         len++;
795                         if (len >= lex->input_length)
796                         {
797                                 lex->token_terminator = s;
798                                 report_invalid_token(lex);
799                         }
800                         else if (*s == 'u')
801                         {
802                                 int                     i;
803                                 int                     ch = 0;
804
805                                 for (i = 1; i <= 4; i++)
806                                 {
807                                         s++;
808                                         len++;
809                                         if (len >= lex->input_length)
810                                         {
811                                                 lex->token_terminator = s;
812                                                 report_invalid_token(lex);
813                                         }
814                                         else if (*s >= '0' && *s <= '9')
815                                                 ch = (ch * 16) + (*s - '0');
816                                         else if (*s >= 'a' && *s <= 'f')
817                                                 ch = (ch * 16) + (*s - 'a') + 10;
818                                         else if (*s >= 'A' && *s <= 'F')
819                                                 ch = (ch * 16) + (*s - 'A') + 10;
820                                         else
821                                         {
822                                                 lex->token_terminator = s + pg_mblen(s);
823                                                 ereport(ERROR,
824                                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
825                                                                  errmsg("invalid input syntax for type json"),
826                                                                  errdetail("\"\\u\" must be followed by four hexadecimal digits."),
827                                                                  report_json_context(lex)));
828                                         }
829                                 }
830                                 if (lex->strval != NULL)
831                                 {
832                                         char            utf8str[5];
833                                         int                     utf8len;
834
835                                         if (ch >= 0xd800 && ch <= 0xdbff)
836                                         {
837                                                 if (hi_surrogate != -1)
838                                                         ereport(ERROR,
839                                                            (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
840                                                                 errmsg("invalid input syntax for type json"),
841                                                                 errdetail("Unicode high surrogate must not follow a high surrogate."),
842                                                                 report_json_context(lex)));
843                                                 hi_surrogate = (ch & 0x3ff) << 10;
844                                                 continue;
845                                         }
846                                         else if (ch >= 0xdc00 && ch <= 0xdfff)
847                                         {
848                                                 if (hi_surrogate == -1)
849                                                         ereport(ERROR,
850                                                            (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
851                                                                 errmsg("invalid input syntax for type json"),
852                                                                 errdetail("Unicode low surrogate must follow a high surrogate."),
853                                                                 report_json_context(lex)));
854                                                 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
855                                                 hi_surrogate = -1;
856                                         }
857
858                                         if (hi_surrogate != -1)
859                                                 ereport(ERROR,
860                                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
861                                                                  errmsg("invalid input syntax for type json"),
862                                                                  errdetail("Unicode low surrogate must follow a high surrogate."),
863                                                                  report_json_context(lex)));
864
865                                         /*
866                                          * For UTF8, replace the escape sequence by the actual
867                                          * utf8 character in lex->strval. Do this also for other
868                                          * encodings if the escape designates an ASCII character,
869                                          * otherwise raise an error.
870                                          */
871
872                                         if (ch == 0)
873                                         {
874                                                 /* We can't allow this, since our TEXT type doesn't */
875                                                 ereport(ERROR,
876                                                                 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
877                                                            errmsg("unsupported Unicode escape sequence"),
878                                                    errdetail("\\u0000 cannot be converted to text."),
879                                                                  report_json_context(lex)));
880                                         }
881                                         else if (GetDatabaseEncoding() == PG_UTF8)
882                                         {
883                                                 unicode_to_utf8(ch, (unsigned char *) utf8str);
884                                                 utf8len = pg_utf_mblen((unsigned char *) utf8str);
885                                                 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
886                                         }
887                                         else if (ch <= 0x007f)
888                                         {
889                                                 /*
890                                                  * This is the only way to designate things like a
891                                                  * form feed character in JSON, so it's useful in all
892                                                  * encodings.
893                                                  */
894                                                 appendStringInfoChar(lex->strval, (char) ch);
895                                         }
896                                         else
897                                         {
898                                                 ereport(ERROR,
899                                                                 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
900                                                            errmsg("unsupported Unicode escape sequence"),
901                                                                  errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
902                                                                  report_json_context(lex)));
903                                         }
904
905                                 }
906                         }
907                         else if (lex->strval != NULL)
908                         {
909                                 if (hi_surrogate != -1)
910                                         ereport(ERROR,
911                                                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
912                                                          errmsg("invalid input syntax for type json"),
913                                                          errdetail("Unicode low surrogate must follow a high surrogate."),
914                                                          report_json_context(lex)));
915
916                                 switch (*s)
917                                 {
918                                         case '"':
919                                         case '\\':
920                                         case '/':
921                                                 appendStringInfoChar(lex->strval, *s);
922                                                 break;
923                                         case 'b':
924                                                 appendStringInfoChar(lex->strval, '\b');
925                                                 break;
926                                         case 'f':
927                                                 appendStringInfoChar(lex->strval, '\f');
928                                                 break;
929                                         case 'n':
930                                                 appendStringInfoChar(lex->strval, '\n');
931                                                 break;
932                                         case 'r':
933                                                 appendStringInfoChar(lex->strval, '\r');
934                                                 break;
935                                         case 't':
936                                                 appendStringInfoChar(lex->strval, '\t');
937                                                 break;
938                                         default:
939                                                 /* Not a valid string escape, so error out. */
940                                                 lex->token_terminator = s + pg_mblen(s);
941                                                 ereport(ERROR,
942                                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
943                                                                  errmsg("invalid input syntax for type json"),
944                                                         errdetail("Escape sequence \"\\%s\" is invalid.",
945                                                                           extract_mb_char(s)),
946                                                                  report_json_context(lex)));
947                                 }
948                         }
949                         else if (strchr("\"\\/bfnrt", *s) == NULL)
950                         {
951                                 /*
952                                  * Simpler processing if we're not bothered about de-escaping
953                                  *
954                                  * It's very tempting to remove the strchr() call here and
955                                  * replace it with a switch statement, but testing so far has
956                                  * shown it's not a performance win.
957                                  */
958                                 lex->token_terminator = s + pg_mblen(s);
959                                 ereport(ERROR,
960                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
961                                                  errmsg("invalid input syntax for type json"),
962                                                  errdetail("Escape sequence \"\\%s\" is invalid.",
963                                                                    extract_mb_char(s)),
964                                                  report_json_context(lex)));
965                         }
966
967                 }
968                 else if (lex->strval != NULL)
969                 {
970                         if (hi_surrogate != -1)
971                                 ereport(ERROR,
972                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
973                                                  errmsg("invalid input syntax for type json"),
974                                                  errdetail("Unicode low surrogate must follow a high surrogate."),
975                                                  report_json_context(lex)));
976
977                         appendStringInfoChar(lex->strval, *s);
978                 }
979
980         }
981
982         if (hi_surrogate != -1)
983                 ereport(ERROR,
984                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
985                                  errmsg("invalid input syntax for type json"),
986                         errdetail("Unicode low surrogate must follow a high surrogate."),
987                                  report_json_context(lex)));
988
989         /* Hooray, we found the end of the string! */
990         lex->prev_token_terminator = lex->token_terminator;
991         lex->token_terminator = s + 1;
992 }
993
994 /*
995  * The next token in the input stream is known to be a number; lex it.
996  *
997  * In JSON, a number consists of four parts:
998  *
999  * (1) An optional minus sign ('-').
1000  *
1001  * (2) Either a single '0', or a string of one or more digits that does not
1002  *         begin with a '0'.
1003  *
1004  * (3) An optional decimal part, consisting of a period ('.') followed by
1005  *         one or more digits.  (Note: While this part can be omitted
1006  *         completely, it's not OK to have only the decimal point without
1007  *         any digits afterwards.)
1008  *
1009  * (4) An optional exponent part, consisting of 'e' or 'E', optionally
1010  *         followed by '+' or '-', followed by one or more digits.  (Note:
1011  *         As with the decimal part, if 'e' or 'E' is present, it must be
1012  *         followed by at least one digit.)
1013  *
1014  * The 's' argument to this function points to the ostensible beginning
1015  * of part 2 - i.e. the character after any optional minus sign, or the
1016  * first character of the string if there is none.
1017  *
1018  * If num_err is not NULL, we return an error flag to *num_err rather than
1019  * raising an error for a badly-formed number.  Also, if total_len is not NULL
1020  * the distance from lex->input to the token end+1 is returned to *total_len.
1021  */
1022 static inline void
1023 json_lex_number(JsonLexContext *lex, char *s,
1024                                 bool *num_err, int *total_len)
1025 {
1026         bool            error = false;
1027         int                     len = s - lex->input;
1028
1029         /* Part (1): leading sign indicator. */
1030         /* Caller already did this for us; so do nothing. */
1031
1032         /* Part (2): parse main digit string. */
1033         if (len < lex->input_length && *s == '0')
1034         {
1035                 s++;
1036                 len++;
1037         }
1038         else if (len < lex->input_length && *s >= '1' && *s <= '9')
1039         {
1040                 do
1041                 {
1042                         s++;
1043                         len++;
1044                 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1045         }
1046         else
1047                 error = true;
1048
1049         /* Part (3): parse optional decimal portion. */
1050         if (len < lex->input_length && *s == '.')
1051         {
1052                 s++;
1053                 len++;
1054                 if (len == lex->input_length || *s < '0' || *s > '9')
1055                         error = true;
1056                 else
1057                 {
1058                         do
1059                         {
1060                                 s++;
1061                                 len++;
1062                         } while (len < lex->input_length && *s >= '0' && *s <= '9');
1063                 }
1064         }
1065
1066         /* Part (4): parse optional exponent. */
1067         if (len < lex->input_length && (*s == 'e' || *s == 'E'))
1068         {
1069                 s++;
1070                 len++;
1071                 if (len < lex->input_length && (*s == '+' || *s == '-'))
1072                 {
1073                         s++;
1074                         len++;
1075                 }
1076                 if (len == lex->input_length || *s < '0' || *s > '9')
1077                         error = true;
1078                 else
1079                 {
1080                         do
1081                         {
1082                                 s++;
1083                                 len++;
1084                         } while (len < lex->input_length && *s >= '0' && *s <= '9');
1085                 }
1086         }
1087
1088         /*
1089          * Check for trailing garbage.  As in json_lex(), any alphanumeric stuff
1090          * here should be considered part of the token for error-reporting
1091          * purposes.
1092          */
1093         for (; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*s); s++, len++)
1094                 error = true;
1095
1096         if (total_len != NULL)
1097                 *total_len = len;
1098
1099         if (num_err != NULL)
1100         {
1101                 /* let the caller handle any error */
1102                 *num_err = error;
1103         }
1104         else
1105         {
1106                 /* return token endpoint */
1107                 lex->prev_token_terminator = lex->token_terminator;
1108                 lex->token_terminator = s;
1109                 /* handle error if any */
1110                 if (error)
1111                         report_invalid_token(lex);
1112         }
1113 }
1114
1115 /*
1116  * Report a parse error.
1117  *
1118  * lex->token_start and lex->token_terminator must identify the current token.
1119  */
1120 static void
1121 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1122 {
1123         char       *token;
1124         int                     toklen;
1125
1126         /* Handle case where the input ended prematurely. */
1127         if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1128                 ereport(ERROR,
1129                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1130                                  errmsg("invalid input syntax for type json"),
1131                                  errdetail("The input string ended unexpectedly."),
1132                                  report_json_context(lex)));
1133
1134         /* Separate out the current token. */
1135         toklen = lex->token_terminator - lex->token_start;
1136         token = palloc(toklen + 1);
1137         memcpy(token, lex->token_start, toklen);
1138         token[toklen] = '\0';
1139
1140         /* Complain, with the appropriate detail message. */
1141         if (ctx == JSON_PARSE_END)
1142                 ereport(ERROR,
1143                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1144                                  errmsg("invalid input syntax for type json"),
1145                                  errdetail("Expected end of input, but found \"%s\".",
1146                                                    token),
1147                                  report_json_context(lex)));
1148         else
1149         {
1150                 switch (ctx)
1151                 {
1152                         case JSON_PARSE_VALUE:
1153                                 ereport(ERROR,
1154                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1155                                                  errmsg("invalid input syntax for type json"),
1156                                                  errdetail("Expected JSON value, but found \"%s\".",
1157                                                                    token),
1158                                                  report_json_context(lex)));
1159                                 break;
1160                         case JSON_PARSE_STRING:
1161                                 ereport(ERROR,
1162                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1163                                                  errmsg("invalid input syntax for type json"),
1164                                                  errdetail("Expected string, but found \"%s\".",
1165                                                                    token),
1166                                                  report_json_context(lex)));
1167                                 break;
1168                         case JSON_PARSE_ARRAY_START:
1169                                 ereport(ERROR,
1170                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1171                                                  errmsg("invalid input syntax for type json"),
1172                                                  errdetail("Expected array element or \"]\", but found \"%s\".",
1173                                                                    token),
1174                                                  report_json_context(lex)));
1175                                 break;
1176                         case JSON_PARSE_ARRAY_NEXT:
1177                                 ereport(ERROR,
1178                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1179                                                  errmsg("invalid input syntax for type json"),
1180                                           errdetail("Expected \",\" or \"]\", but found \"%s\".",
1181                                                                 token),
1182                                                  report_json_context(lex)));
1183                                 break;
1184                         case JSON_PARSE_OBJECT_START:
1185                                 ereport(ERROR,
1186                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1187                                                  errmsg("invalid input syntax for type json"),
1188                                          errdetail("Expected string or \"}\", but found \"%s\".",
1189                                                            token),
1190                                                  report_json_context(lex)));
1191                                 break;
1192                         case JSON_PARSE_OBJECT_LABEL:
1193                                 ereport(ERROR,
1194                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1195                                                  errmsg("invalid input syntax for type json"),
1196                                                  errdetail("Expected \":\", but found \"%s\".",
1197                                                                    token),
1198                                                  report_json_context(lex)));
1199                                 break;
1200                         case JSON_PARSE_OBJECT_NEXT:
1201                                 ereport(ERROR,
1202                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1203                                                  errmsg("invalid input syntax for type json"),
1204                                           errdetail("Expected \",\" or \"}\", but found \"%s\".",
1205                                                                 token),
1206                                                  report_json_context(lex)));
1207                                 break;
1208                         case JSON_PARSE_OBJECT_COMMA:
1209                                 ereport(ERROR,
1210                                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1211                                                  errmsg("invalid input syntax for type json"),
1212                                                  errdetail("Expected string, but found \"%s\".",
1213                                                                    token),
1214                                                  report_json_context(lex)));
1215                                 break;
1216                         default:
1217                                 elog(ERROR, "unexpected json parse state: %d", ctx);
1218                 }
1219         }
1220 }
1221
1222 /*
1223  * Report an invalid input token.
1224  *
1225  * lex->token_start and lex->token_terminator must identify the token.
1226  */
1227 static void
1228 report_invalid_token(JsonLexContext *lex)
1229 {
1230         char       *token;
1231         int                     toklen;
1232
1233         /* Separate out the offending token. */
1234         toklen = lex->token_terminator - lex->token_start;
1235         token = palloc(toklen + 1);
1236         memcpy(token, lex->token_start, toklen);
1237         token[toklen] = '\0';
1238
1239         ereport(ERROR,
1240                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1241                          errmsg("invalid input syntax for type json"),
1242                          errdetail("Token \"%s\" is invalid.", token),
1243                          report_json_context(lex)));
1244 }
1245
1246 /*
1247  * Report a CONTEXT line for bogus JSON input.
1248  *
1249  * lex->token_terminator must be set to identify the spot where we detected
1250  * the error.  Note that lex->token_start might be NULL, in case we recognized
1251  * error at EOF.
1252  *
1253  * The return value isn't meaningful, but we make it non-void so that this
1254  * can be invoked inside ereport().
1255  */
1256 static int
1257 report_json_context(JsonLexContext *lex)
1258 {
1259         const char *context_start;
1260         const char *context_end;
1261         const char *line_start;
1262         int                     line_number;
1263         char       *ctxt;
1264         int                     ctxtlen;
1265         const char *prefix;
1266         const char *suffix;
1267
1268         /* Choose boundaries for the part of the input we will display */
1269         context_start = lex->input;
1270         context_end = lex->token_terminator;
1271         line_start = context_start;
1272         line_number = 1;
1273         for (;;)
1274         {
1275                 /* Always advance over newlines */
1276                 if (context_start < context_end && *context_start == '\n')
1277                 {
1278                         context_start++;
1279                         line_start = context_start;
1280                         line_number++;
1281                         continue;
1282                 }
1283                 /* Otherwise, done as soon as we are close enough to context_end */
1284                 if (context_end - context_start < 50)
1285                         break;
1286                 /* Advance to next multibyte character */
1287                 if (IS_HIGHBIT_SET(*context_start))
1288                         context_start += pg_mblen(context_start);
1289                 else
1290                         context_start++;
1291         }
1292
1293         /*
1294          * We add "..." to indicate that the excerpt doesn't start at the
1295          * beginning of the line ... but if we're within 3 characters of the
1296          * beginning of the line, we might as well just show the whole line.
1297          */
1298         if (context_start - line_start <= 3)
1299                 context_start = line_start;
1300
1301         /* Get a null-terminated copy of the data to present */
1302         ctxtlen = context_end - context_start;
1303         ctxt = palloc(ctxtlen + 1);
1304         memcpy(ctxt, context_start, ctxtlen);
1305         ctxt[ctxtlen] = '\0';
1306
1307         /*
1308          * Show the context, prefixing "..." if not starting at start of line, and
1309          * suffixing "..." if not ending at end of line.
1310          */
1311         prefix = (context_start > line_start) ? "..." : "";
1312         suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1313
1314         return errcontext("JSON data, line %d: %s%s%s",
1315                                           line_number, prefix, ctxt, suffix);
1316 }
1317
1318 /*
1319  * Extract a single, possibly multi-byte char from the input string.
1320  */
1321 static char *
1322 extract_mb_char(char *s)
1323 {
1324         char       *res;
1325         int                     len;
1326
1327         len = pg_mblen(s);
1328         res = palloc(len + 1);
1329         memcpy(res, s, len);
1330         res[len] = '\0';
1331
1332         return res;
1333 }
1334
1335 /*
1336  * Determine how we want to print values of a given type in datum_to_json.
1337  *
1338  * Given the datatype OID, return its JsonTypeCategory, as well as the type's
1339  * output function OID.  If the returned category is JSONTYPE_CAST, we
1340  * return the OID of the type->JSON cast function instead.
1341  */
1342 static void
1343 json_categorize_type(Oid typoid,
1344                                          JsonTypeCategory *tcategory,
1345                                          Oid *outfuncoid)
1346 {
1347         bool            typisvarlena;
1348
1349         /* Look through any domain */
1350         typoid = getBaseType(typoid);
1351
1352         *outfuncoid = InvalidOid;
1353
1354         /*
1355          * We need to get the output function for everything except date and
1356          * timestamp types, array and composite types, booleans, and non-builtin
1357          * types where there's a cast to json.
1358          */
1359
1360         switch (typoid)
1361         {
1362                 case BOOLOID:
1363                         *tcategory = JSONTYPE_BOOL;
1364                         break;
1365
1366                 case INT2OID:
1367                 case INT4OID:
1368                 case INT8OID:
1369                 case FLOAT4OID:
1370                 case FLOAT8OID:
1371                 case NUMERICOID:
1372                         getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1373                         *tcategory = JSONTYPE_NUMERIC;
1374                         break;
1375
1376                 case DATEOID:
1377                         *tcategory = JSONTYPE_DATE;
1378                         break;
1379
1380                 case TIMESTAMPOID:
1381                         *tcategory = JSONTYPE_TIMESTAMP;
1382                         break;
1383
1384                 case TIMESTAMPTZOID:
1385                         *tcategory = JSONTYPE_TIMESTAMPTZ;
1386                         break;
1387
1388                 case JSONOID:
1389                 case JSONBOID:
1390                         getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1391                         *tcategory = JSONTYPE_JSON;
1392                         break;
1393
1394                 default:
1395                         /* Check for arrays and composites */
1396                         if (OidIsValid(get_element_type(typoid)))
1397                                 *tcategory = JSONTYPE_ARRAY;
1398                         else if (type_is_rowtype(typoid))
1399                                 *tcategory = JSONTYPE_COMPOSITE;
1400                         else
1401                         {
1402                                 /* It's probably the general case ... */
1403                                 *tcategory = JSONTYPE_OTHER;
1404                                 /* but let's look for a cast to json, if it's not built-in */
1405                                 if (typoid >= FirstNormalObjectId)
1406                                 {
1407                                         Oid                     castfunc;
1408                                         CoercionPathType ctype;
1409
1410                                         ctype = find_coercion_pathway(JSONOID, typoid,
1411                                                                                                   COERCION_EXPLICIT,
1412                                                                                                   &castfunc);
1413                                         if (ctype == COERCION_PATH_FUNC && OidIsValid(castfunc))
1414                                         {
1415                                                 *tcategory = JSONTYPE_CAST;
1416                                                 *outfuncoid = castfunc;
1417                                         }
1418                                         else
1419                                         {
1420                                                 /* non builtin type with no cast */
1421                                                 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1422                                         }
1423                                 }
1424                                 else
1425                                 {
1426                                         /* any other builtin type */
1427                                         getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1428                                 }
1429                         }
1430                         break;
1431         }
1432 }
1433
1434 /*
1435  * Turn a Datum into JSON text, appending the string to "result".
1436  *
1437  * tcategory and outfuncoid are from a previous call to json_categorize_type,
1438  * except that if is_null is true then they can be invalid.
1439  *
1440  * If key_scalar is true, the value is being printed as a key, so insist
1441  * it's of an acceptable type, and force it to be quoted.
1442  */
1443 static void
1444 datum_to_json(Datum val, bool is_null, StringInfo result,
1445                           JsonTypeCategory tcategory, Oid outfuncoid,
1446                           bool key_scalar)
1447 {
1448         char       *outputstr;
1449         text       *jsontext;
1450
1451         check_stack_depth();
1452
1453         /* callers are expected to ensure that null keys are not passed in */
1454         Assert(!(key_scalar && is_null));
1455
1456         if (is_null)
1457         {
1458                 appendStringInfoString(result, "null");
1459                 return;
1460         }
1461
1462         if (key_scalar &&
1463                 (tcategory == JSONTYPE_ARRAY ||
1464                  tcategory == JSONTYPE_COMPOSITE ||
1465                  tcategory == JSONTYPE_JSON ||
1466                  tcategory == JSONTYPE_CAST))
1467                 ereport(ERROR,
1468                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1469                  errmsg("key value must be scalar, not array, composite, or json")));
1470
1471         switch (tcategory)
1472         {
1473                 case JSONTYPE_ARRAY:
1474                         array_to_json_internal(val, result, false);
1475                         break;
1476                 case JSONTYPE_COMPOSITE:
1477                         composite_to_json(val, result, false);
1478                         break;
1479                 case JSONTYPE_BOOL:
1480                         outputstr = DatumGetBool(val) ? "true" : "false";
1481                         if (key_scalar)
1482                                 escape_json(result, outputstr);
1483                         else
1484                                 appendStringInfoString(result, outputstr);
1485                         break;
1486                 case JSONTYPE_NUMERIC:
1487                         outputstr = OidOutputFunctionCall(outfuncoid, val);
1488
1489                         /*
1490                          * Don't call escape_json for a non-key if it's a valid JSON
1491                          * number.
1492                          */
1493                         if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
1494                                 appendStringInfoString(result, outputstr);
1495                         else
1496                                 escape_json(result, outputstr);
1497                         pfree(outputstr);
1498                         break;
1499                 case JSONTYPE_DATE:
1500                         {
1501                                 DateADT         date;
1502                                 struct pg_tm tm;
1503                                 char            buf[MAXDATELEN + 1];
1504
1505                                 date = DatumGetDateADT(val);
1506                                 /* Same as date_out(), but forcing DateStyle */
1507                                 if (DATE_NOT_FINITE(date))
1508                                         EncodeSpecialDate(date, buf);
1509                                 else
1510                                 {
1511                                         j2date(date + POSTGRES_EPOCH_JDATE,
1512                                                    &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1513                                         EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1514                                 }
1515                                 appendStringInfo(result, "\"%s\"", buf);
1516                         }
1517                         break;
1518                 case JSONTYPE_TIMESTAMP:
1519                         {
1520                                 Timestamp       timestamp;
1521                                 struct pg_tm tm;
1522                                 fsec_t          fsec;
1523                                 char            buf[MAXDATELEN + 1];
1524
1525                                 timestamp = DatumGetTimestamp(val);
1526                                 /* Same as timestamp_out(), but forcing DateStyle */
1527                                 if (TIMESTAMP_NOT_FINITE(timestamp))
1528                                         EncodeSpecialTimestamp(timestamp, buf);
1529                                 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1530                                         EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
1531                                 else
1532                                         ereport(ERROR,
1533                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1534                                                          errmsg("timestamp out of range")));
1535                                 appendStringInfo(result, "\"%s\"", buf);
1536                         }
1537                         break;
1538                 case JSONTYPE_TIMESTAMPTZ:
1539                         {
1540                                 TimestampTz timestamp;
1541                                 struct pg_tm tm;
1542                                 int                     tz;
1543                                 fsec_t          fsec;
1544                                 const char *tzn = NULL;
1545                                 char            buf[MAXDATELEN + 1];
1546
1547                                 timestamp = DatumGetTimestampTz(val);
1548                                 /* Same as timestamptz_out(), but forcing DateStyle */
1549                                 if (TIMESTAMP_NOT_FINITE(timestamp))
1550                                         EncodeSpecialTimestamp(timestamp, buf);
1551                                 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1552                                         EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
1553                                 else
1554                                         ereport(ERROR,
1555                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1556                                                          errmsg("timestamp out of range")));
1557                                 appendStringInfo(result, "\"%s\"", buf);
1558                         }
1559                         break;
1560                 case JSONTYPE_JSON:
1561                         /* JSON and JSONB output will already be escaped */
1562                         outputstr = OidOutputFunctionCall(outfuncoid, val);
1563                         appendStringInfoString(result, outputstr);
1564                         pfree(outputstr);
1565                         break;
1566                 case JSONTYPE_CAST:
1567                         /* outfuncoid refers to a cast function, not an output function */
1568                         jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
1569                         outputstr = text_to_cstring(jsontext);
1570                         appendStringInfoString(result, outputstr);
1571                         pfree(outputstr);
1572                         pfree(jsontext);
1573                         break;
1574                 default:
1575                         outputstr = OidOutputFunctionCall(outfuncoid, val);
1576                         escape_json(result, outputstr);
1577                         pfree(outputstr);
1578                         break;
1579         }
1580 }
1581
1582 /*
1583  * Process a single dimension of an array.
1584  * If it's the innermost dimension, output the values, otherwise call
1585  * ourselves recursively to process the next dimension.
1586  */
1587 static void
1588 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1589                                   bool *nulls, int *valcount, JsonTypeCategory tcategory,
1590                                   Oid outfuncoid, bool use_line_feeds)
1591 {
1592         int                     i;
1593         const char *sep;
1594
1595         Assert(dim < ndims);
1596
1597         sep = use_line_feeds ? ",\n " : ",";
1598
1599         appendStringInfoChar(result, '[');
1600
1601         for (i = 1; i <= dims[dim]; i++)
1602         {
1603                 if (i > 1)
1604                         appendStringInfoString(result, sep);
1605
1606                 if (dim + 1 == ndims)
1607                 {
1608                         datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1609                                                   outfuncoid, false);
1610                         (*valcount)++;
1611                 }
1612                 else
1613                 {
1614                         /*
1615                          * Do we want line feeds on inner dimensions of arrays? For now
1616                          * we'll say no.
1617                          */
1618                         array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1619                                                           valcount, tcategory, outfuncoid, false);
1620                 }
1621         }
1622
1623         appendStringInfoChar(result, ']');
1624 }
1625
1626 /*
1627  * Turn an array into JSON.
1628  */
1629 static void
1630 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1631 {
1632         ArrayType  *v = DatumGetArrayTypeP(array);
1633         Oid                     element_type = ARR_ELEMTYPE(v);
1634         int                *dim;
1635         int                     ndim;
1636         int                     nitems;
1637         int                     count = 0;
1638         Datum      *elements;
1639         bool       *nulls;
1640         int16           typlen;
1641         bool            typbyval;
1642         char            typalign;
1643         JsonTypeCategory tcategory;
1644         Oid                     outfuncoid;
1645
1646         ndim = ARR_NDIM(v);
1647         dim = ARR_DIMS(v);
1648         nitems = ArrayGetNItems(ndim, dim);
1649
1650         if (nitems <= 0)
1651         {
1652                 appendStringInfoString(result, "[]");
1653                 return;
1654         }
1655
1656         get_typlenbyvalalign(element_type,
1657                                                  &typlen, &typbyval, &typalign);
1658
1659         json_categorize_type(element_type,
1660                                                  &tcategory, &outfuncoid);
1661
1662         deconstruct_array(v, element_type, typlen, typbyval,
1663                                           typalign, &elements, &nulls,
1664                                           &nitems);
1665
1666         array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1667                                           outfuncoid, use_line_feeds);
1668
1669         pfree(elements);
1670         pfree(nulls);
1671 }
1672
1673 /*
1674  * Turn a composite / record into JSON.
1675  */
1676 static void
1677 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1678 {
1679         HeapTupleHeader td;
1680         Oid                     tupType;
1681         int32           tupTypmod;
1682         TupleDesc       tupdesc;
1683         HeapTupleData tmptup,
1684                            *tuple;
1685         int                     i;
1686         bool            needsep = false;
1687         const char *sep;
1688
1689         sep = use_line_feeds ? ",\n " : ",";
1690
1691         td = DatumGetHeapTupleHeader(composite);
1692
1693         /* Extract rowtype info and find a tupdesc */
1694         tupType = HeapTupleHeaderGetTypeId(td);
1695         tupTypmod = HeapTupleHeaderGetTypMod(td);
1696         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1697
1698         /* Build a temporary HeapTuple control structure */
1699         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1700         tmptup.t_data = td;
1701         tuple = &tmptup;
1702
1703         appendStringInfoChar(result, '{');
1704
1705         for (i = 0; i < tupdesc->natts; i++)
1706         {
1707                 Datum           val;
1708                 bool            isnull;
1709                 char       *attname;
1710                 JsonTypeCategory tcategory;
1711                 Oid                     outfuncoid;
1712
1713                 if (tupdesc->attrs[i]->attisdropped)
1714                         continue;
1715
1716                 if (needsep)
1717                         appendStringInfoString(result, sep);
1718                 needsep = true;
1719
1720                 attname = NameStr(tupdesc->attrs[i]->attname);
1721                 escape_json(result, attname);
1722                 appendStringInfoChar(result, ':');
1723
1724                 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1725
1726                 if (isnull)
1727                 {
1728                         tcategory = JSONTYPE_NULL;
1729                         outfuncoid = InvalidOid;
1730                 }
1731                 else
1732                         json_categorize_type(tupdesc->attrs[i]->atttypid,
1733                                                                  &tcategory, &outfuncoid);
1734
1735                 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1736         }
1737
1738         appendStringInfoChar(result, '}');
1739         ReleaseTupleDesc(tupdesc);
1740 }
1741
1742 /*
1743  * Append JSON text for "val" to "result".
1744  *
1745  * This is just a thin wrapper around datum_to_json.  If the same type will be
1746  * printed many times, avoid using this; better to do the json_categorize_type
1747  * lookups only once.
1748  */
1749 static void
1750 add_json(Datum val, bool is_null, StringInfo result,
1751                  Oid val_type, bool key_scalar)
1752 {
1753         JsonTypeCategory tcategory;
1754         Oid                     outfuncoid;
1755
1756         if (val_type == InvalidOid)
1757                 ereport(ERROR,
1758                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1759                                  errmsg("could not determine input data type")));
1760
1761         if (is_null)
1762         {
1763                 tcategory = JSONTYPE_NULL;
1764                 outfuncoid = InvalidOid;
1765         }
1766         else
1767                 json_categorize_type(val_type,
1768                                                          &tcategory, &outfuncoid);
1769
1770         datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1771 }
1772
1773 /*
1774  * SQL function array_to_json(row)
1775  */
1776 extern Datum
1777 array_to_json(PG_FUNCTION_ARGS)
1778 {
1779         Datum           array = PG_GETARG_DATUM(0);
1780         StringInfo      result;
1781
1782         result = makeStringInfo();
1783
1784         array_to_json_internal(array, result, false);
1785
1786         PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1787 }
1788
1789 /*
1790  * SQL function array_to_json(row, prettybool)
1791  */
1792 extern Datum
1793 array_to_json_pretty(PG_FUNCTION_ARGS)
1794 {
1795         Datum           array = PG_GETARG_DATUM(0);
1796         bool            use_line_feeds = PG_GETARG_BOOL(1);
1797         StringInfo      result;
1798
1799         result = makeStringInfo();
1800
1801         array_to_json_internal(array, result, use_line_feeds);
1802
1803         PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1804 }
1805
1806 /*
1807  * SQL function row_to_json(row)
1808  */
1809 extern Datum
1810 row_to_json(PG_FUNCTION_ARGS)
1811 {
1812         Datum           array = PG_GETARG_DATUM(0);
1813         StringInfo      result;
1814
1815         result = makeStringInfo();
1816
1817         composite_to_json(array, result, false);
1818
1819         PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1820 }
1821
1822 /*
1823  * SQL function row_to_json(row, prettybool)
1824  */
1825 extern Datum
1826 row_to_json_pretty(PG_FUNCTION_ARGS)
1827 {
1828         Datum           array = PG_GETARG_DATUM(0);
1829         bool            use_line_feeds = PG_GETARG_BOOL(1);
1830         StringInfo      result;
1831
1832         result = makeStringInfo();
1833
1834         composite_to_json(array, result, use_line_feeds);
1835
1836         PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1837 }
1838
1839 /*
1840  * SQL function to_json(anyvalue)
1841  */
1842 Datum
1843 to_json(PG_FUNCTION_ARGS)
1844 {
1845         Datum           val = PG_GETARG_DATUM(0);
1846         Oid                     val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1847         StringInfo      result;
1848         JsonTypeCategory tcategory;
1849         Oid                     outfuncoid;
1850
1851         if (val_type == InvalidOid)
1852                 ereport(ERROR,
1853                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1854                                  errmsg("could not determine input data type")));
1855
1856         json_categorize_type(val_type,
1857                                                  &tcategory, &outfuncoid);
1858
1859         result = makeStringInfo();
1860
1861         datum_to_json(val, false, result, tcategory, outfuncoid, false);
1862
1863         PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1864 }
1865
1866 /*
1867  * json_agg transition function
1868  *
1869  * aggregate input column as a json array value.
1870  */
1871 Datum
1872 json_agg_transfn(PG_FUNCTION_ARGS)
1873 {
1874         MemoryContext aggcontext,
1875                                 oldcontext;
1876         JsonAggState *state;
1877         Datum           val;
1878
1879         if (!AggCheckCallContext(fcinfo, &aggcontext))
1880         {
1881                 /* cannot be called directly because of internal-type argument */
1882                 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1883         }
1884
1885         if (PG_ARGISNULL(0))
1886         {
1887                 Oid                     arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1888
1889                 if (arg_type == InvalidOid)
1890                         ereport(ERROR,
1891                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1892                                          errmsg("could not determine input data type")));
1893
1894                 /*
1895                  * Make this state object in a context where it will persist for the
1896                  * duration of the aggregate call.  MemoryContextSwitchTo is only
1897                  * needed the first time, as the StringInfo routines make sure they
1898                  * use the right context to enlarge the object if necessary.
1899                  */
1900                 oldcontext = MemoryContextSwitchTo(aggcontext);
1901                 state = (JsonAggState *) palloc(sizeof(JsonAggState));
1902                 state->str = makeStringInfo();
1903                 MemoryContextSwitchTo(oldcontext);
1904
1905                 appendStringInfoChar(state->str, '[');
1906                 json_categorize_type(arg_type, &state->val_category,
1907                                                          &state->val_output_func);
1908         }
1909         else
1910         {
1911                 state = (JsonAggState *) PG_GETARG_POINTER(0);
1912                 appendStringInfoString(state->str, ", ");
1913         }
1914
1915         /* fast path for NULLs */
1916         if (PG_ARGISNULL(1))
1917         {
1918                 datum_to_json((Datum) 0, true, state->str, JSONTYPE_NULL,
1919                                           InvalidOid, false);
1920                 PG_RETURN_POINTER(state);
1921         }
1922
1923         val = PG_GETARG_DATUM(1);
1924
1925         /* add some whitespace if structured type and not first item */
1926         if (!PG_ARGISNULL(0) &&
1927                 (state->val_category == JSONTYPE_ARRAY ||
1928                  state->val_category == JSONTYPE_COMPOSITE))
1929         {
1930                 appendStringInfoString(state->str, "\n ");
1931         }
1932
1933         datum_to_json(val, false, state->str, state->val_category,
1934                                   state->val_output_func, false);
1935
1936         /*
1937          * The transition type for array_agg() is declared to be "internal", which
1938          * is a pass-by-value type the same size as a pointer.  So we can safely
1939          * pass the JsonAggState pointer through nodeAgg.c's machinations.
1940          */
1941         PG_RETURN_POINTER(state);
1942 }
1943
1944 /*
1945  * json_agg final function
1946  */
1947 Datum
1948 json_agg_finalfn(PG_FUNCTION_ARGS)
1949 {
1950         JsonAggState *state;
1951
1952         /* cannot be called directly because of internal-type argument */
1953         Assert(AggCheckCallContext(fcinfo, NULL));
1954
1955         state = PG_ARGISNULL(0) ?
1956                 NULL :
1957                 (JsonAggState *) PG_GETARG_POINTER(0);
1958
1959         /* NULL result for no rows in, as is standard with aggregates */
1960         if (state == NULL)
1961                 PG_RETURN_NULL();
1962
1963         /* Else return state with appropriate array terminator added */
1964         PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, "]"));
1965 }
1966
1967 /*
1968  * json_object_agg transition function.
1969  *
1970  * aggregate two input columns as a single json object value.
1971  */
1972 Datum
1973 json_object_agg_transfn(PG_FUNCTION_ARGS)
1974 {
1975         MemoryContext aggcontext,
1976                                 oldcontext;
1977         JsonAggState *state;
1978         Datum           arg;
1979
1980         if (!AggCheckCallContext(fcinfo, &aggcontext))
1981         {
1982                 /* cannot be called directly because of internal-type argument */
1983                 elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
1984         }
1985
1986         if (PG_ARGISNULL(0))
1987         {
1988                 Oid                     arg_type;
1989
1990                 /*
1991                  * Make the StringInfo in a context where it will persist for the
1992                  * duration of the aggregate call. Switching context is only needed
1993                  * for this initial step, as the StringInfo routines make sure they
1994                  * use the right context to enlarge the object if necessary.
1995                  */
1996                 oldcontext = MemoryContextSwitchTo(aggcontext);
1997                 state = (JsonAggState *) palloc(sizeof(JsonAggState));
1998                 state->str = makeStringInfo();
1999                 MemoryContextSwitchTo(oldcontext);
2000
2001                 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
2002
2003                 if (arg_type == InvalidOid)
2004                         ereport(ERROR,
2005                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2006                                          errmsg("could not determine data type for argument 1")));
2007
2008                 json_categorize_type(arg_type, &state->key_category,
2009                                                          &state->key_output_func);
2010
2011                 arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
2012
2013                 if (arg_type == InvalidOid)
2014                         ereport(ERROR,
2015                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2016                                          errmsg("could not determine data type for argument 2")));
2017
2018                 json_categorize_type(arg_type, &state->val_category,
2019                                                          &state->val_output_func);
2020
2021                 appendStringInfoString(state->str, "{ ");
2022         }
2023         else
2024         {
2025                 state = (JsonAggState *) PG_GETARG_POINTER(0);
2026                 appendStringInfoString(state->str, ", ");
2027         }
2028
2029         /*
2030          * Note: since json_object_agg() is declared as taking type "any", the
2031          * parser will not do any type conversion on unknown-type literals (that
2032          * is, undecorated strings or NULLs).  Such values will arrive here as
2033          * type UNKNOWN, which fortunately does not matter to us, since
2034          * unknownout() works fine.
2035          */
2036
2037         if (PG_ARGISNULL(1))
2038                 ereport(ERROR,
2039                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2040                                  errmsg("field name must not be null")));
2041
2042         arg = PG_GETARG_DATUM(1);
2043
2044         datum_to_json(arg, false, state->str, state->key_category,
2045                                   state->key_output_func, true);
2046
2047         appendStringInfoString(state->str, " : ");
2048
2049         if (PG_ARGISNULL(2))
2050                 arg = (Datum) 0;
2051         else
2052                 arg = PG_GETARG_DATUM(2);
2053
2054         datum_to_json(arg, PG_ARGISNULL(2), state->str, state->val_category,
2055                                   state->val_output_func, false);
2056
2057         PG_RETURN_POINTER(state);
2058 }
2059
2060 /*
2061  * json_object_agg final function.
2062  */
2063 Datum
2064 json_object_agg_finalfn(PG_FUNCTION_ARGS)
2065 {
2066         JsonAggState *state;
2067
2068         /* cannot be called directly because of internal-type argument */
2069         Assert(AggCheckCallContext(fcinfo, NULL));
2070
2071         state = PG_ARGISNULL(0) ? NULL : (JsonAggState *) PG_GETARG_POINTER(0);
2072
2073         /* NULL result for no rows in, as is standard with aggregates */
2074         if (state == NULL)
2075                 PG_RETURN_NULL();
2076
2077         /* Else return state with appropriate object terminator added */
2078         PG_RETURN_TEXT_P(catenate_stringinfo_string(state->str, " }"));
2079 }
2080
2081 /*
2082  * Helper function for aggregates: return given StringInfo's contents plus
2083  * specified trailing string, as a text datum.  We need this because aggregate
2084  * final functions are not allowed to modify the aggregate state.
2085  */
2086 static text *
2087 catenate_stringinfo_string(StringInfo buffer, const char *addon)
2088 {
2089         /* custom version of cstring_to_text_with_len */
2090         int                     buflen = buffer->len;
2091         int                     addlen = strlen(addon);
2092         text       *result = (text *) palloc(buflen + addlen + VARHDRSZ);
2093
2094         SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
2095         memcpy(VARDATA(result), buffer->data, buflen);
2096         memcpy(VARDATA(result) + buflen, addon, addlen);
2097
2098         return result;
2099 }
2100
2101 /*
2102  * SQL function json_build_object(variadic "any")
2103  */
2104 Datum
2105 json_build_object(PG_FUNCTION_ARGS)
2106 {
2107         int                     nargs = PG_NARGS();
2108         int                     i;
2109         Datum           arg;
2110         const char *sep = "";
2111         StringInfo      result;
2112         Oid                     val_type;
2113
2114         if (nargs % 2 != 0)
2115                 ereport(ERROR,
2116                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2117                                  errmsg("argument list must have even number of elements"),
2118                                  errhint("The arguments of json_build_object() must consist of alternating keys and values.")));
2119
2120         result = makeStringInfo();
2121
2122         appendStringInfoChar(result, '{');
2123
2124         for (i = 0; i < nargs; i += 2)
2125         {
2126                 /*
2127                  * Note: since json_build_object() is declared as taking type "any",
2128                  * the parser will not do any type conversion on unknown-type literals
2129                  * (that is, undecorated strings or NULLs).  Such values will arrive
2130                  * here as type UNKNOWN, which fortunately does not matter to us,
2131                  * since unknownout() works fine.
2132                  */
2133                 appendStringInfoString(result, sep);
2134                 sep = ", ";
2135
2136                 /* process key */
2137                 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2138
2139                 if (val_type == InvalidOid)
2140                         ereport(ERROR,
2141                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2142                                          errmsg("could not determine data type for argument %d",
2143                                                         i + 1)));
2144
2145                 if (PG_ARGISNULL(i))
2146                         ereport(ERROR,
2147                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2148                                          errmsg("argument %d cannot be null", i + 1),
2149                                          errhint("Object keys should be text.")));
2150
2151                 arg = PG_GETARG_DATUM(i);
2152
2153                 add_json(arg, false, result, val_type, true);
2154
2155                 appendStringInfoString(result, " : ");
2156
2157                 /* process value */
2158                 val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
2159
2160                 if (val_type == InvalidOid)
2161                         ereport(ERROR,
2162                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2163                                          errmsg("could not determine data type for argument %d",
2164                                                         i + 2)));
2165
2166                 if (PG_ARGISNULL(i + 1))
2167                         arg = (Datum) 0;
2168                 else
2169                         arg = PG_GETARG_DATUM(i + 1);
2170
2171                 add_json(arg, PG_ARGISNULL(i + 1), result, val_type, false);
2172         }
2173
2174         appendStringInfoChar(result, '}');
2175
2176         PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2177 }
2178
2179 /*
2180  * degenerate case of json_build_object where it gets 0 arguments.
2181  */
2182 Datum
2183 json_build_object_noargs(PG_FUNCTION_ARGS)
2184 {
2185         PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2186 }
2187
2188 /*
2189  * SQL function json_build_array(variadic "any")
2190  */
2191 Datum
2192 json_build_array(PG_FUNCTION_ARGS)
2193 {
2194         int                     nargs = PG_NARGS();
2195         int                     i;
2196         Datum           arg;
2197         const char *sep = "";
2198         StringInfo      result;
2199         Oid                     val_type;
2200
2201         result = makeStringInfo();
2202
2203         appendStringInfoChar(result, '[');
2204
2205         for (i = 0; i < nargs; i++)
2206         {
2207                 /*
2208                  * Note: since json_build_array() is declared as taking type "any",
2209                  * the parser will not do any type conversion on unknown-type literals
2210                  * (that is, undecorated strings or NULLs).  Such values will arrive
2211                  * here as type UNKNOWN, which fortunately does not matter to us,
2212                  * since unknownout() works fine.
2213                  */
2214                 appendStringInfoString(result, sep);
2215                 sep = ", ";
2216
2217                 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2218
2219                 if (val_type == InvalidOid)
2220                         ereport(ERROR,
2221                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2222                                          errmsg("could not determine data type for argument %d",
2223                                                         i + 1)));
2224
2225                 if (PG_ARGISNULL(i))
2226                         arg = (Datum) 0;
2227                 else
2228                         arg = PG_GETARG_DATUM(i);
2229
2230                 add_json(arg, PG_ARGISNULL(i), result, val_type, false);
2231         }
2232
2233         appendStringInfoChar(result, ']');
2234
2235         PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2236 }
2237
2238 /*
2239  * degenerate case of json_build_array where it gets 0 arguments.
2240  */
2241 Datum
2242 json_build_array_noargs(PG_FUNCTION_ARGS)
2243 {
2244         PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2245 }
2246
2247 /*
2248  * SQL function json_object(text[])
2249  *
2250  * take a one or two dimensional array of text as key/value pairs
2251  * for a json object.
2252  */
2253 Datum
2254 json_object(PG_FUNCTION_ARGS)
2255 {
2256         ArrayType  *in_array = PG_GETARG_ARRAYTYPE_P(0);
2257         int                     ndims = ARR_NDIM(in_array);
2258         StringInfoData result;
2259         Datum      *in_datums;
2260         bool       *in_nulls;
2261         int                     in_count,
2262                                 count,
2263                                 i;
2264         text       *rval;
2265         char       *v;
2266
2267         switch (ndims)
2268         {
2269                 case 0:
2270                         PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2271                         break;
2272
2273                 case 1:
2274                         if ((ARR_DIMS(in_array)[0]) % 2)
2275                                 ereport(ERROR,
2276                                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2277                                                  errmsg("array must have even number of elements")));
2278                         break;
2279
2280                 case 2:
2281                         if ((ARR_DIMS(in_array)[1]) != 2)
2282                                 ereport(ERROR,
2283                                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2284                                                  errmsg("array must have two columns")));
2285                         break;
2286
2287                 default:
2288                         ereport(ERROR,
2289                                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2290                                          errmsg("wrong number of array subscripts")));
2291         }
2292
2293         deconstruct_array(in_array,
2294                                           TEXTOID, -1, false, 'i',
2295                                           &in_datums, &in_nulls, &in_count);
2296
2297         count = in_count / 2;
2298
2299         initStringInfo(&result);
2300
2301         appendStringInfoChar(&result, '{');
2302
2303         for (i = 0; i < count; ++i)
2304         {
2305                 if (in_nulls[i * 2])
2306                         ereport(ERROR,
2307                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2308                                          errmsg("null value not allowed for object key")));
2309
2310                 v = TextDatumGetCString(in_datums[i * 2]);
2311                 if (i > 0)
2312                         appendStringInfoString(&result, ", ");
2313                 escape_json(&result, v);
2314                 appendStringInfoString(&result, " : ");
2315                 pfree(v);
2316                 if (in_nulls[i * 2 + 1])
2317                         appendStringInfoString(&result, "null");
2318                 else
2319                 {
2320                         v = TextDatumGetCString(in_datums[i * 2 + 1]);
2321                         escape_json(&result, v);
2322                         pfree(v);
2323                 }
2324         }
2325
2326         appendStringInfoChar(&result, '}');
2327
2328         pfree(in_datums);
2329         pfree(in_nulls);
2330
2331         rval = cstring_to_text_with_len(result.data, result.len);
2332         pfree(result.data);
2333
2334         PG_RETURN_TEXT_P(rval);
2335
2336 }
2337
2338 /*
2339  * SQL function json_object(text[], text[])
2340  *
2341  * take separate key and value arrays of text to construct a json object
2342  * pairwise.
2343  */
2344 Datum
2345 json_object_two_arg(PG_FUNCTION_ARGS)
2346 {
2347         ArrayType  *key_array = PG_GETARG_ARRAYTYPE_P(0);
2348         ArrayType  *val_array = PG_GETARG_ARRAYTYPE_P(1);
2349         int                     nkdims = ARR_NDIM(key_array);
2350         int                     nvdims = ARR_NDIM(val_array);
2351         StringInfoData result;
2352         Datum      *key_datums,
2353                            *val_datums;
2354         bool       *key_nulls,
2355                            *val_nulls;
2356         int                     key_count,
2357                                 val_count,
2358                                 i;
2359         text       *rval;
2360         char       *v;
2361
2362         if (nkdims > 1 || nkdims != nvdims)
2363                 ereport(ERROR,
2364                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2365                                  errmsg("wrong number of array subscripts")));
2366
2367         if (nkdims == 0)
2368                 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2369
2370         deconstruct_array(key_array,
2371                                           TEXTOID, -1, false, 'i',
2372                                           &key_datums, &key_nulls, &key_count);
2373
2374         deconstruct_array(val_array,
2375                                           TEXTOID, -1, false, 'i',
2376                                           &val_datums, &val_nulls, &val_count);
2377
2378         if (key_count != val_count)
2379                 ereport(ERROR,
2380                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2381                                  errmsg("mismatched array dimensions")));
2382
2383         initStringInfo(&result);
2384
2385         appendStringInfoChar(&result, '{');
2386
2387         for (i = 0; i < key_count; ++i)
2388         {
2389                 if (key_nulls[i])
2390                         ereport(ERROR,
2391                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2392                                          errmsg("null value not allowed for object key")));
2393
2394                 v = TextDatumGetCString(key_datums[i]);
2395                 if (i > 0)
2396                         appendStringInfoString(&result, ", ");
2397                 escape_json(&result, v);
2398                 appendStringInfoString(&result, " : ");
2399                 pfree(v);
2400                 if (val_nulls[i])
2401                         appendStringInfoString(&result, "null");
2402                 else
2403                 {
2404                         v = TextDatumGetCString(val_datums[i]);
2405                         escape_json(&result, v);
2406                         pfree(v);
2407                 }
2408         }
2409
2410         appendStringInfoChar(&result, '}');
2411
2412         pfree(key_datums);
2413         pfree(key_nulls);
2414         pfree(val_datums);
2415         pfree(val_nulls);
2416
2417         rval = cstring_to_text_with_len(result.data, result.len);
2418         pfree(result.data);
2419
2420         PG_RETURN_TEXT_P(rval);
2421 }
2422
2423
2424 /*
2425  * Produce a JSON string literal, properly escaping characters in the text.
2426  */
2427 void
2428 escape_json(StringInfo buf, const char *str)
2429 {
2430         const char *p;
2431
2432         appendStringInfoCharMacro(buf, '"');
2433         for (p = str; *p; p++)
2434         {
2435                 switch (*p)
2436                 {
2437                         case '\b':
2438                                 appendStringInfoString(buf, "\\b");
2439                                 break;
2440                         case '\f':
2441                                 appendStringInfoString(buf, "\\f");
2442                                 break;
2443                         case '\n':
2444                                 appendStringInfoString(buf, "\\n");
2445                                 break;
2446                         case '\r':
2447                                 appendStringInfoString(buf, "\\r");
2448                                 break;
2449                         case '\t':
2450                                 appendStringInfoString(buf, "\\t");
2451                                 break;
2452                         case '"':
2453                                 appendStringInfoString(buf, "\\\"");
2454                                 break;
2455                         case '\\':
2456                                 appendStringInfoString(buf, "\\\\");
2457                                 break;
2458                         default:
2459                                 if ((unsigned char) *p < ' ')
2460                                         appendStringInfo(buf, "\\u%04x", (int) *p);
2461                                 else
2462                                         appendStringInfoCharMacro(buf, *p);
2463                                 break;
2464                 }
2465         }
2466         appendStringInfoCharMacro(buf, '"');
2467 }
2468
2469 /*
2470  * SQL function json_typeof(json) -> text
2471  *
2472  * Returns the type of the outermost JSON value as TEXT.  Possible types are
2473  * "object", "array", "string", "number", "boolean", and "null".
2474  *
2475  * Performs a single call to json_lex() to get the first token of the supplied
2476  * value.  This initial token uniquely determines the value's type.  As our
2477  * input must already have been validated by json_in() or json_recv(), the
2478  * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2479  * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2480  */
2481 Datum
2482 json_typeof(PG_FUNCTION_ARGS)
2483 {
2484         text       *json;
2485
2486         JsonLexContext *lex;
2487         JsonTokenType tok;
2488         char       *type;
2489
2490         json = PG_GETARG_TEXT_P(0);
2491         lex = makeJsonLexContext(json, false);
2492
2493         /* Lex exactly one token from the input and check its type. */
2494         json_lex(lex);
2495         tok = lex_peek(lex);
2496         switch (tok)
2497         {
2498                 case JSON_TOKEN_OBJECT_START:
2499                         type = "object";
2500                         break;
2501                 case JSON_TOKEN_ARRAY_START:
2502                         type = "array";
2503                         break;
2504                 case JSON_TOKEN_STRING:
2505                         type = "string";
2506                         break;
2507                 case JSON_TOKEN_NUMBER:
2508                         type = "number";
2509                         break;
2510                 case JSON_TOKEN_TRUE:
2511                 case JSON_TOKEN_FALSE:
2512                         type = "boolean";
2513                         break;
2514                 case JSON_TOKEN_NULL:
2515                         type = "null";
2516                         break;
2517                 default:
2518                         elog(ERROR, "unexpected json token: %d", tok);
2519         }
2520
2521         PG_RETURN_TEXT_P(cstring_to_text(type));
2522 }