-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathpgsp_json.c
1498 lines (1267 loc) · 42.9 KB
/
pgsp_json.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* pgsp_json.c: Plan handler for JSON/XML/YAML style plans
*
* Copyright (c) 2012-2024, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
*
* IDENTIFICATION
* pg_store_plans/pgsp_json.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#if PG_VERSION_NUM >= 130000
#include "mb/pg_wchar.h"
#endif
#include "miscadmin.h"
#include "nodes/nodes.h"
#include "nodes/parsenodes.h"
#include "nodes/bitmapset.h"
#include "parser/scanner.h"
#include "utils/xml.h"
#include "utils/json.h"
#if PG_VERSION_NUM < 130000
#include "utils/jsonapi.h"
#else
#include "common/jsonapi.h"
#endif
#include "pgsp_json.h"
#include "pgsp_json_int.h"
#if PG_VERSION_NUM < 160000
#include "parser/gram.h"
#define JsonParseErrorType void
#define JSONACTION_RETURN_SUCCESS() return
#else
/* In PG16, include/scan.h was gone. Define required symbols manually.. */
/* must be in sync with src/backend/parser/gram.h */
#include "pgsp_token_types.h"
#define JSONACTION_RETURN_SUCCESS() return JSON_SUCCESS
#endif
#define INDENT_STEP 2
void normalize_expr(char *expr, bool preserve_space);
static const char *converter_core(word_table *tbl,
const char *src, pgsp_parser_mode mode);
static JsonParseErrorType json_objstart(void *state);
static JsonParseErrorType json_objend(void *state);
static JsonParseErrorType json_arrstart(void *state);
static JsonParseErrorType json_arrend(void *state);
static JsonParseErrorType json_ofstart(void *state, char *fname, bool isnull);
static JsonParseErrorType json_aestart(void *state, bool isnull);
static JsonParseErrorType json_scalar(void *state, char *token,
JsonTokenType tokentype);
static JsonParseErrorType yaml_objstart(void *state);
static JsonParseErrorType yaml_objend(void *state);
static JsonParseErrorType yaml_arrstart(void *state);
static JsonParseErrorType yaml_arrend(void *state);
static JsonParseErrorType yaml_ofstart(void *state, char *fname, bool isnull);
static JsonParseErrorType yaml_aestart(void *state, bool isnull);
static JsonParseErrorType yaml_scalar(void *state, char *token,
JsonTokenType tokentype);
static void adjust_wbuf(pgspParserContext *ctx, int len);
static char *hyphenate_words(pgspParserContext *ctx, char *src);
static JsonParseErrorType xml_objstart(void *state);
static JsonParseErrorType xml_objend(void *state);
static JsonParseErrorType xml_arrend(void *state);
static JsonParseErrorType xml_ofstart(void *state, char *fname, bool isnull);
static JsonParseErrorType xml_ofend(void *state, char *fname, bool isnull);
static JsonParseErrorType xml_aestart(void *state, bool isnull);
static JsonParseErrorType xml_aeend(void *state, bool isnull);
static JsonParseErrorType xml_scalar(void *state, char *token,
JsonTokenType tokentype) ;
static void init_json_semaction(JsonSemAction *sem,
pgspParserContext *ctx);
word_table propfields[] =
{
{P_NodeType, "t" ,"Node Type", NULL, true, conv_nodetype, SETTER(node_type)},
{P_RelationShip, "h" ,"Parent Relationship", NULL, true, conv_relasionship, NULL},
{P_RelationName, "n" ,"Relation Name", NULL, true, NULL, SETTER(obj_name)},
{P_FunctioName, "f" ,"Function Name", NULL, true, NULL, SETTER(obj_name)},
{P_IndexName, "i" ,"Index Name", NULL, true, NULL, SETTER(index_name)},
{P_CTEName, "c" ,"CTE Name", NULL, true, NULL, SETTER(obj_name)},
{P_TrgRelation, "w" ,"Relation", NULL, true, NULL, SETTER(trig_relation)},
{P_Schema, "s" ,"Schema", NULL, true, NULL, SETTER(schema_name)},
{P_Alias, "a" ,"Alias", NULL, true, NULL, SETTER(alias)},
{P_Output, "o" ,"Output", NULL, true, conv_expression, SETTER(output)},
{P_ScanDir, "d" ,"Scan Direction", NULL, true, conv_scandir, SETTER(scan_dir)},
{P_MergeCond, "m" ,"Merge Cond", NULL, true, conv_expression, SETTER(merge_cond)},
{P_Strategy, "g" ,"Strategy", NULL, true, conv_strategy, SETTER(strategy)},
{P_JoinType, "j" ,"Join Type", NULL, true, conv_jointype, SETTER(join_type)},
{P_SortMethod, "e" ,"Sort Method", NULL, true, conv_sortmethod, SETTER(sort_method)},
{P_SortKey, "k" ,"Sort Key", NULL, true, conv_expression, SETTER(sort_key)},
{P_Filter, "5" ,"Filter", NULL, true, conv_expression, SETTER(filter)},
{P_JoinFilter, "6" ,"Join Filter", NULL, true, conv_expression, SETTER(join_filter)},
{P_HashCond, "7" ,"Hash Cond", NULL, true, conv_expression, SETTER(hash_cond)},
{P_IndexCond, "8" ,"Index Cond", NULL, true, conv_expression, SETTER(index_cond)},
{P_TidCond, "9" ,"TID Cond", NULL, true, conv_expression, SETTER(tid_cond)},
{P_RecheckCond, "0" ,"Recheck Cond", NULL, true, conv_expression, SETTER(recheck_cond)},
{P_Operation, "!" ,"Operation", NULL, true, conv_operation, SETTER(operation)},
{P_SubplanName, "q" ,"Subplan Name", NULL, true, NULL, SETTER(subplan_name)},
{P_Command, "b" ,"Command", NULL, true, conv_setsetopcommand,SETTER(setopcommand)},
{P_Triggers, "r" ,"Triggers", NULL, true, NULL, NULL},
{P_Trigger, "u" ,"Trigger", NULL, true, NULL, SETTER(node_type)},
{P_TriggerName, "v" ,"Trigger Name", NULL, true, NULL, SETTER(trig_name)},
{P_ConstraintName, "x" ,"Constraint Name", NULL, true, NULL, NULL},
{P_Plans, "l" ,"Plans", NULL, true, NULL, NULL},
{P_Plan, "p" ,"Plan", NULL, true, NULL, NULL},
{P_GroupKey, "-" ,"Group Key", NULL, true, NULL, SETTER(group_key)},
{P_GroupSets, "=" ,"Grouping Sets", NULL, true, NULL, NULL},
{P_GroupKeys, "\\" ,"Group Keys", NULL, true, NULL, SETTER(group_key)},
{P_HashKeys, "~" ,"Hash Keys", NULL, true, NULL, SETTER(hash_key)},
{P_HashKey, "|" ,"Hash Key", NULL, true, NULL, SETTER(hash_key)},
{P_Parallel, "`" ,"Parallel Aware", NULL, true, NULL, SETTER(parallel_aware)},
{P_PartialMode, ">" ,"Partial Mode", NULL, true, conv_partialmode,SETTER(partial_mode)},
{P_WorkersPlanned, "{" ,"Workers Planned", NULL, true, NULL, SETTER(workers_planned)},
{P_WorkersLaunched, "}" ,"Workers Launched", NULL, true, NULL, SETTER(workers_launched)},
{P_InnerUnique, "?" ,"Inner Unique", NULL, true, NULL, SETTER(inner_unique)},
{P_AsyncCapable, "ac", "Async Capable", NULL, true, NULL, SETTER(async_capable)},
/* Values of these properties are ignored on normalization */
{P_FunctionCall, "y" ,"Function Call", NULL, false, NULL, SETTER(func_call)},
{P_StartupCost, "1" ,"Startup Cost", NULL, false, NULL, SETTER(startup_cost)},
{P_TotalCost, "2" ,"Total Cost", NULL, false, NULL, SETTER(total_cost)},
{P_PlanRows, "3" ,"Plan Rows", NULL, false, NULL, SETTER(plan_rows)},
{P_PlanWidth, "4" ,"Plan Width", NULL, false, NULL, SETTER(plan_width)},
{P_ActualStartupTime,"A","Actual Startup Time", NULL, false, NULL, SETTER(actual_startup_time)},
{P_ActualTotalTime, "B" ,"Actual Total Time", NULL, false, NULL, SETTER(actual_total_time)},
{P_ActualRows, "C" ,"Actual Rows", NULL, false, NULL, SETTER(actual_rows)},
{P_ActualLoops, "D" ,"Actual Loops", NULL, false, NULL, SETTER(actual_loops)},
{P_HeapFetches, "E" ,"Heap Fetches", NULL, false, NULL, SETTER(heap_fetches)},
{P_SharedHitBlks, "F" ,"Shared Hit Blocks", NULL, false, NULL, SETTER(shared_hit_blks)},
{P_SharedReadBlks, "G" ,"Shared Read Blocks", NULL, false, NULL, SETTER(shared_read_blks)},
{P_SharedDirtiedBlks,"H","Shared Dirtied Blocks",NULL,false, NULL, SETTER(shared_dirtied_blks)},
{P_SharedWrittenBlks,"I","Shared Written Blocks",NULL,false, NULL, SETTER(shared_written_blks)},
{P_LocalHitBlks, "J" ,"Local Hit Blocks", NULL, false, NULL, SETTER(local_hit_blks)},
{P_LocalReadBlks, "K" ,"Local Read Blocks", NULL, false, NULL, SETTER(local_read_blks)},
{P_LocalDirtiedBlks,"L" ,"Local Dirtied Blocks",NULL, false, NULL, SETTER(local_dirtied_blks)},
{P_LocalWrittenBlks,"M" ,"Local Written Blocks",NULL, false, NULL, SETTER(local_written_blks)},
{P_TempReadBlks, "N" ,"Temp Read Blocks", NULL, false, NULL, SETTER(temp_read_blks)},
{P_TempWrittenBlks, "O" ,"Temp Written Blocks", NULL, false, NULL, SETTER(temp_written_blks)},
{P_IOReadTime, "P" ,"I/O Read Time", NULL, false, NULL, SETTER(io_read_time)},
{P_IOWwriteTime, "Q" ,"I/O Write Time", NULL, false, NULL, SETTER(io_write_time)},
{P_SortSpaceUsed, "R" ,"Sort Space Used", NULL, false, NULL, SETTER(sort_space_used)},
{P_SortSpaceType, "S" ,"Sort Space Type", NULL, false, conv_sortspacetype,SETTER(sort_space_type)},
{P_PeakMemoryUsage, "T" ,"Peak Memory Usage", NULL, false, NULL, SETTER(peak_memory_usage)},
{P_OrgHashBatches, "U","Original Hash Batches",NULL, false, NULL, SETTER(org_hash_batches)},
{P_OrgHashBuckets, "*","Original Hash Buckets",NULL, false, NULL, SETTER(org_hash_buckets)},
{P_HashBatches, "V" ,"Hash Batches", NULL, false, NULL, SETTER(hash_batches)},
{P_HashBuckets, "W" ,"Hash Buckets", NULL, false, NULL, SETTER(hash_buckets)},
{P_RowsFilterRmvd, "X" ,"Rows Removed by Filter",NULL,false,NULL, SETTER(filter_removed)},
{P_RowsIdxRchkRmvd, "Y" ,"Rows Removed by Index Recheck",NULL,false, NULL, SETTER(idxrchk_removed)},
{P_TrgTime, "Z" ,"Time", NULL, false, NULL, SETTER(trig_time)},
{P_TrgCalls, "z" ,"Calls", NULL, false, NULL, SETTER(trig_calls)},
{P_PlanTime, "#" ,"Planning Time", NULL, false, NULL, SETTER(plan_time)},
{P_ExecTime, "$" ,"Execution Time", NULL, false, NULL, SETTER(exec_time)},
{P_ExactHeapBlks, "&" ,"Exact Heap Blocks", NULL, false, NULL, SETTER(exact_heap_blks)},
{P_LossyHeapBlks, "(" ,"Lossy Heap Blocks", NULL, false, NULL, SETTER(lossy_heap_blks)},
{P_RowsJoinFltRemvd,")" ,"Rows Removed by Join Filter", NULL, false, NULL, SETTER(joinfilt_removed)},
{P_TargetTables, "_" ,"Target Tables", NULL, false, NULL, NULL},
{P_ConfRes, "%" ,"Conflict Resolution", NULL, false, NULL, SETTER(conflict_resolution)},
{P_ConfArbitIdx, "@" ,"Conflict Arbiter Indexes",NULL, false, NULL, SETTER(conflict_arbiter_indexes)},
{P_TuplesInserted, "^" ,"Tuples Inserted", NULL, false, NULL, SETTER(tuples_inserted)},
{P_ConfTuples, "+" ,"Conflicting Tuples", NULL, false, NULL, SETTER(conflicting_tuples)},
{P_SamplingMethod, ":" ,"Sampling Method" , NULL, false, NULL, SETTER(sampling_method)},
{P_SamplingParams, ";" ,"Sampling Parameters" , NULL, false, NULL, SETTER(sampling_params)},
{P_RepeatableSeed, "<" ,"Repeatable Seed" , NULL, false, NULL, SETTER(repeatable_seed)},
{P_Workers, "[" ,"Workers", NULL, false, NULL, NULL},
{P_WorkerNumber, "]" ,"Worker Number", NULL, false, NULL, SETTER(worker_number)},
{P_TableFuncName, "aa" ,"Table Function Name",NULL, false, NULL, SETTER(table_func_name)},
{P_PresortedKey, "pk" ,"Presorted Key" ,NULL, false, NULL, SETTER(presorted_key)},
{P_FullsortGroups, "fg" ,"Full-sort Groups" ,NULL, false, NULL, NULL},
{P_SortMethodsUsed, "su" ,"Sort Methods Used" ,NULL, false, NULL, SETTER(sortmethod_used)},
{P_SortSpaceMemory, "sm" ,"Sort Space Memory" ,NULL, false, NULL, SETTER(sortspace_mem)},
{P_GroupCount, "gc" ,"Group Count" ,NULL, false, NULL, SETTER(group_count)},
{P_AvgSortSpcUsed, "as" ,"Average Sort Space Used",NULL, false, NULL, SETTER(avg_sortspc_used)},
{P_PeakSortSpcUsed, "ps" ,"Peak Sort Space Used",NULL, false, NULL, SETTER(peak_sortspc_used)},
{P_PreSortedGroups, "pg" ,"Pre-sorted Groups" ,NULL, false, NULL, NULL},
{P_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table nodetypes[] =
{
{T_Result, "a" ,"Result", NULL, false, NULL, NULL},
{T_ModifyTable, "b" ,"ModifyTable", NULL, false, NULL, NULL},
{T_Append, "c" ,"Append", NULL, false, NULL, NULL},
{T_MergeAppend, "d" ,"Merge Append", NULL, false, NULL, NULL},
{T_RecursiveUnion,"e" ,"Recursive Union",NULL, false, NULL, NULL},
{T_BitmapAnd, "f" ,"BitmapAnd", NULL, false, NULL, NULL},
{T_BitmapOr, "g" ,"BitmapOr", NULL, false, NULL, NULL},
#if PG_VERSION_NUM < 16
{T_Scan, "" , "", "", false, NULL, NULL},
#endif
{T_SeqScan, "h" ,"Seq Scan", NULL, false, NULL, NULL},
{T_IndexScan, "i" ,"Index Scan", NULL, false, NULL, NULL},
{T_IndexOnlyScan,"j","Index Only Scan",NULL, false, NULL, NULL},
{T_BitmapIndexScan,"k" ,"Bitmap Index Scan", NULL, false, NULL, NULL},
{T_BitmapHeapScan,"l" ,"Bitmap Heap Scan", NULL ,false, NULL, NULL},
{T_TidScan, "m" ,"Tid Scan", NULL, false, NULL, NULL},
{T_SubqueryScan,"n" ,"Subquery Scan", NULL, false, NULL, NULL},
{T_FunctionScan,"o" ,"Function Scan", NULL, false, NULL, NULL},
{T_ValuesScan, "p" ,"Values Scan", NULL, false, NULL, NULL},
{T_CteScan, "q" ,"CTE Scan", NULL, false, NULL, NULL},
{T_WorkTableScan,"r","WorkTable Scan", NULL, false, NULL, NULL},
{T_ForeignScan, "s" , "Foreign Scan", NULL, false, NULL, NULL},
#if PG_VERSION_NUM < 16
{T_Join, "" , "", NULL, false, NULL, NULL},
#endif
{T_NestLoop, "t" ,"Nested Loop", NULL, false, NULL, NULL},
{T_MergeJoin, "u" ,"Merge Join", "Merge", false, NULL, NULL},
{T_HashJoin, "v" ,"Hash Join", "Hash", false, NULL, NULL},
{T_Material, "w" ,"Materialize", NULL, false, NULL, NULL},
{T_Sort, "x" ,"Sort", NULL, false, NULL, NULL},
{T_Group, "y" ,"Group", NULL, false, NULL, NULL},
{T_Agg, "z" ,"Aggregate", NULL, false, NULL, NULL},
{T_WindowAgg, "0" ,"WindowAgg", NULL, false, NULL, NULL},
{T_Unique, "1" ,"Unique", NULL, false, NULL, NULL},
{T_Hash, "2" ,"Hash", NULL, false, NULL, NULL},
{T_SetOp, "3" ,"SetOp", NULL, false, NULL, NULL},
{T_LockRows, "4" ,"LockRows", NULL, false, NULL, NULL},
{T_Limit, "5" ,"Limit", NULL, false, NULL, NULL},
#if PG_VERSION_NUM >= 90500
{T_SampleScan, "B" ,"Sample Scan", NULL, false, NULL, NULL},
#endif
#if PG_VERSION_NUM >= 90600
{T_Gather, "6" ,"Gather", NULL, false, NULL, NULL},
#endif
#if PG_VERSION_NUM >= 100000
{T_ProjectSet, "7" ,"ProjectSet", NULL, false, NULL, NULL},
{T_TableFuncScan,"8","Table Function Scan", NULL, false, NULL, NULL},
{T_NamedTuplestoreScan,"9","Named Tuplestore Scan", NULL, false, NULL, NULL},
{T_GatherMerge, "A" ,"Gather Merge", NULL, false, NULL, NULL},
#endif
#if PG_VERSION_NUM >= 130000
{T_IncrementalSort, "C" ,"Incremental Sort", NULL, false, NULL, NULL},
#endif
#if PG_VERSION_NUM >= 140000
{T_TidRangeScan,"D", "Tid Range Scan", NULL, false, NULL, NULL},
{T_Memoize, "E", "Memoize", NULL, false, NULL, NULL},
#endif
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table directions[] =
{
{T_Invalid, "b" ,"Backward", "Backward", false, NULL, NULL},
{T_Invalid, "n" ,"NoMovement","", false, NULL, NULL},
{T_Invalid, "f" ,"Forward", "", false, NULL, NULL},
{T_Invalid, NULL , NULL, NULL, false, NULL, NULL}
};
word_table relationships[] =
{
{T_Invalid, "o" ,"Outer", NULL, false, NULL, NULL},
{T_Invalid, "i" ,"Inner", NULL, false, NULL, NULL},
{T_Invalid, "s" ,"Subquery", NULL, false, NULL, NULL},
{T_Invalid, "m" ,"Member", NULL, false, NULL, NULL},
{T_Invalid, "I" ,"InitPlan", NULL, false, NULL, NULL},
{T_Invalid, "S" ,"SubPlan", NULL, false, NULL, NULL},
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table strategies[] =
{
{S_Plain, "p" ,"Plain", NULL, false, NULL, NULL},
{S_Sorted, "s" ,"Sorted", NULL, false, NULL, NULL},
{S_Hashed, "h" ,"Hashed", NULL, false, NULL, NULL},
{S_Mixed, "m" ,"Mixed", NULL, false, NULL, NULL},
{S_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table operations[] =
{
{T_Invalid, "i" ,"Insert", NULL, false, NULL, NULL},
{T_Invalid, "d" ,"Delete", NULL, false, NULL, NULL},
{T_Invalid, "u" ,"Update", NULL, false, NULL, NULL},
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table jointypes[] =
{
{T_Invalid, "i" ,"Inner", NULL, false, NULL, NULL},
{T_Invalid, "l" ,"Left", NULL, false, NULL, NULL},
{T_Invalid, "f" ,"Full", NULL, false, NULL, NULL},
{T_Invalid, "r" ,"Right", NULL, false, NULL, NULL},
{T_Invalid, "s" ,"Semi", NULL, false, NULL, NULL},
{T_Invalid, "a" ,"Anti", NULL, false, NULL, NULL},
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table setsetopcommands[] =
{
{T_Invalid, "i" ,"Intersect", NULL, false, NULL, NULL},
{T_Invalid, "I" ,"Intersect All", NULL, false, NULL, NULL},
{T_Invalid, "e" ,"Except", NULL, false, NULL, NULL},
{T_Invalid, "E" ,"Except All", NULL, false, NULL, NULL},
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table sortmethods[] =
{
{T_Invalid, "h" ,"top-N heapsort", NULL, false, NULL, NULL},
{T_Invalid, "q" ,"quicksort", NULL, false, NULL, NULL},
{T_Invalid, "e" ,"external sort", NULL, false, NULL, NULL},
{T_Invalid, "E" ,"external merge", NULL, false, NULL, NULL},
{T_Invalid, "s" ,"still in progress", NULL, false, NULL, NULL},
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table sortspacetype[] =
{
{T_Invalid, "d" ,"Disk", NULL, false, NULL, NULL},
{T_Invalid, "m" ,"Memory",NULL, false, NULL, NULL},
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table partialmode[] =
{
{T_Invalid, "p" ,"Partial", NULL, false, NULL, NULL},
{T_Invalid, "f" ,"Finalize",NULL, false, NULL, NULL},
{T_Invalid, "s" ,"Simple",NULL, false, NULL, NULL},
{T_Invalid, NULL, NULL, NULL, false, NULL, NULL}
};
word_table *
search_word_table(word_table *tbl, const char *word, int mode)
{
word_table *p;
bool longname =
(mode == PGSP_JSON_SHORTEN || mode == PGSP_JSON_NORMALIZE);
/*
* Use simple linear search. We can gain too small portion of the whole
* processing time using more 'clever' algorithms like b-tree or tries,
* which won't be worth the additional memory, complexity and
* initialization cost.
*/
for (p = tbl ; p->longname ; p++)
{
if (strcmp(longname ? p->longname: p->shortname, word) == 0)
break;
}
if (p->longname == NULL && mode == PGSP_JSON_TEXTIZE)
{
/* Fallback to long json prop name */
for (p = tbl ; p->longname ; p++)
if (strcmp(p->longname, word) == 0)
break;
}
return (p->longname ? p : NULL);
}
const char *
converter_core(word_table *tbl,
const char *src, pgsp_parser_mode mode)
{
word_table *p;
char *ret;
p = search_word_table(tbl, src, mode);
if (!p) return src;
ret = p->shortname;
switch(mode)
{
case PGSP_JSON_SHORTEN:
case PGSP_JSON_NORMALIZE:
ret = p->shortname;
break;
case PGSP_JSON_INFLATE:
case PGSP_JSON_YAMLIZE:
case PGSP_JSON_XMLIZE:
ret = p->longname;
break;
case PGSP_JSON_TEXTIZE:
if(p->textname)
ret = p->textname;
else
ret = p->longname;
break;
default:
elog(ERROR, "Internal error");
}
return ret;
}
const char *
conv_nodetype(const char *src, pgsp_parser_mode mode)
{
return converter_core(nodetypes, src, mode);
}
const char *
conv_scandir(const char *src, pgsp_parser_mode mode)
{
return converter_core(directions, src, mode);
}
const char *
conv_relasionship(const char *src, pgsp_parser_mode mode)
{
return converter_core(relationships, src, mode);
}
const char *
conv_strategy(const char *src, pgsp_parser_mode mode)
{
return converter_core(strategies, src, mode);
}
/*
* Look for these operator characters in order to decide whether to strip
* whitespaces which are needless from the view of sql syntax in
* normalize_expr(). This must be synced with op_chars in scan.l.
*/
#define OPCHARS "~!@#^&|`?+-*/%<>="
#define IS_WSCHAR(c) ((c) == ' ' || (c) == '\n' || (c) == '\t')
#define IS_CONST(tok) (tok == FCONST || tok == SCONST || tok == BCONST || \
tok == XCONST || tok == ICONST || tok == NULL_P || \
tok == TRUE_P || tok == FALSE_P || \
tok == CURRENT_CATALOG || tok == CURRENT_DATE || \
tok == CURRENT_ROLE || tok == CURRENT_SCHEMA || \
tok == CURRENT_TIME || tok == CURRENT_TIMESTAMP || \
tok == CURRENT_USER || \
tok == LOCALTIME || tok == LOCALTIMESTAMP)
#define IS_INDENTED_ARRAY(v) ((v) == P_GroupKeys || (v) == P_HashKeys)
/*
* norm_yylex: core_yylex with replacing some tokens.
*/
static int
norm_yylex(char *str, core_YYSTYPE *yylval, YYLTYPE *yylloc, core_yyscan_t yyscanner)
{
int tok;
PG_TRY();
{
tok = core_yylex(yylval, yylloc, yyscanner);
}
PG_CATCH();
{
/*
* Error might occur during parsing quoted tokens that chopped
* halfway. Just ignore the rest of this query even if there might
* be other reasons for parsing to fail.
*/
FlushErrorState();
return -1;
}
PG_END_TRY();
/*
* '?' alone is assumed to be an IDENT. If there's a real
* operator '?', this should be confused but there's hardly be.
*/
if (tok == Op && str[*yylloc] == '?' &&
strchr(OPCHARS, str[*yylloc + 1]) == NULL)
tok = SCONST;
/*
* Replace tokens with '=' if the operator is consists of two or
* more opchars only. Assuming that opchars do not compose a token
* with non-opchars, check the first char only is sufficient.
*/
if (tok == Op && strchr(OPCHARS, str[*yylloc]) != NULL)
tok = '=';
return tok;
}
/*
* normalize_expr - Normalize statements or expressions.
*
* Mask constants, strip unnecessary whitespaces and upcase keywords. expr is
* modified in-place (destructively). If readability is more important than
* uniqueness, preserve_space puts one space for one existent whitespace for
* more readability.
*/
/* scanner interface is changed in PG12 */
#if PG_VERSION_NUM < 120000
#define ScanKeywords (*ScanKeywords)
#define ScanKeywordTokens NumScanKeywords
#endif
void
normalize_expr(char *expr, bool preserve_space)
{
core_yyscan_t yyscanner;
core_yy_extra_type yyextra;
core_YYSTYPE yylval;
YYLTYPE yylloc;
YYLTYPE lastloc;
YYLTYPE start;
char *wp;
int tok, lasttok;
wp = expr;
yyscanner = scanner_init(expr,
&yyextra,
&ScanKeywords,
ScanKeywordTokens);
/*
* The warnings about nonstandard escape strings is already emitted in the
* core. Just silence them here.
*/
#if PG_VERSION_NUM >= 90500
yyextra.escape_string_warning = false;
#endif
lasttok = 0;
lastloc = -1;
for (;;)
{
tok = norm_yylex(expr, &yylval, &yylloc, yyscanner);
start = yylloc;
if (lastloc >= 0)
{
int i, i2;
/* Skipping preceding whitespaces */
for(i = lastloc ; i < start && IS_WSCHAR(expr[i]) ; i++);
/* Searching for trailing whitespace */
for(i2 = i; i2 < start && !IS_WSCHAR(expr[i2]) ; i2++);
if (lasttok == IDENT)
{
/* Identifiers are copied in case-sensitive manner. */
memcpy(wp, expr + i, i2 - i);
wp += i2 - i;
}
#if PG_VERSION_NUM >= 100000
/*
* Since PG10 pg_stat_statements doesn't store trailing semicolon
* in the column "query". Normalization is basically useless in the
* version but still usefull to match utility commands so follow
* the behavior change.
*/
else if (lasttok == ';')
{
/* Just do nothing */
}
#endif
else
{
/* Upcase keywords */
char *sp;
for (sp = expr + i ; sp < expr + i2 ; sp++, wp++)
*wp = (*sp >= 'a' && *sp <= 'z' ?
*sp - ('a' - 'A') : *sp);
}
/*
* Because of destructive writing, wp must not go advance the
* reading point.
* Although this function's output does not need any validity as a
* statement or an expression, spaces are added where it should be
* to keep some extent of sanity. If readability is more important
* than uniqueness, preserve_space adds one space for each
* existent whitespace.
*/
if (tok > 0 &&
i2 < start &&
(preserve_space ||
(tok >= IDENT && lasttok >= IDENT &&
!IS_CONST(tok) && !IS_CONST(lasttok))))
*wp++ = ' ';
start = i2;
}
/* Exit on parse error. */
if (tok < 0)
{
*wp = 0;
return;
}
/*
* Negative signs before numbers are tokenized separately. And
* explicit positive signs won't appear in deparsed expressions.
*/
if (tok == '-')
tok = norm_yylex(expr, &yylval, &yylloc, yyscanner);
/* Exit on parse error. */
if (tok < 0)
{
*wp = 0;
return;
}
if (IS_CONST(tok))
{
YYLTYPE end;
tok = norm_yylex(expr, &yylval, &end, yyscanner);
/* Exit on parse error. */
if (tok < 0)
{
*wp = 0;
return;
}
/*
* Negative values may be surrounded with parens by the
* deparser. Mask involving them.
*/
if (lasttok == '(' && tok == ')')
{
wp -= (start - lastloc);
start = lastloc;
end++;
}
while (expr[end - 1] == ' ')
end--;
*wp++ = '?';
yylloc = end;
}
if (tok == 0)
break;
lasttok = tok;
lastloc = yylloc;
}
*wp = 0;
}
const char *
conv_expression(const char *src, pgsp_parser_mode mode)
{
const char *ret = src;
if (mode == PGSP_JSON_NORMALIZE)
{
char *t = pstrdup(src);
normalize_expr(t, true);
ret = (const char *)t;
}
return ret;
}
const char *
conv_operation(const char *src, pgsp_parser_mode mode)
{
return converter_core(operations, src, mode);
}
const char *
conv_jointype(const char *src, pgsp_parser_mode mode)
{
return converter_core(jointypes, src, mode);
}
const char *
conv_setsetopcommand(const char *src, pgsp_parser_mode mode)
{
return converter_core(setsetopcommands, src, mode);
}
const char *
conv_sortmethod(const char *src, pgsp_parser_mode mode)
{
return converter_core(sortmethods, src, mode);
}
const char *
conv_sortspacetype(const char *src, pgsp_parser_mode mode)
{
return converter_core(sortspacetype, src, mode);
}
const char *
conv_partialmode(const char *src, pgsp_parser_mode mode)
{
return converter_core(partialmode, src, mode);
}
/**** Parser callbacks ****/
/* JSON */
static JsonParseErrorType
json_objstart(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (ctx->mode == PGSP_JSON_INFLATE)
{
if (!ctx->fname && ctx->dest->len > 0)
{
appendStringInfoChar(ctx->dest, '\n');
appendStringInfoSpaces(ctx->dest, (ctx->level) * INDENT_STEP);
}
ctx->fname = NULL;
}
appendStringInfoChar(ctx->dest, '{');
ctx->level++;
ctx->first = bms_add_member(ctx->first, ctx->level);
if (ctx->mode == PGSP_JSON_INFLATE)
appendStringInfoChar(ctx->dest, '\n');
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
json_objend(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (ctx->mode == PGSP_JSON_INFLATE)
{
if (!bms_is_member(ctx->level, ctx->first))
appendStringInfoChar(ctx->dest, '\n');
appendStringInfoSpaces(ctx->dest, (ctx->level - 1) * INDENT_STEP);
}
appendStringInfoChar(ctx->dest, '}');
ctx->level--;
ctx->last_elem_is_object = true;
ctx->first = bms_del_member(ctx->first, ctx->level);
ctx->fname = NULL;
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
json_arrstart(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (IS_INDENTED_ARRAY(ctx->current_list))
ctx->wlist_level++;
appendStringInfoChar(ctx->dest, '[');
ctx->fname = NULL;
ctx->level++;
ctx->last_elem_is_object = true;
ctx->first = bms_add_member(ctx->first, ctx->level);
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
json_arrend(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (IS_INDENTED_ARRAY(ctx->current_list))
ctx->wlist_level--;
if (ctx->mode == PGSP_JSON_INFLATE &&
(IS_INDENTED_ARRAY(ctx->current_list) ?
ctx->wlist_level == 0 : ctx->last_elem_is_object))
{
appendStringInfoChar(ctx->dest, '\n');
appendStringInfoSpaces(ctx->dest, (ctx->level - 1) * INDENT_STEP);
}
appendStringInfoChar(ctx->dest, ']');
ctx->level--;
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
json_ofstart(void *state, char *fname, bool isnull)
{
word_table *p;
pgspParserContext *ctx = (pgspParserContext *)state;
char *fn;
ctx->remove = false;
p = search_word_table(propfields, fname, ctx->mode);
if (!p)
{
ereport(DEBUG1,
(errmsg("JSON parser encoutered unknown field name: \"%s\".", fname),
errdetail_log("INPUT: \"%s\"", ctx->org_string)));
}
ctx->remove = (ctx->mode == PGSP_JSON_NORMALIZE &&
(!p || !p->normalize_use));
if (ctx->remove)
JSONACTION_RETURN_SUCCESS();
if (!bms_is_member(ctx->level, ctx->first))
{
appendStringInfoChar(ctx->dest, ',');
if (ctx->mode == PGSP_JSON_INFLATE)
appendStringInfoChar(ctx->dest, '\n');
}
else
ctx->first = bms_del_member(ctx->first, ctx->level);
if (ctx->mode == PGSP_JSON_INFLATE)
appendStringInfoSpaces(ctx->dest, ctx->level * INDENT_STEP);
/*
* We intentionally let some property names not have a short name. Use long
* name for the cases.
*/
if (!p || !p->longname)
fn = fname;
else if (ctx->mode == PGSP_JSON_INFLATE ||
!(p->shortname && p->shortname[0]))
fn = p->longname;
else
fn = p->shortname;
escape_json(ctx->dest, fn);
ctx->fname = fn;
ctx->valconverter = (p ? p->converter : NULL);
appendStringInfoChar(ctx->dest, ':');
if (ctx->mode == PGSP_JSON_INFLATE)
appendStringInfoChar(ctx->dest, ' ');
if (p && IS_INDENTED_ARRAY(p->tag))
{
ctx->current_list = p->tag;
ctx->list_fname = fname;
ctx->wlist_level = 0;
}
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
json_ofend(void *state, char *fname, bool isnull)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (ctx->list_fname && strcmp(fname, ctx->list_fname) == 0)
{
ctx->list_fname = NULL;
ctx->current_list = P_Invalid;
}
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
json_aestart(void *state, bool isnull)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (ctx->remove)
JSONACTION_RETURN_SUCCESS();
if (IS_INDENTED_ARRAY(ctx->current_list) &&
ctx->wlist_level == 1)
{
if (!bms_is_member(ctx->level, ctx->first))
appendStringInfoChar(ctx->dest, ',');
if (ctx->mode == PGSP_JSON_INFLATE)
{
appendStringInfoChar(ctx->dest, '\n');
appendStringInfoSpaces(ctx->dest, (ctx->level) * INDENT_STEP);
}
}
else
{
if (!bms_is_member(ctx->level, ctx->first))
{
appendStringInfoChar(ctx->dest, ',');
if (ctx->mode == PGSP_JSON_INFLATE &&
!ctx->last_elem_is_object)
appendStringInfoChar(ctx->dest, ' ');
}
}
ctx->first = bms_del_member(ctx->first, ctx->level);
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
json_scalar(void *state, char *token, JsonTokenType tokentype)
{
pgspParserContext *ctx = (pgspParserContext *)state;
const char *val = token;
if (ctx->remove)
JSONACTION_RETURN_SUCCESS();
if (ctx->valconverter)
val = ctx->valconverter(token, ctx->mode);
if (tokentype == JSON_TOKEN_STRING)
escape_json(ctx->dest, val);
else
appendStringInfoString(ctx->dest, val);
ctx->last_elem_is_object = false;
JSONACTION_RETURN_SUCCESS();
}
/* YAML */
static JsonParseErrorType
yaml_objstart(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (ctx->fname)
{
if (ctx->dest->len > 0)
appendStringInfoChar(ctx->dest, '\n');
appendStringInfoSpaces(ctx->dest, (ctx->level - 1) * INDENT_STEP);
appendStringInfoString(ctx->dest, "- ");
appendStringInfoString(ctx->dest, ctx->fname);
appendStringInfoString(ctx->dest, ":\n");
appendStringInfoSpaces(ctx->dest, (ctx->level + 1) * INDENT_STEP);
ctx->fname = NULL;
}
ctx->level++;
ctx->first = bms_add_member(ctx->first, ctx->level);
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
yaml_objend(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
ctx->level--;
ctx->last_elem_is_object = true;
ctx->first = bms_del_member(ctx->first, ctx->level);
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
yaml_arrstart(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
if (ctx->fname)
{
appendStringInfoString(ctx->dest, ctx->fname);
appendStringInfoString(ctx->dest, ":");
}
ctx->fname = NULL;
ctx->level++;
ctx->first = bms_add_member(ctx->first, ctx->level);
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
yaml_arrend(void *state)
{
pgspParserContext *ctx = (pgspParserContext *)state;
ctx->level--;
JSONACTION_RETURN_SUCCESS();
}
static JsonParseErrorType
yaml_ofstart(void *state, char *fname, bool isnull)
{
word_table *p;
pgspParserContext *ctx = (pgspParserContext *)state;
char *s;
p = search_word_table(propfields, fname, ctx->mode);