3 #include "nodes/nodes.h"
4 #include "nodes/parsenodes.h"
5 #include "nodes/bitmapset.h"
6 #include "parser/scanner.h"
7 #include "parser/gram.h"
9 #include "utils/json.h"
10 #include "utils/jsonapi.h"
12 #include "pgsp_json.h"
13 #include "pgsp_json_int.h"
18 void normalize_expr(char *expr, bool preserve_space);
19 static const char *coverter_core(word_table *tbl,
20 const char *src, pgsp_parser_mode mode);
22 static void json_objstart(void *state);
23 static void json_objend(void *state);
24 static void json_arrstart(void *state);
25 static void json_arrend(void *state);
26 static void json_ofstart(void *state, char *fname, bool isnull);
27 static void json_aestart(void *state, bool isnull);
28 static void json_scalar(void *state, char *token, JsonTokenType tokentype);
30 static void yaml_objstart(void *state);
31 static void yaml_objend(void *state);
32 static void yaml_arrstart(void *state);
33 static void yaml_arrend(void *state);
34 static void yaml_ofstart(void *state, char *fname, bool isnull);
35 static void yaml_aestart(void *state, bool isnull);
36 static void yaml_scalar(void *state, char *token, JsonTokenType tokentype);
38 static void adjust_wbuf(pgspParserContext *ctx, int len);
39 static char *hyphenate_words(pgspParserContext *ctx, char *src);
40 static void xml_objstart(void *state);
41 static void xml_objend(void *state);
42 static void xml_arrend(void *state);
43 static void xml_ofstart(void *state, char *fname, bool isnull);
44 static void xml_ofend(void *state, char *fname, bool isnull);
45 static void xml_aestart(void *state, bool isnull);
46 static void xml_aeend(void *state, bool isnull);
47 static void xml_scalar(void *state, char *token, JsonTokenType tokentype) ;
49 static void init_json_semaction(JsonSemAction *sem,
50 pgspParserContext *ctx);
52 word_table propfields[] =
54 {P_NodeType, "t" ,"Node Type", NULL, true, conv_nodetype, SETTER(node_type)},
55 {P_RelationShip, "h" ,"Parent Relationship", NULL, true, conv_relasionship, NULL},
56 {P_RelationName, "n" ,"Relation Name", NULL, true, NULL, SETTER(obj_name)},
57 {P_FunctioName, "f" ,"Function Name", NULL, true, NULL, SETTER(obj_name)},
58 {P_IndexName, "i" ,"Index Name", NULL, true, NULL, SETTER(index_name)},
59 {P_CTEName, "c" ,"CTE Name", NULL, true, NULL, SETTER(obj_name)},
60 {P_TrgRelation, "w" ,"Relation", NULL, true, NULL, SETTER(trig_relation)},
61 {P_Schema, "s" ,"Schema", NULL, true, NULL, SETTER(schema_name)},
62 {P_Alias, "a" ,"Alias", NULL, true, NULL, SETTER(alias)},
63 {P_Output, "o" ,"Output", NULL, true, conv_expression, SETTER(output)},
64 {P_ScanDir, "d" ,"Scan Direction", NULL, true, conv_scandir, SETTER(scan_dir)},
65 {P_MergeCond, "m" ,"Merge Cond", NULL, true, conv_expression, SETTER(merge_cond)},
66 {P_Strategy, "g" ,"Strategy", NULL, true, conv_strategy, SETTER(strategy)},
67 {P_JoinType, "j" ,"Join Type", NULL, true, conv_jointype, SETTER(join_type)},
68 {P_SortMethod, "e" ,"Sort Method", NULL, true, conv_sortmethod, SETTER(sort_method)},
69 {P_SortKey, "k" ,"Sort Key", NULL, true, NULL, SETTER(sort_key)},
70 {P_Filter, "5" ,"Filter", NULL, true, conv_expression, SETTER(filter)},
71 {P_JoinFilter, "6" ,"Join Filter", NULL, true, conv_expression, SETTER(join_filter)},
72 {P_HashCond, "7" ,"Hash Cond", NULL, true, conv_expression, SETTER(hash_cond)},
73 {P_IndexCond, "8" ,"Index Cond", NULL, true, conv_expression, SETTER(index_cond)},
74 {P_TidCond, "9" ,"TID Cond", NULL, true, conv_expression, SETTER(tid_cond)},
75 {P_RecheckCond, "0" ,"Recheck Cond", NULL, true, conv_expression, SETTER(recheck_cond)},
76 {P_Operation, "!" ,"Operation", NULL, true, conv_operation, SETTER(operation)},
77 {P_SubplanName, "q" ,"Subplan Name", NULL, true, NULL, SETTER(subplan_name)},
78 {P_Command, "b" ,"Command", NULL, true, conv_setsetopcommand,SETTER(setopcommand)},
79 {P_Triggers, "r" ,"Triggers", NULL, true, NULL, NULL},
80 {P_Trigger, "u" ,"Trigger", NULL, true, NULL, SETTER(node_type)},
81 {P_TriggerName, "v" ,"Trigger Name", NULL, true, NULL, SETTER(trig_name)},
82 {P_ConstraintName, "x" ,"Constraint Name", NULL, true, NULL, NULL},
83 {P_Plans, "l" ,"Plans", NULL, true, NULL, NULL},
84 {P_Plan, "p" ,"Plan", NULL, true, NULL, NULL},
87 {P_FunctionCall, "y" ,"Function Call", NULL, false, NULL, SETTER(func_call)},
88 {P_StartupCost, "1" ,"Startup Cost", NULL, false, NULL, SETTER(startup_cost)},
89 {P_TotalCost, "2" ,"Total Cost", NULL, false, NULL, SETTER(total_cost)},
90 {P_PlanRows, "3" ,"Plan Rows", NULL, false, NULL, SETTER(plan_rows)},
91 {P_PlanWidth, "4" ,"Plan Width", NULL, false, NULL, SETTER(plan_width)},
92 {P_ActualStartupTime,"A","Actual Startup Time", NULL, false, NULL, SETTER(actual_startup_time)},
93 {P_ActualTotalTime, "B" ,"Actual Total Time", NULL, false, NULL, SETTER(actual_total_time)},
94 {P_ActualRows, "C" ,"Actual Rows", NULL, false, NULL, SETTER(actual_rows)},
95 {P_ActualLoops, "D" ,"Actual Loops", NULL, false, NULL, SETTER(actual_loops)},
96 {P_HeapFetches, "E" ,"Heap Fetches", NULL, false, NULL, SETTER(heap_fetches)},
97 {P_SharedHitBlks, "F" ,"Shared Hit Blocks", NULL, false, NULL, SETTER(shared_hit_blks)},
98 {P_SharedReadBlks, "G" ,"Shared Read Blocks", NULL, false, NULL, SETTER(shared_read_blks)},
99 {P_SharedDirtiedBlks,"H","Shared Dirtied Blocks",NULL,false, NULL, SETTER(shared_dirtied_blks)},
100 {P_SharedWrittenBlks,"I","Shared Written Blocks",NULL,false, NULL, SETTER(shared_written_blks)},
101 {P_LocalHitBlks, "J" ,"Local Hit Blocks", NULL, false, NULL, SETTER(local_hit_blks)},
102 {P_LocalReadBlks, "K" ,"Local Read Blocks", NULL, false, NULL, SETTER(local_read_blks)},
103 {P_LocalDirtiedBlks,"L" ,"Local Dirtied Blocks",NULL, false, NULL, SETTER(local_dirtied_blks)},
104 {P_LocalWrittenBlks,"M" ,"Local Written Blocks",NULL, false, NULL, SETTER(local_written_blks)},
105 {P_TempReadBlks, "N" ,"Temp Read Blocks", NULL, false, NULL, SETTER(temp_read_blks)},
106 {P_TempWrittenBlks, "O" ,"Temp Written Blocks", NULL, false, NULL, SETTER(temp_written_blks)},
107 {P_IOReadTime, "P" ,"I/O Read Time", NULL, false, NULL, SETTER(io_read_time)},
108 {P_IOWwriteTime, "Q" ,"I/O Write Time", NULL, false, NULL, SETTER(io_write_time)},
109 {P_SortSpaceUsed, "R" ,"Sort Space Used", NULL, false, NULL, SETTER(sort_space_used)},
110 {P_SortSpaceType, "S" ,"Sort Space Type", NULL, false, conv_sortspacetype,SETTER(sort_space_type)},
111 {P_PeakMemoryUsage, "T" ,"Peak Memory Usage", NULL, false, NULL, SETTER(peak_memory_usage)},
112 {P_OrgHashBatches, "U","Original Hash Batches",NULL, false, NULL, SETTER(org_hash_batches)},
113 {P_HashBatches, "V" ,"Hash Batches", NULL, false, NULL, SETTER(hash_batches)},
114 {P_HashBuckets, "W" ,"Hash Buckets", NULL, false, NULL, SETTER(hash_buckets)},
115 {P_RowsFilterRmvd, "X" ,"Rows Removed by Filter",NULL,false,NULL, SETTER(filter_removed)},
116 {P_RowsIdxRchkRmvd, "Y" ,"Rows Removed by Index Recheck",NULL,false, NULL, SETTER(idxrchk_removed)},
117 {P_TrgTime, "Z" ,"Time", NULL, false, NULL, SETTER(trig_time)},
118 {P_TrgCalls, "z" ,"Calls", NULL, false, NULL, SETTER(trig_calls)},
119 {P_Invalid, NULL, NULL, NULL, false, NULL, NULL}
122 word_table nodetypes[] =
124 {T_Result, "a" ,"Result", NULL, false, NULL, NULL},
125 {T_ModifyTable, "b" ,"ModifyTable", NULL, false, NULL, NULL},
126 {T_Append, "c" ,"Append", NULL, false, NULL, NULL},
127 {T_MergeAppend, "d" ,"Merge Append", NULL, false, NULL, NULL},
128 {T_RecursiveUnion,"e" ,"Recursive Union",NULL, false, NULL, NULL},
129 {T_BitmapAnd, "f" ,"BitmapAnd", NULL, false, NULL, NULL},
130 {T_BitmapOr, "g" ,"BitmapOr", NULL, false, NULL, NULL},
131 {T_Scan, "" , "", "", false, NULL, NULL},
132 {T_SeqScan, "h" ,"Seq Scan", NULL, false, NULL, NULL},
133 {T_IndexScan, "i" ,"Index Scan", NULL, false, NULL, NULL},
134 {T_IndexOnlyScan,"j","Index Only Scan",NULL, false, NULL, NULL},
135 {T_BitmapIndexScan,"k" ,"Bitmap Index Scan", NULL, false, NULL, NULL},
136 {T_BitmapHeapScan,"l" ,"Bitmap Heap Scan", NULL ,false, NULL, NULL},
137 {T_TidScan, "m" ,"Tid Scan", NULL, false, NULL, NULL},
138 {T_SubqueryScan,"n" ,"Subquery Scan", NULL, false, NULL, NULL},
139 {T_FunctionScan,"o" ,"Function Scan", NULL, false, NULL, NULL},
140 {T_ValuesScan, "p" ,"Values Scan", NULL, false, NULL, NULL},
141 {T_CteScan, "q" ,"CTE Scan", NULL, false, NULL, NULL},
142 {T_WorkTableScan,"r","Workable Scan", NULL, false, NULL, NULL},
143 {T_ForeignScan, "s" , "Foreign Scan", NULL, false, NULL, NULL},
144 {T_Join, "" , "", NULL, false, NULL, NULL},
145 {T_NestLoop, "t" ,"Nested Loop", NULL, false, NULL, NULL},
146 {T_MergeJoin, "u" ,"Merge Join", "Merge", false, NULL, NULL},
147 {T_HashJoin, "v" ,"Hash Join", "Hash", false, NULL, NULL},
148 {T_Material, "w" ,"Materialize", NULL, false, NULL, NULL},
149 {T_Sort, "x" ,"Sort", NULL, false, NULL, NULL},
150 {T_Group, "y" ,"Group", NULL, false, NULL, NULL},
151 {T_Agg, "z" ,"Aggregate", NULL, false, NULL, NULL},
152 {T_WindowAgg, "0" ,"WindowAgg", NULL, false, NULL, NULL},
153 {T_Unique, "1" ,"Unique", NULL, false, NULL, NULL},
154 {T_Hash, "2" ,"Hash", NULL, false, NULL, NULL},
155 {T_SetOp, "3" ,"SetOp", NULL, false, NULL, NULL},
156 {T_LockRows, "4" ,"LockRows", NULL, false, NULL, NULL},
157 {T_Limit, "5" ,"Limit", NULL, false, NULL, NULL},
158 {T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
161 word_table directions[] =
163 {T_Invalid, "b" ,"Backward", "Backward", false, NULL, NULL},
164 {T_Invalid, "n" ,"NoMovement","", false, NULL, NULL},
165 {T_Invalid, "f" ,"Forward", "", false, NULL, NULL},
166 {T_Invalid, NULL , NULL, NULL, false, NULL, NULL}
169 word_table relationships[] =
171 {T_Invalid, "o" ,"Outer", NULL, false, NULL, NULL},
172 {T_Invalid, "i" ,"Inner", NULL, false, NULL, NULL},
173 {T_Invalid, "s" ,"Subquery", NULL, false, NULL, NULL},
174 {T_Invalid, "m" ,"Member", NULL, false, NULL, NULL},
175 {T_Invalid, "I" ,"InitPlan", NULL, false, NULL, NULL},
176 {T_Invalid, "S" ,"SubPlan", NULL, false, NULL, NULL},
177 {T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
180 word_table strategies[] =
182 {S_Plain, "p" ,"Plain", NULL, false, NULL, NULL},
183 {S_Sorted, "s" ,"Sorted", NULL, false, NULL, NULL},
184 {S_Hashed, "h" ,"Hashed", NULL, false, NULL, NULL},
185 {S_Invalid, NULL, NULL, NULL, false, NULL, NULL}
188 word_table operations[] =
190 {T_Invalid, "i" ,"Insert", NULL, false, NULL, NULL},
191 {T_Invalid, "d" ,"Delete", NULL, false, NULL, NULL},
192 {T_Invalid, "u" ,"Update", NULL, false, NULL, NULL},
193 {T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
196 word_table jointypes[] =
198 {T_Invalid, "i" ,"Inner", NULL, false, NULL, NULL},
199 {T_Invalid, "l" ,"Left", NULL, false, NULL, NULL},
200 {T_Invalid, "f" ,"Full", NULL, false, NULL, NULL},
201 {T_Invalid, "r" ,"Right", NULL, false, NULL, NULL},
202 {T_Invalid, "s" ,"Semi", NULL, false, NULL, NULL},
203 {T_Invalid, "a" ,"Anti", NULL, false, NULL, NULL},
204 {T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
207 word_table setsetopcommands[] =
209 {T_Invalid, "i" ,"Intersect", NULL, false, NULL, NULL},
210 {T_Invalid, "I" ,"Intersect All", NULL, false, NULL, NULL},
211 {T_Invalid, "e" ,"Except", NULL, false, NULL, NULL},
212 {T_Invalid, "E" ,"Except All", NULL, false, NULL, NULL},
213 {T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
216 word_table sortmethods[] =
218 {T_Invalid, "h" ,"top-N heapsort", NULL, false, NULL, NULL},
219 {T_Invalid, "q" ,"quicksort", NULL, false, NULL, NULL},
220 {T_Invalid, "e" ,"external sort", NULL, false, NULL, NULL},
221 {T_Invalid, "E" ,"external merge", NULL, false, NULL, NULL},
222 {T_Invalid, "s" ,"still in progress", NULL, false, NULL, NULL},
223 {T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
226 word_table sortspacetype[] =
228 {T_Invalid, "d" ,"Disk", NULL, false, NULL, NULL},
229 {T_Invalid, "m" ,"Memory",NULL, false, NULL, NULL},
230 {T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
234 search_word_table(word_table *tbl, const char *word, int mode)
239 (mode == PGSP_JSON_SHORTEN || mode == PGSP_JSON_NORMALIZE);
243 * Use simple linear search. We can gain too small portion of the whole
244 * processing time using more 'clever' algorithms like b-tree or tries,
245 * which won't be worth the additional memory, complexity and
246 * initialization cost.
248 for (p = tbl ; p->longname ; p++)
250 if (strcmp(longname ? p->longname: p->shortname, word) == 0)
254 if (p->longname == NULL && mode == PGSP_JSON_TEXTIZE)
256 /* Fallback to long json prop name */
257 for (p = tbl ; p->longname ; p++)
258 if (strcmp(p->longname, word) == 0)
262 return (p->longname ? p : NULL);
267 coverter_core(word_table *tbl,
268 const char *src, pgsp_parser_mode mode)
273 p = search_word_table(tbl, src, mode);
280 case PGSP_JSON_SHORTEN:
281 case PGSP_JSON_NORMALIZE:
284 case PGSP_JSON_INFLATE:
285 case PGSP_JSON_YAMLIZE:
286 case PGSP_JSON_XMLIZE:
289 case PGSP_JSON_TEXTIZE:
296 elog(ERROR, "Internal error");
302 conv_nodetype(const char *src, pgsp_parser_mode mode)
304 return coverter_core(nodetypes, src, mode);
308 conv_scandir(const char *src, pgsp_parser_mode mode)
310 return coverter_core(directions, src, mode);
314 conv_relasionship(const char *src, pgsp_parser_mode mode)
316 return coverter_core(relationships, src, mode);
320 conv_strategy(const char *src, pgsp_parser_mode mode)
322 return coverter_core(strategies, src, mode);
326 * Look for these operator characters in order to decide whether to strip
327 * whitespaces which are needless from the view of sql syntax in
328 * normalize_expr(). This must be synced with op_chars in scan.l.
330 #define OPCHARS "~!@#^&|`?+-*/%<>="
331 #define IS_WSCHAR(c) ((c) == ' ' || (c) == '\n' || (c) == '\t')
332 #define IS_CONST(tok) (tok == FCONST || tok == SCONST || tok == BCONST || \
333 tok == XCONST || tok == ICONST || tok == NULL_P || \
334 tok == TRUE_P || tok == FALSE_P || \
335 tok == CURRENT_DATE || tok == CURRENT_TIME || \
336 tok == LOCALTIME || tok == LOCALTIMESTAMP)
339 * norm_yylex: core_yylex with replacing some tokens.
342 norm_yylex(char *str, core_YYSTYPE *yylval, YYLTYPE *yylloc, core_yyscan_t yyscanner)
346 tok = core_yylex(yylval, yylloc, yyscanner);
349 * '?' alone is assumed to be an IDENT. If there's a real
350 * operator '?', this should be confused but there's hardly be.
352 if (tok == Op && str[*yylloc] == '?' &&
353 strchr(OPCHARS, str[*yylloc + 1]) == NULL)
357 * Replace tokens with '=' if the operator is consists of two or
358 * more opchars only. Assuming that opchars do not compose a token
359 * with non-opchars, check the first char only is sufficient.
361 if (tok == Op && strchr(OPCHARS, str[*yylloc]) != NULL)
368 * normalize_expr - Normalize statements or expressions.
370 * Mask constants, strip unnecessary whitespaces and upcase keywords. expr is
371 * modified in-place (destructively). If readablity is more important than
372 * uniqueness, preserve_space puts one space for one existent whitespace for
376 normalize_expr(char *expr, bool preserve_space)
378 core_yyscan_t yyscanner;
379 core_yy_extra_type yyextra;
388 yyscanner = scanner_init(expr,
398 tok = norm_yylex(expr, &yylval, &yylloc, yyscanner);
405 /* Skipping preceding whitespaces */
406 for(i = lastloc ; i < start && IS_WSCHAR(expr[i]) ; i++);
408 /* Searching for trailing whitespace */
409 for(i2 = i; i2 < start && !IS_WSCHAR(expr[i2]) ; i2++);
411 if (lasttok == IDENT)
413 /* Identifiers are copied in case-sensitive manner. */
414 memcpy(wp, expr + i, i2 - i);
419 /* Upcase keywords */
421 for (sp = expr + i ; sp < expr + i2 ; sp++, wp++)
422 *wp = (*sp >= 'a' && *sp <= 'z' ?
423 *sp - ('a' - 'A') : *sp);
427 * Because of destructive writing, wp must not go advance the
429 * Altough this function's output does not need any validity as a
430 * statement or an expression, spaces are added where it should be
431 * to keep some extent of sanity. If readablity is more important
432 * than uniqueness, preserve_space adds one space for each
433 * existent whitespace to keep readabilty.
437 (tok >= IDENT && lasttok >= IDENT &&
438 !IS_CONST(tok) && !IS_CONST(lasttok))))
445 * Negative signs before numbers are tokenized separately. And
446 * explicit positive signs won't appear in deparsed expressions.
449 tok = norm_yylex(expr, &yylval, &yylloc, yyscanner);
455 tok = norm_yylex(expr, &yylval, &end, yyscanner);
458 * Negative values may be surrounded with parens by the
459 * deparser. Mask involving them.
461 if (lasttok == '(' && tok == ')')
467 while (expr[end - 1] == ' ') end--;
483 conv_expression(const char *src, pgsp_parser_mode mode)
485 const char *ret = src;
487 if (mode == PGSP_JSON_NORMALIZE)
489 char *t = pstrdup(src);
490 normalize_expr(t, true);
491 ret = (const char *)t;
497 conv_operation(const char *src, pgsp_parser_mode mode)
499 return coverter_core(operations, src, mode);
504 conv_jointype(const char *src, pgsp_parser_mode mode)
506 return coverter_core(jointypes, src, mode);
510 conv_setsetopcommand(const char *src, pgsp_parser_mode mode)
512 return coverter_core(setsetopcommands, src, mode);
516 conv_sortmethod(const char *src, pgsp_parser_mode mode)
518 return coverter_core(sortmethods, src, mode);
522 conv_sortspacetype(const char *src, pgsp_parser_mode mode)
524 return coverter_core(sortspacetype, src, mode);
527 /**** Parser callbacks ****/
531 json_objstart(void *state)
533 pgspParserContext *ctx = (pgspParserContext *)state;
535 if (ctx->mode == PGSP_JSON_INFLATE)
537 if (!ctx->fname && ctx->dest->len > 0)
539 appendStringInfoChar(ctx->dest, '\n');
540 appendStringInfoSpaces(ctx->dest, (ctx->level) * INDENT_STEP);
544 appendStringInfoChar(ctx->dest, '{');
547 ctx->first = bms_add_member(ctx->first, ctx->level);
549 if (ctx->mode == PGSP_JSON_INFLATE)
550 appendStringInfoChar(ctx->dest, '\n');
554 json_objend(void *state)
556 pgspParserContext *ctx = (pgspParserContext *)state;
557 if (ctx->mode == PGSP_JSON_INFLATE)
559 if (!bms_is_member(ctx->level, ctx->first))
560 appendStringInfoChar(ctx->dest, '\n');
561 appendStringInfoSpaces(ctx->dest, (ctx->level - 1) * INDENT_STEP);
564 appendStringInfoChar(ctx->dest, '}');
567 ctx->last_elem_is_object = true;
568 ctx->first = bms_del_member(ctx->first, ctx->level);
573 json_arrstart(void *state)
575 pgspParserContext *ctx = (pgspParserContext *)state;
577 appendStringInfoChar(ctx->dest, '[');
580 ctx->last_elem_is_object = true;
581 ctx->first = bms_add_member(ctx->first, ctx->level);
585 json_arrend(void *state)
587 pgspParserContext *ctx = (pgspParserContext *)state;
588 if (ctx->mode == PGSP_JSON_INFLATE &&
589 ctx->last_elem_is_object)
591 appendStringInfoChar(ctx->dest, '\n');
592 appendStringInfoSpaces(ctx->dest, (ctx->level - 1) * INDENT_STEP);
595 appendStringInfoChar(ctx->dest, ']');
600 json_ofstart(void *state, char *fname, bool isnull)
603 pgspParserContext *ctx = (pgspParserContext *)state;
607 p = search_word_table(propfields, fname, ctx->mode);
611 (errmsg("JSON parser encoutered unknown field name: \"%s\".", fname),
612 errdetail_log("INPUT: \"%s\"", ctx->org_string)));
615 ctx->remove = (ctx->mode == PGSP_JSON_NORMALIZE &&
616 (!p || !p->normalize_use));
621 if (!bms_is_member(ctx->level, ctx->first))
623 appendStringInfoChar(ctx->dest, ',');
624 if (ctx->mode == PGSP_JSON_INFLATE)
625 appendStringInfoChar(ctx->dest, '\n');
628 ctx->first = bms_del_member(ctx->first, ctx->level);
630 if (ctx->mode == PGSP_JSON_INFLATE)
631 appendStringInfoSpaces(ctx->dest, ctx->level * INDENT_STEP);
633 if (!p || !p->longname)
635 else if (ctx->mode == PGSP_JSON_INFLATE)
640 escape_json(ctx->dest, fn);
642 ctx->valconverter = (p ? p->converter : NULL);
644 appendStringInfoChar(ctx->dest, ':');
646 if (ctx->mode == PGSP_JSON_INFLATE)
647 appendStringInfoChar(ctx->dest, ' ');
651 json_aestart(void *state, bool isnull)
653 pgspParserContext *ctx = (pgspParserContext *)state;
657 if (!bms_is_member(ctx->level, ctx->first))
659 appendStringInfoChar(ctx->dest, ',');
660 if (ctx->mode == PGSP_JSON_INFLATE &&
661 !ctx->last_elem_is_object)
662 appendStringInfoChar(ctx->dest, ' ');
665 ctx->first = bms_del_member(ctx->first, ctx->level);
669 json_scalar(void *state, char *token, JsonTokenType tokentype)
671 pgspParserContext *ctx = (pgspParserContext *)state;
672 const char *val = token;
677 if (ctx->valconverter)
678 val = ctx->valconverter(token, ctx->mode);
680 if (tokentype == JSON_TOKEN_STRING)
681 escape_json(ctx->dest, val);
683 appendStringInfoString(ctx->dest, val);
684 ctx->last_elem_is_object = false;
690 yaml_objstart(void *state)
692 pgspParserContext *ctx = (pgspParserContext *)state;
696 if (ctx->dest->len > 0)
697 appendStringInfoChar(ctx->dest, '\n');
698 appendStringInfoSpaces(ctx->dest, (ctx->level - 1) * INDENT_STEP);
699 appendStringInfoString(ctx->dest, "- ");
700 appendStringInfoString(ctx->dest, ctx->fname);
701 appendStringInfoString(ctx->dest, ":\n");
702 appendStringInfoSpaces(ctx->dest, (ctx->level + 1) * INDENT_STEP);
707 ctx->first = bms_add_member(ctx->first, ctx->level);
711 yaml_objend(void *state)
713 pgspParserContext *ctx = (pgspParserContext *)state;
716 ctx->last_elem_is_object = true;
717 ctx->first = bms_del_member(ctx->first, ctx->level);
721 yaml_arrstart(void *state)
723 pgspParserContext *ctx = (pgspParserContext *)state;
727 appendStringInfoString(ctx->dest, ctx->fname);
728 appendStringInfoString(ctx->dest, ":");
733 ctx->first = bms_add_member(ctx->first, ctx->level);
737 yaml_arrend(void *state)
739 pgspParserContext *ctx = (pgspParserContext *)state;
743 yaml_ofstart(void *state, char *fname, bool isnull)
746 pgspParserContext *ctx = (pgspParserContext *)state;
749 p = search_word_table(propfields, fname, ctx->mode);
753 (errmsg("Short JSON parser encoutered unknown field name: \"%s\".", fname),
754 errdetail_log("INPUT: \"%s\"", ctx->org_string)));
756 s = (p ? p->longname : fname);
758 if (!bms_is_member(ctx->level, ctx->first))
760 appendStringInfoString(ctx->dest, "\n");
761 appendStringInfoSpaces(ctx->dest, ctx->level * INDENT_STEP);
764 ctx->first = bms_del_member(ctx->first, ctx->level);
766 ctx->valconverter = NULL;
768 ctx->valconverter = (p ? p->converter : NULL);
772 yaml_aestart(void *state, bool isnull)
774 pgspParserContext *ctx = (pgspParserContext *)state;
776 appendStringInfoString(ctx->dest, "\n");
777 bms_del_member(ctx->first, ctx->level);
778 appendStringInfoSpaces(ctx->dest, ctx->level * INDENT_STEP);
779 appendStringInfoString(ctx->dest, "- ");
783 yaml_scalar(void *state, char *token, JsonTokenType tokentype)
785 pgspParserContext *ctx = (pgspParserContext *)state;
789 appendStringInfoString(ctx->dest, ctx->fname);
790 appendStringInfoString(ctx->dest, ": ");
794 json_scalar(state, token, tokentype);
796 ctx->last_elem_is_object = false;
802 xml_objstart(void *state)
804 pgspParserContext *ctx = (pgspParserContext *)state;
807 ctx->first = bms_add_member(ctx->first, ctx->level);
812 xml_objend(void *state)
814 pgspParserContext *ctx = (pgspParserContext *)state;
815 appendStringInfoChar(ctx->dest, '\n');
816 appendStringInfoSpaces(ctx->dest, ctx->level * INDENT_STEP);
819 ctx->first = bms_del_member(ctx->first, ctx->level);
821 ctx->last_elem_is_object = true;
825 xml_arrend(void *state)
827 pgspParserContext *ctx = (pgspParserContext *)state;
829 appendStringInfoChar(ctx->dest, '\n');
830 appendStringInfoSpaces(ctx->dest, (ctx->level + 1) * INDENT_STEP);
834 adjust_wbuf(pgspParserContext *ctx, int len)
838 for (buflen = ctx->wbuflen ; len > buflen ; buflen *= 2);
839 if (buflen > ctx->wbuflen)
841 ctx->wbuf = (char *)palloc(buflen);
842 ctx->wbuflen = buflen;
847 hyphenate_words(pgspParserContext *ctx, char *src)
851 adjust_wbuf(ctx, strlen(src) + 1);
852 strcpy(ctx->wbuf, src);
854 for (p = ctx->wbuf ; *p ; p++)
855 if (*p == ' ') *p = '-';
861 xml_ofstart(void *state, char *fname, bool isnull)
864 pgspParserContext *ctx = (pgspParserContext *)state;
867 p = search_word_table(propfields, fname, ctx->mode);
871 (errmsg("Short JSON parser encoutered unknown field name: \"%s\".", fname),
872 errdetail_log("INPUT: \"%s\"", ctx->org_string)));
874 s = (p ? p->longname : fname);
877 * save current process context
878 * There's no problem if P_Plan appears recursively.
880 if (p && (p->tag == P_Plan || p->tag == P_Triggers))
881 ctx->processing = p->tag;
883 appendStringInfoChar(ctx->dest, '\n');
884 appendStringInfoSpaces(ctx->dest, (ctx->level + 1) * INDENT_STEP);
886 ctx->valconverter = NULL;
888 appendStringInfoChar(ctx->dest, '<');
889 appendStringInfoString(ctx->dest, escape_xml(hyphenate_words(ctx, s)));
890 appendStringInfoChar(ctx->dest, '>');
891 ctx->valconverter = (p ? p->converter : NULL);
894 * If the object field name is Plan or Triggers, the value should be an
895 * array and the items are tagged by other than "Item". "Item"s appear
896 * only in Output field.
898 if (p && (p->tag == P_Plans || p->tag == P_Triggers))
899 ctx->not_item = bms_add_member(ctx->not_item, ctx->level + 1);
901 ctx->not_item = bms_del_member(ctx->not_item, ctx->level + 1);
905 xml_ofend(void *state, char *fname, bool isnull)
907 pgspParserContext *ctx = (pgspParserContext *)state;
911 p = search_word_table(propfields, fname, ctx->mode);
912 s = (p ? p->longname : fname);
914 appendStringInfoString(ctx->dest, "</");
915 appendStringInfoString(ctx->dest, escape_xml(hyphenate_words(ctx, s)));
916 appendStringInfoChar(ctx->dest, '>');
920 xml_aestart(void *state, bool isnull)
922 pgspParserContext *ctx = (pgspParserContext *)state;
926 * The "Trigger" in "Triggers", "Plan" in "Plans" and "Item" nodes are
927 * implicitly represented in JSON format. Restore them for XML format.
931 if (bms_is_member(ctx->level, ctx->not_item))
933 if (ctx->processing == P_Plan)
941 appendStringInfoChar(ctx->dest, '\n');
942 appendStringInfoSpaces(ctx->dest, (ctx->level + 1) * INDENT_STEP);
943 appendStringInfoString(ctx->dest, tag);
947 xml_aeend(void *state, bool isnull)
949 pgspParserContext *ctx = (pgspParserContext *)state;
953 * The "Plan" in "Plans" or "Item" nodes are implicitly represented in
954 * JSON format. Restore it for XML format.
957 if (bms_is_member(ctx->level, ctx->not_item))
959 if (ctx->processing == P_Plan)
966 appendStringInfoString(ctx->dest, tag);
971 xml_scalar(void *state, char *token, JsonTokenType tokentype)
973 pgspParserContext *ctx = (pgspParserContext *)state;
974 const char *s = token;
976 if (ctx->valconverter)
977 s = ctx->valconverter(token, PGSP_JSON_XMLIZE);
979 if (tokentype == JSON_TOKEN_STRING)
982 appendStringInfoString(ctx->dest, s);
983 ctx->last_elem_is_object = false;
986 /********************************/
988 init_parser_context(pgspParserContext *ctx, int mode,
989 char *orgstr, char *buf, int buflen){
990 memset(ctx, 0, sizeof(*ctx));
991 ctx->dest = makeStringInfo();
993 ctx->org_string = orgstr;
995 ctx->wbuflen = buflen;
1001 * Wrap pg_parse_json in order to restore InterruptHoldoffCount when parse
1004 * Returns true when parse completed. False for unexpected end of string.
1007 run_pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
1009 MemoryContext ccxt = CurrentMemoryContext;
1010 uint32 saved_IntrHoldoffCount;
1013 * "ereport(ERROR.." occurs on error in pg_parse_json resets
1014 * InterruptHoldoffCount to zero, so we must save the value before calling
1015 * json parser to restore it on parse error. See errfinish().
1017 saved_IntrHoldoffCount = InterruptHoldoffCount;
1021 pg_parse_json(lex, sem);
1028 InterruptHoldoffCount = saved_IntrHoldoffCount;
1030 ecxt = MemoryContextSwitchTo(ccxt);
1031 errdata = CopyErrorData();
1033 if (errdata->sqlerrcode == ERRCODE_INVALID_TEXT_REPRESENTATION)
1040 MemoryContextSwitchTo(ecxt);
1050 init_json_lex_context(JsonLexContext *lex, char *json)
1052 lex->input = lex->token_terminator = lex->line_start = json;
1053 lex->line_number = 1;
1054 lex->input_length = strlen(json);
1055 lex->strval = makeStringInfo();
1059 init_json_semaction(JsonSemAction *sem, pgspParserContext *ctx)
1061 sem->semstate = (void*)ctx;
1062 sem->object_start = json_objstart;
1063 sem->object_end = json_objend;
1064 sem->array_start = json_arrstart;
1065 sem->array_end = json_arrend;
1066 sem->object_field_start = json_ofstart;
1067 sem->object_field_end = NULL;
1068 sem->array_element_start= json_aestart;
1069 sem->array_element_end = NULL;
1070 sem->scalar = json_scalar;
1074 pgsp_json_shorten(char *json)
1078 pgspParserContext ctx;
1080 init_json_lex_context(&lex, json);
1081 init_parser_context(&ctx, PGSP_JSON_SHORTEN, json, NULL, 0);
1082 init_json_semaction(&sem, &ctx);
1084 run_pg_parse_json(&lex, &sem);
1086 return ctx.dest->data;
1090 pgsp_json_normalize(char *json)
1094 pgspParserContext ctx;
1096 init_json_lex_context(&lex, json);
1097 init_parser_context(&ctx,PGSP_JSON_NORMALIZE, json, NULL, 0);
1098 init_json_semaction(&sem, &ctx);
1100 run_pg_parse_json(&lex, &sem);
1102 return ctx.dest->data;
1106 pgsp_json_inflate(char *json)
1110 pgspParserContext ctx;
1112 init_json_lex_context(&lex, json);
1113 init_parser_context(&ctx, PGSP_JSON_INFLATE, json, NULL, 0);
1114 init_json_semaction(&sem, &ctx);
1116 if (!run_pg_parse_json(&lex, &sem))
1118 if (ctx.dest->len > 0 &&
1119 ctx.dest->data[ctx.dest->len - 1] != '\n')
1120 appendStringInfoChar(ctx.dest, '\n');
1122 if (ctx.dest->len == 0)
1123 appendStringInfoString(ctx.dest, "<Input was not JSON>");
1125 appendStringInfoString(ctx.dest, "<truncated>");
1128 return ctx.dest->data;
1132 pgsp_json_yamlize(char *json)
1134 pgspParserContext ctx;
1138 init_json_lex_context(&lex, json);
1139 init_parser_context(&ctx, PGSP_JSON_YAMLIZE, json, NULL, 0);
1141 sem.semstate = (void*)&ctx;
1142 sem.object_start = yaml_objstart;
1143 sem.object_end = yaml_objend;
1144 sem.array_start = yaml_arrstart;
1145 sem.array_end = yaml_arrend;
1146 sem.object_field_start = yaml_ofstart;
1147 sem.object_field_end = NULL;
1148 sem.array_element_start= yaml_aestart;
1149 sem.array_element_end = NULL;
1150 sem.scalar = yaml_scalar;
1152 if (!run_pg_parse_json(&lex, &sem))
1154 if (ctx.dest->len > 0 &&
1155 ctx.dest->data[ctx.dest->len - 1] != '\n')
1156 appendStringInfoChar(ctx.dest, '\n');
1158 if (ctx.dest->len == 0)
1159 appendStringInfoString(ctx.dest, "<Input was not JSON>");
1161 appendStringInfoString(ctx.dest, "<truncated>");
1164 return ctx.dest->data;
1168 pgsp_json_xmlize(char *json)
1170 pgspParserContext ctx;
1176 init_json_lex_context(&lex, json);
1177 init_parser_context(&ctx, PGSP_JSON_XMLIZE, json, buf, sizeof(buf));
1179 sem.semstate = (void*)&ctx;
1180 sem.object_start = xml_objstart;
1181 sem.object_end = xml_objend;
1182 sem.array_start = NULL;
1183 sem.array_end = xml_arrend;
1184 sem.object_field_start = xml_ofstart;
1185 sem.object_field_end = xml_ofend;
1186 sem.array_element_start= xml_aestart;
1187 sem.array_element_end = xml_aeend;
1188 sem.scalar = xml_scalar;
1190 appendStringInfo(ctx.dest,
1191 "<explain xmlns=\"http://www.postgresql.org/2009/explain\">\n <Query>");
1192 start_len = ctx.dest->len;
1194 if (!run_pg_parse_json(&lex, &sem))
1196 if (ctx.dest->len > start_len &&
1197 ctx.dest->data[ctx.dest->len - 1] != '\n')
1198 appendStringInfoChar(ctx.dest, '\n');
1200 if (ctx.dest->len == start_len)
1202 resetStringInfo(ctx.dest);
1203 appendStringInfoString(ctx.dest, "<Input was not JSON>");
1206 appendStringInfoString(ctx.dest, "<truncated>");
1209 appendStringInfo(ctx.dest, "</Query>\n</explain>\n");
1211 return ctx.dest->data;