forked from enova/pgl_ddl_deploy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres_deparse.18.c
More file actions
12257 lines (10949 loc) · 376 KB
/
Copy pathpostgres_deparse.18.c
File metadata and controls
12257 lines (10949 loc) · 376 KB
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
#include "pg_config.h"
#if(PG_MAJORVERSION_NUM == 18)
// From https://github.com/pganalyze/libpg_query/blob/18.0.0/src/postgres_deparse.c
// Copyright (c) 2015, Lukas Fittl <lukas@fittl.com>
// Copyright (c) 2016-2023, Duboce Labs, Inc. (pganalyze) <team@pganalyze.com>
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of pg_query nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "postgres_deparse.h"
#include "postgres.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "catalog/pg_attribute.h"
#include "catalog/pg_class.h"
#include "catalog/pg_trigger.h"
#include "commands/trigger.h"
#include "common/keywords.h"
#include "common/kwlookup.h"
#include "lib/stringinfo.h"
#include "nodes/nodes.h"
#include "nodes/parsenodes.h"
#include "nodes/pg_list.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/timestamp.h"
#include "utils/xml.h"
/*
* # Deparser overview
*
* The deparser works by walking the input parse tree and emitting into the
* currently active "part" as pointed to (indirectly) by the state struct.
*
* A lot of the structure of the deparser described below is meant to support
* the optional "pretty print" mode that can be enabled and configured through
* the deparser options, and inserts whitespace (newlines/spaces) as needed to
* make the output easier to read.
*
* ## Nesting levels
*
* Starting at the state struct we have a currently active "nesting level",
* which indicates the base indentation, as well as contains one or more part
* groups, each of which has one or more parts.
*
* Nesting levels are typically opened, or "increased", when processing a new
* statement contained within other statements, or for certain statement-like
* constructs (e.g. CASE clauses) that require custom indendation.
*
* Nesting levels are closed, or "decreased", when exiting such statements or
* statement-like constructs. During this operation all parts and subparts get
* flattened (turned into a simple list of parts), and are added to the parent
* nesting level.
*
* At the end of the tree walk the parts of the top most nesting level get
* emitted into the output string, formatted based on the deparse options.
*
* ## Part groups
*
* Part groups are usually started for each "major" keyword, which is chosen
* for how the output is intended to be laid out. For example, the "FROM"
* keyword in a SELECT statement is considered "major" and starts a new part
* group, vs the "JOIN" keyword is not, and as such both regular tables and
* JOIN clauses will be within one part group.
*
* ## Parts, indentation and merging
*
* The parts contained in part groups may be indented one additional level
* beyond the base indentation of the currently active nesting level, to help
* differentiate them from the major keywords. This can be turned off with
* DEPARSE_PART_NO_INDENT, for example as needed to format WITH clauses
* effectively.
*
* Parts may be merged with other parts within the same group, if the indent
* mode is set to DEPARSE_PART_INDENT_AND_MERGE. This is utilized to put
* certain items, for example the target list items in SELECT on one or more
* lines, breaking at separators as needed to respect the maximum line limit.
*
* ## Node context
*
* Node context is used when the same function in the deparser needs to behave
* differently depending on the parent node. For example, a SELECT statement
* needs wrapping parenthesis in certain situations where the parent statement
* uses a set operation (e.g. UNION).
*
* ## Comments
*
* Comments do not exist as nodes in a Postgres parse tree, and as such need to
* be passed in separately through the deparser options. They are placed in the
* output on a best effort basis, by matching against node locations. Comments
* will only be output at most once, but may not be output at all in certain
* cases, for example when the comment's specified match location is never
* reached by any of the nodes visited.
*/
typedef enum DeparseNodeContext {
DEPARSE_NODE_CONTEXT_NONE,
// Parent node type (and sometimes field)
DEPARSE_NODE_CONTEXT_INSERT_RELATION,
DEPARSE_NODE_CONTEXT_INSERT_SELECT,
DEPARSE_NODE_CONTEXT_A_EXPR,
DEPARSE_NODE_CONTEXT_CREATE_TYPE,
DEPARSE_NODE_CONTEXT_ALTER_TYPE,
DEPARSE_NODE_CONTEXT_ALTER_DOMAIN,
DEPARSE_NODE_CONTEXT_SET_STATEMENT,
DEPARSE_NODE_CONTEXT_FUNC_EXPR,
DEPARSE_NODE_CONTEXT_SELECT_SETOP,
DEPARSE_NODE_CONTEXT_SELECT_SORT_CLAUSE,
// Identifier vs constant context
DEPARSE_NODE_CONTEXT_IDENTIFIER,
DEPARSE_NODE_CONTEXT_CONSTANT
} DeparseNodeContext;
typedef enum DeparsePartIndentMode {
/* Don't indent parts at all, used in special cases (e.g. WITH clauses) */
DEPARSE_PART_NO_INDENT,
/* Indent parts but don't merge them (keep each on their own line) */
DEPARSE_PART_INDENT,
/* Indent parts and merge them together up to the max line length */
DEPARSE_PART_INDENT_AND_MERGE
} DeparsePartIndentMode;
// Each part is typically one line to be emitted in pretty print mode
typedef struct DeparseStatePart
{
StringInfo str;
/* If this gets emitted as its own line, number of spaces to be added as indentation */
int indent;
/* Allow merging this part with adjacent parts that are marked as mergeable */
bool mergeable;
} DeparseStatePart;
// A part group are typically all parts associated with a major keyword
typedef struct DeparseStatePartGroup
{
const char *keyword;
List *parts;
DeparsePartIndentMode indent_mode;
} DeparseStatePartGroup;
// Nesting levels may be statements, or complex parts of statements that should be indented (e.g. CASE)
typedef struct DeparseStateNestingLevel
{
/* List of DeparseStatePartGroup items */
List *part_groups;
/* Add this much indentation to every part */
int base_indent;
} DeparseStateNestingLevel;
typedef struct DeparseState
{
DeparseStateNestingLevel *current;
/* List of DeparseStatePart items */
List *result_parts;
/* Deparse options originally passed in */
PostgresDeparseOpts *opts;
/* Set of indexes of comments already placed in the output query */
Bitmapset *emitted_comments;
} DeparseState;
static void deparseSelectStmt(DeparseState *state, SelectStmt *stmt, DeparseNodeContext context);
static void deparseIntoClause(DeparseState *state, IntoClause *into_clause);
static void deparseRangeVar(DeparseState *state, RangeVar *range_var, DeparseNodeContext context);
static void deparseResTarget(DeparseState *state, ResTarget *res_target, DeparseNodeContext context);
static void deparseAlias(DeparseState *state, Alias *alias);
static void deparseWindowDef(DeparseState *state, WindowDef* window_def);
static void deparseColumnRef(DeparseState *state, ColumnRef* column_ref);
static void deparseSubLink(DeparseState *state, SubLink* sub_link);
static void deparseAExpr(DeparseState *state, A_Expr* a_expr, DeparseNodeContext context);
static void deparseBoolExpr(DeparseState *state, BoolExpr *bool_expr);
static void deparseAStar(DeparseState *state, A_Star* a_star);
static void deparseCollateClause(DeparseState *state, CollateClause* collate_clause);
static void deparseSortBy(DeparseState *state, SortBy* sort_by);
static void deparseParamRef(DeparseState *state, ParamRef* param_ref);
static void deparseSQLValueFunction(DeparseState *state, SQLValueFunction* sql_value_function);
static void deparseWithClause(DeparseState *state, WithClause *with_clause);
static void deparseJoinExpr(DeparseState *state, JoinExpr *join_expr);
static void deparseCommonTableExpr(DeparseState *state, CommonTableExpr *cte);
static void deparseRangeSubselect(DeparseState *state, RangeSubselect *range_subselect);
static void deparseRangeFunction(DeparseState *state, RangeFunction *range_func);
static void deparseAArrayExpr(DeparseState *state, A_ArrayExpr * array_expr);
static void deparseRowExpr(DeparseState *state, RowExpr *row_expr);
static void deparseTypeCast(DeparseState *state, TypeCast *type_cast, DeparseNodeContext context);
static void deparseTypeName(DeparseState *state, TypeName *type_name);
static void deparseIntervalTypmods(DeparseState *state, TypeName *type_name);
static void deparseNullTest(DeparseState *state, NullTest *null_test);
static void deparseCaseExpr(DeparseState *state, CaseExpr *case_expr);
static void deparseCaseWhen(DeparseState *state, CaseWhen *case_when);
static void deparseAIndirection(DeparseState *state, A_Indirection *a_indirection);
static void deparseAIndices(DeparseState *state, A_Indices *a_indices);
static void deparseCoalesceExpr(DeparseState *state, CoalesceExpr *coalesce_expr);
static void deparseBooleanTest(DeparseState *state, BooleanTest *boolean_test);
static void deparseColumnDef(DeparseState *state, ColumnDef *column_def);
static void deparseInsertStmt(DeparseState *state, InsertStmt *insert_stmt);
static void deparseOnConflictClause(DeparseState *state, OnConflictClause *on_conflict_clause);
static void deparseIndexElem(DeparseState *state, IndexElem* index_elem);
static void deparseUpdateStmt(DeparseState *state, UpdateStmt *update_stmt);
static void deparseDeleteStmt(DeparseState *state, DeleteStmt *delete_stmt);
static void deparseLockingClause(DeparseState *state, LockingClause *locking_clause);
static void deparseSetToDefault(DeparseState *state, SetToDefault *set_to_default);
static void deparseCreateCastStmt(DeparseState *state, CreateCastStmt *create_cast_stmt);
static void deparseCreateDomainStmt(DeparseState *state, CreateDomainStmt *create_domain_stmt);
static void deparseFunctionParameter(DeparseState *state, FunctionParameter *function_parameter);
static void deparseRoleSpec(DeparseState *state, RoleSpec *role_spec);
static void deparseViewStmt(DeparseState *state, ViewStmt *view_stmt);
static void deparseVariableSetStmt(DeparseState *state, VariableSetStmt* variable_set_stmt);
static void deparseReplicaIdentityStmt(DeparseState *state, ReplicaIdentityStmt *replica_identity_stmt);
static void deparseRangeTableSample(DeparseState *state, RangeTableSample *range_table_sample);
static void deparseRangeTableFunc(DeparseState *state, RangeTableFunc* range_table_func);
static void deparseGroupingSet(DeparseState *state, GroupingSet *grouping_set);
static void deparseFuncCall(DeparseState *state, FuncCall *func_call, DeparseNodeContext context);
static void deparseMinMaxExpr(DeparseState *state, MinMaxExpr *min_max_expr);
static void deparseXmlExpr(DeparseState *state, XmlExpr* xml_expr, DeparseNodeContext context);
static void deparseXmlSerialize(DeparseState *state, XmlSerialize *xml_serialize);
static void deparseJsonIsPredicate(DeparseState *state, JsonIsPredicate *json_is_predicate);
static void deparseJsonObjectAgg(DeparseState *state, JsonObjectAgg *json_object_agg);
static void deparseJsonArrayAgg(DeparseState *state, JsonArrayAgg *json_array_agg);
static void deparseJsonObjectConstructor(DeparseState *state, JsonObjectConstructor *json_object_constructor);
static void deparseJsonArrayConstructor(DeparseState *state, JsonArrayConstructor *json_array_constructor);
static void deparseJsonArrayQueryConstructor(DeparseState *state, JsonArrayQueryConstructor *json_array_query_constructor);
static void deparseJsonValueExpr(DeparseState *state, JsonValueExpr *json_value_expr);
static void deparseJsonOutput(DeparseState *state, JsonOutput *json_output);
static void deparseJsonParseExpr(DeparseState *state, JsonParseExpr *json_parse_expr);
static void deparseJsonScalarExpr(DeparseState *state, JsonScalarExpr *json_scalar_expr);
static void deparseJsonSerializeExpr(DeparseState *state, JsonSerializeExpr *json_serialize_expr);
static void deparseJsonTable(DeparseState *state, JsonTable *json_table);
static void deparseJsonTableColumn(DeparseState *state, JsonTableColumn *json_table_column);
static void deparseJsonTableColumns(DeparseState *state, List *json_table_columns);
static void deparseJsonTablePathSpec(DeparseState *state, JsonTablePathSpec *json_table_path_spec);
static void deparseJsonBehavior(DeparseState *state, JsonBehavior *json_behavior);
static void deparseJsonFuncExpr(DeparseState *state, JsonFuncExpr *json_func_expr);
static void deparseJsonQuotesClauseOpt(DeparseState *state, JsonQuotes quotes);
static void deparseJsonOnErrorClauseOpt(DeparseState *state, JsonBehavior *behavior);
static void deparseJsonOnEmptyClauseOpt(DeparseState *state, JsonBehavior *behavior);
static void deparseConstraint(DeparseState *state, Constraint *constraint, DeparseNodeContext context);
static void deparseATAlterConstraint(DeparseState *state, ATAlterConstraint *constraint);
static void deparseSchemaStmt(DeparseState *state, Node *node);
static void deparseExecuteStmt(DeparseState *state, ExecuteStmt *execute_stmt);
static void deparseTriggerTransition(DeparseState *state, TriggerTransition *trigger_transition);
static void deparseCreateOpClassItem(DeparseState *state, CreateOpClassItem *create_op_class_item);
static void deparseAConst(DeparseState *state, A_Const *a_const);
static void deparseGroupingFunc(DeparseState *state, GroupingFunc *grouping_func);
static void deparsePreparableStmt(DeparseState *state, Node *node);
static void deparseRuleActionStmt(DeparseState *state, Node *node);
static void deparseExplainableStmt(DeparseState *state, Node *node);
static void deparseStmt(DeparseState *state, Node *node);
static void deparseValue(DeparseState *state, union ValUnion *value, DeparseNodeContext context);
static void
removeTrailingSpaceFromStr(StringInfo str)
{
if (str->len >= 1 && str->data[str->len - 1] == ' ') {
str->len -= 1;
str->data[str->len] = '\0';
}
}
// Check whether the value is a reserved keyword, to determine escaping for output
//
// Note that since the parser lowercases all keywords, this does *not* match when the
// value is not all-lowercase and a reserved keyword.
static bool
isReservedKeyword(const char *val)
{
int kwnum = ScanKeywordLookup(val, &ScanKeywords);
bool all_lower_case = true;
const char *cp;
for (cp = val; *cp; cp++)
{
if (!(
(*cp >= 'a' && *cp <= 'z') ||
(*cp >= '0' && *cp <= '9') ||
(*cp == '_')))
{
all_lower_case = false;
break;
}
}
return all_lower_case && kwnum >= 0 && ScanKeywordCategories[kwnum] == RESERVED_KEYWORD;
}
// Returns whether the given value consists only of operator characters
static bool
isOp(const char *val)
{
const char *cp;
Assert(strlen(val) > 0);
for (cp = val; *cp; cp++)
{
if (!(
*cp == '~' ||
*cp == '!' ||
*cp == '@' ||
*cp == '#' ||
*cp == '^' ||
*cp == '&' ||
*cp == '|' ||
*cp == '`' ||
*cp == '?' ||
*cp == '+' ||
*cp == '-' ||
*cp == '*' ||
*cp == '/' ||
*cp == '%' ||
*cp == '<' ||
*cp == '>' ||
*cp == '='))
return false;
}
return true;
}
static DeparseStatePart *
makeDeparseStatePart(DeparseState *state, DeparseStateNestingLevel *level, DeparsePartIndentMode indent_mode)
{
DeparseStatePart *part = palloc(sizeof(DeparseStatePart));
part->str = makeStringInfo();
part->indent = level->base_indent;
if (indent_mode != DEPARSE_PART_NO_INDENT)
part->indent += state->opts->indent_size;
part->mergeable = indent_mode == DEPARSE_PART_INDENT_AND_MERGE;
return part;
}
static void
freeDeparseStatePart(DeparseStatePart *part)
{
pfree(part->str->data);
pfree(part->str);
pfree(part);
}
// Returns current active part group, and initializes the first one (including an empty part) if needed
static DeparseStatePartGroup *
deparseGetCurrentPartGroup(DeparseState *state)
{
DeparseStateNestingLevel *level = state->current;
if (level->part_groups)
return (DeparseStatePartGroup *) llast(level->part_groups);
DeparseStatePartGroup *part_group = palloc0(sizeof(DeparseStatePartGroup));
part_group->parts = lappend(part_group->parts, makeDeparseStatePart(state, level, part_group->indent_mode));
level->part_groups = lappend(level->part_groups, part_group);
return part_group;
}
static DeparseStatePart *
deparseGetCurrentPart(DeparseState *state)
{
DeparseStatePartGroup *part_group = deparseGetCurrentPartGroup(state);
return (DeparseStatePart *) llast(part_group->parts);
}
static void
deparseMarkCurrentPartNonMergable(DeparseState *state)
{
DeparseStatePart *part = deparseGetCurrentPart(state);
part->mergeable = false;
}
static StringInfo deparseGetCurrentStringInfo(DeparseState *state)
{
DeparseStatePart *part = deparseGetCurrentPart(state);
Assert(part != NULL);
return part->str;
}
static void deparseAppendStringInfo(DeparseState *state, const char *fmt,...)
{
StringInfo str = deparseGetCurrentStringInfo(state);
int save_errno = errno;
for (;;)
{
va_list args;
int needed;
/* Try to format the data. */
errno = save_errno;
va_start(args, fmt);
needed = appendStringInfoVA(str, fmt, args);
va_end(args);
if (needed == 0)
break; /* success */
/* Increase the buffer size and try again. */
enlargeStringInfo(str, needed);
}
}
static void deparseAppendStringInfoString(DeparseState *state, const char *s)
{
StringInfo str = deparseGetCurrentStringInfo(state);
appendStringInfoString(str, s);
}
static void deparseAppendStringInfoChar(DeparseState *state, char ch)
{
StringInfo str = deparseGetCurrentStringInfo(state);
appendStringInfoChar(str, ch);
}
static void
removeTrailingSpace(DeparseState *state)
{
StringInfo str = deparseGetCurrentStringInfo(state);
removeTrailingSpaceFromStr(str);
}
static void
deparseRemoveTrailingEmptyPart(DeparseState *state)
{
DeparseStatePartGroup *part_group = deparseGetCurrentPartGroup(state);
DeparseStatePart *last_part = deparseGetCurrentPart(state);
if (last_part->str->len == 0)
{
freeDeparseStatePart(last_part);
part_group->parts = list_delete_last(part_group->parts);
}
}
static void
deparseAppendPart(DeparseState *state, bool deduplicate)
{
DeparseStatePartGroup *part_group = deparseGetCurrentPartGroup(state);
// Remove previous part if its empty and we deduplicate. We don't keep
// the existing part since it may have the wrong indent level or mode.
if (deduplicate)
deparseRemoveTrailingEmptyPart(state);
part_group->parts = lappend(part_group->parts, makeDeparseStatePart(state, state->current, part_group->indent_mode));
}
static void
deparseAppendCommaAndPart(DeparseState *state)
{
if (state->opts->commas_start_of_line)
{
deparseAppendPart(state, true);
deparseAppendStringInfoString(state, ", ");
}
else
{
deparseAppendStringInfoChar(state, ',');
deparseAppendPart(state, true);
}
}
static void
deparseAppendPartGroup(DeparseState *state, const char *keyword, DeparsePartIndentMode indent_mode)
{
DeparseStateNestingLevel *level = state->current;
DeparseStatePartGroup *part_group = palloc0(sizeof(DeparseStatePartGroup));
if (list_length(level->part_groups) > 0)
removeTrailingSpace(state);
part_group->keyword = keyword;
part_group->parts = lappend(part_group->parts, makeDeparseStatePart(state, state->current, indent_mode));
part_group->indent_mode = indent_mode;
level->part_groups = lappend(level->part_groups, part_group);
}
static void
deparseAppendCommentsIfNeeded(DeparseState *state, ParseLoc location)
{
for (int i = 0; i < state->opts->comment_count; i++)
{
if (bms_is_member(i, state->emitted_comments))
continue;
PostgresDeparseComment *comment = state->opts->comments[i];
if (comment->match_location > location)
continue;
// Emit one less leading newline if we already emitted one for formatting reasons
int newlines_before_comment = comment->newlines_before_comment;
if (state->opts->pretty_print && newlines_before_comment > 0 &&
deparseGetCurrentPartGroup(state)->keyword != NULL &&
deparseGetCurrentStringInfo(state)->len == 0)
newlines_before_comment -= 1;
for (int j = 0; j < newlines_before_comment; j++)
{
if (state->opts->pretty_print)
deparseAppendPart(state, false);
else
deparseAppendStringInfoChar(state, '\n');
}
deparseAppendStringInfoString(state, comment->str);
/* never merge comments with other parts */
deparseMarkCurrentPartNonMergable(state);
for (int j = 0; j < comment->newlines_after_comment; j++)
{
if (state->opts->pretty_print)
deparseAppendPart(state, false);
else
deparseAppendStringInfoChar(state, '\n');
}
state->emitted_comments = bms_add_member(state->emitted_comments, i);
}
}
static void
deparseEmit(DeparseState *state, StringInfo str)
{
ListCell *lc;
/* If the last part is empty, drop it, so we don't confuse the newline output */
DeparseStatePart *last_part = (DeparseStatePart *) llast(state->result_parts);
if (last_part && last_part->str->len == 0)
{
freeDeparseStatePart(last_part);
state->result_parts = list_delete_last(state->result_parts);
}
foreach (lc, state->result_parts)
{
DeparseStatePart *part = (DeparseStatePart *) lfirst(lc);
bool last_part = list_cell_number(state->result_parts, lc) == list_length(state->result_parts) - 1;
if (!state->opts->pretty_print && part->str->len > 0 && (part->str->data[0] == ')' || part->str->data[0] == ';'))
removeTrailingSpaceFromStr(str);
if (state->opts->pretty_print)
{
for (int i = 0; i < part->indent; i++)
appendStringInfoChar(str, ' ');
}
appendStringInfoString(str, part->str->data);
removeTrailingSpaceFromStr(str);
if (!last_part)
{
if (state->opts->pretty_print)
appendStringInfoChar(str, '\n');
else if (str->data[str->len - 1] != '(')
appendStringInfoChar(str, ' ');
}
freeDeparseStatePart(part);
}
list_free(state->result_parts);
state->result_parts = NIL;
if (state->opts->pretty_print && state->opts->trailing_newline)
appendStringInfoChar(str, '\n');
}
static DeparseStateNestingLevel *
deparseStateIncreaseNestingLevel(DeparseState *state)
{
DeparseStateNestingLevel *parent = state->current;
DeparseStateNestingLevel *level = palloc0(sizeof(DeparseStateNestingLevel));
if (parent)
{
DeparseStatePartGroup *part_group = deparseGetCurrentPartGroup(state);
level->base_indent = parent->base_indent + state->opts->indent_size;
if (part_group->indent_mode != DEPARSE_PART_NO_INDENT) /* Indent again if parts next to us are also indented */
level->base_indent += state->opts->indent_size;
/* Parts with nested elements don't get merged, even if otherwise permitted */
deparseMarkCurrentPartNonMergable(state);
}
state->current = level;
return parent;
}
static void
deparseStateDecreaseNestingLevel(DeparseState *state, DeparseStateNestingLevel *parent_level)
{
ListCell *lc;
ListCell *lc2;
DeparseStateNestingLevel *level = state->current;
Assert(level != NULL);
foreach (lc, level->part_groups)
{
DeparseStatePartGroup *part_group = (DeparseStatePartGroup *) lfirst(lc);
/* Merge parts */
if (part_group->indent_mode == DEPARSE_PART_INDENT_AND_MERGE && list_length(part_group->parts) > 1)
{
DeparseStatePart *target = (DeparseStatePart *) linitial(part_group->parts);
for_each_from (lc2, part_group->parts, 1)
{
DeparseStatePart *part = (DeparseStatePart *) lfirst(lc2);
removeTrailingSpaceFromStr(target->str);
if (target->mergeable && part->mergeable &&
target->indent + target->str->len + 1 + part->str->len <= state->opts->max_line_length)
{
if (target->str->len > 0 && target->str->data[target->str->len - 1] != '(')
appendStringInfoChar(target->str, ' ');
appendStringInfoString(target->str, part->str->data);
freeDeparseStatePart(part);
part_group->parts = foreach_delete_current(part_group->parts, lc2);
}
else
{
target = part;
}
}
}
if (part_group->keyword != NULL)
{
DeparseStatePart *target = makeDeparseStatePart(state, level, false);
appendStringInfoString(target->str, part_group->keyword);
part_group->parts = list_insert_nth(part_group->parts, 0, target);
if (list_length(part_group->parts) == 2 || part_group->indent_mode == DEPARSE_PART_NO_INDENT)
{
DeparseStatePart *part = (DeparseStatePart *) lsecond(part_group->parts);
if (part->str->len > 0)
appendStringInfo(target->str, " %s", part->str->data);
freeDeparseStatePart(part);
part_group->parts = list_delete_nth_cell(part_group->parts, 1);
}
}
if (parent_level)
{
DeparseStatePartGroup *parent_part_group = (DeparseStatePartGroup *) llast(parent_level->part_groups);
parent_part_group->parts = list_concat(parent_part_group->parts, part_group->parts);
}
else
{
// If its the top level, save as results instead
state->result_parts = list_concat(state->result_parts, part_group->parts);
}
list_free(part_group->parts);
pfree(part_group);
}
list_free(level->part_groups);
pfree(level);
state->current = parent_level;
if (parent_level)
{
/* Make sure parent statement writes that follow are on their own line */
deparseAppendPart(state, true);
/* Parts with nested elements don't get merged, even if otherwise permitted */
deparseMarkCurrentPartNonMergable(state);
}
}
/*
* Append a SQL string literal representing "val" to buf.
*
* Copied here from postgres_fdw/deparse.c to avoid adding
* many additional dependencies, and modified to work with deparser
* state.
*/
static void
deparseStringLiteral(DeparseState *state, const char *val)
{
const char *valptr;
/*
* Rather than making assumptions about the remote server's value of
* standard_conforming_strings, always use E'foo' syntax if there are any
* backslashes. This will fail on remote servers before 8.1, but those
* are long out of support.
*/
if (strchr(val, '\\') != NULL)
deparseAppendStringInfoChar(state, ESCAPE_STRING_SYNTAX);
deparseAppendStringInfoChar(state, '\'');
for (valptr = val; *valptr; valptr++)
{
char ch = *valptr;
if (SQL_STR_DOUBLE(ch, true))
deparseAppendStringInfoChar(state, ch);
deparseAppendStringInfoChar(state, ch);
}
deparseAppendStringInfoChar(state, '\'');
}
// "any_name" in gram.y
static void deparseAnyName(DeparseState *state, List *parts)
{
ListCell *lc = NULL;
foreach(lc, parts)
{
Assert(IsA(lfirst(lc), String));
deparseAppendStringInfoString(state, quote_identifier(strVal(lfirst(lc))));
if (lnext(parts, lc))
deparseAppendStringInfoChar(state, '.');
}
}
static void deparseAnyNameSkipFirst(DeparseState *state, List *parts)
{
ListCell *lc = NULL;
for_each_from(lc, parts, 1)
{
Assert(IsA(lfirst(lc), String));
deparseAppendStringInfoString(state, quote_identifier(strVal(lfirst(lc))));
if (lnext(parts, lc))
deparseAppendStringInfoChar(state, '.');
}
}
static void deparseAnyNameSkipLast(DeparseState *state, List *parts)
{
ListCell *lc = NULL;
foreach (lc, parts)
{
if (lnext(parts, lc))
{
deparseAppendStringInfoString(state, quote_identifier(strVal(lfirst(lc))));
if (foreach_current_index(lc) < list_length(parts) - 2)
deparseAppendStringInfoChar(state, '.');
}
}
}
// "func_expr" in gram.y
static void deparseFuncExpr(DeparseState *state, Node *node, DeparseNodeContext context)
{
switch (nodeTag(node))
{
case T_FuncCall:
deparseFuncCall(state, castNode(FuncCall, node), context);
break;
case T_SQLValueFunction:
deparseSQLValueFunction(state, castNode(SQLValueFunction, node));
break;
case T_MinMaxExpr:
deparseMinMaxExpr(state, castNode(MinMaxExpr, node));
break;
case T_CoalesceExpr:
deparseCoalesceExpr(state, castNode(CoalesceExpr, node));
break;
case T_XmlExpr:
deparseXmlExpr(state, castNode(XmlExpr, node), context);
break;
case T_XmlSerialize:
deparseXmlSerialize(state, castNode(XmlSerialize, node));
break;
case T_JsonObjectAgg:
deparseJsonObjectAgg(state, castNode(JsonObjectAgg, node));
break;
case T_JsonArrayAgg:
deparseJsonArrayAgg(state, castNode(JsonArrayAgg, node));
break;
case T_JsonObjectConstructor:
deparseJsonObjectConstructor(state, castNode(JsonObjectConstructor, node));
break;
case T_JsonArrayConstructor:
deparseJsonArrayConstructor(state, castNode(JsonArrayConstructor, node));
break;
case T_JsonArrayQueryConstructor:
deparseJsonArrayQueryConstructor(state, castNode(JsonArrayQueryConstructor, node));
break;
default:
elog(ERROR, "deparse: unpermitted node type in func_expr: %d",
(int) nodeTag(node));
break;
}
}
static void deparseCExpr(DeparseState *state, Node *node);
// "a_expr" in gram.y
static void deparseExpr(DeparseState *state, Node *node, DeparseNodeContext context)
{
if (node == NULL)
return;
switch (nodeTag(node))
{
case T_ColumnRef:
case T_A_Const:
case T_ParamRef:
case T_A_Indirection:
case T_CaseExpr:
case T_SubLink:
case T_A_ArrayExpr:
case T_RowExpr:
case T_GroupingFunc:
deparseCExpr(state, node);
break;
case T_TypeCast:
deparseTypeCast(state, castNode(TypeCast, node), DEPARSE_NODE_CONTEXT_NONE);
break;
case T_CollateClause:
deparseCollateClause(state, castNode(CollateClause, node));
break;
case T_A_Expr:
deparseAExpr(state, castNode(A_Expr, node), DEPARSE_NODE_CONTEXT_A_EXPR);
break;
case T_BoolExpr:
deparseBoolExpr(state, castNode(BoolExpr, node));
break;
case T_NullTest:
deparseNullTest(state, castNode(NullTest, node));
break;
case T_BooleanTest:
deparseBooleanTest(state, castNode(BooleanTest, node));
break;
case T_JsonIsPredicate:
deparseJsonIsPredicate(state, castNode(JsonIsPredicate, node));
break;
case T_SetToDefault:
deparseSetToDefault(state, castNode(SetToDefault, node));
break;
case T_MergeSupportFunc:
deparseAppendStringInfoString(state, "merge_action() ");
break;
case T_JsonParseExpr:
deparseJsonParseExpr(state, castNode(JsonParseExpr, node));
break;
case T_JsonScalarExpr:
deparseJsonScalarExpr(state, castNode(JsonScalarExpr, node));
break;
case T_JsonSerializeExpr:
deparseJsonSerializeExpr(state, castNode(JsonSerializeExpr, node));
break;
case T_JsonFuncExpr:
deparseJsonFuncExpr(state, castNode(JsonFuncExpr, node));
break;
case T_FuncCall:
case T_SQLValueFunction:
case T_MinMaxExpr:
case T_CoalesceExpr:
case T_XmlExpr:
case T_XmlSerialize:
case T_JsonObjectAgg:
case T_JsonArrayAgg:
case T_JsonObjectConstructor:
case T_JsonArrayConstructor:
case T_JsonArrayQueryConstructor:
deparseFuncExpr(state, node, context);
break;
default:
// Note that this is also the fallthrough for deparseBExpr and deparseCExpr
elog(ERROR, "deparse: unpermitted node type in a_expr/b_expr/c_expr: %d",
(int) nodeTag(node));
break;
}
}
// "b_expr" in gram.y
static void deparseBExpr(DeparseState *state, Node *node)
{
if (IsA(node, XmlExpr)) {
deparseXmlExpr(state, castNode(XmlExpr, node), DEPARSE_NODE_CONTEXT_NONE);
return;
}
if (IsA(node, A_Expr)) {
A_Expr *a_expr = castNode(A_Expr, node);
// Other kinds are handled by "c_expr", with parens added around them
if (a_expr->kind == AEXPR_OP || a_expr->kind == AEXPR_DISTINCT || a_expr->kind == AEXPR_NOT_DISTINCT) {
deparseAExpr(state, a_expr, DEPARSE_NODE_CONTEXT_NONE);
return;
}
}
if (IsA(node, BoolExpr)) {
BoolExpr *bool_expr = castNode(BoolExpr, node);
if (bool_expr->boolop == NOT_EXPR) {
deparseBoolExpr(state, bool_expr);
return;
}
}
deparseCExpr(state, node);
}
// "AexprConst" in gram.y
static void deparseAexprConst(DeparseState *state, Node *node)
{
switch (nodeTag(node))
{
case T_A_Const:
deparseAConst(state, castNode(A_Const, node));
break;
case T_TypeCast:
deparseTypeCast(state, castNode(TypeCast, node), DEPARSE_NODE_CONTEXT_NONE);
break;
default:
elog(ERROR, "deparse: unpermitted node type in AexprConst: %d",
(int) nodeTag(node));
break;
}
}
// "c_expr" in gram.y
static void deparseCExpr(DeparseState *state, Node *node)
{
switch (nodeTag(node))
{
case T_ColumnRef:
deparseColumnRef(state, castNode(ColumnRef, node));
break;
case T_A_Const:
deparseAConst(state, castNode(A_Const, node));
break;
case T_ParamRef:
deparseParamRef(state, castNode(ParamRef, node));
break;
case T_A_Indirection:
deparseAIndirection(state, castNode(A_Indirection, node));
break;
case T_CaseExpr:
deparseCaseExpr(state, castNode(CaseExpr, node));
break;
case T_SubLink:
deparseSubLink(state, castNode(SubLink, node));
break;
case T_A_ArrayExpr:
deparseAArrayExpr(state, castNode(A_ArrayExpr, node));
break;
case T_RowExpr:
deparseRowExpr(state, castNode(RowExpr, node));
break;
case T_GroupingFunc:
deparseGroupingFunc(state, castNode(GroupingFunc, node));
break;
case T_FuncCall:
case T_SQLValueFunction:
case T_MinMaxExpr:
case T_CoalesceExpr:
case T_XmlExpr:
case T_XmlSerialize:
case T_JsonObjectAgg:
case T_JsonArrayAgg:
case T_JsonObjectConstructor:
case T_JsonArrayConstructor:
case T_JsonArrayQueryConstructor:
deparseFuncExpr(state, node, DEPARSE_NODE_CONTEXT_NONE);
break;
default:
deparseAppendStringInfoChar(state, '(');
// Because we wrap this in parenthesis, the expression inside follows "a_expr" parser rules
deparseExpr(state, node, DEPARSE_NODE_CONTEXT_A_EXPR);
deparseAppendStringInfoChar(state, ')');
break;
}
}
// "expr_list" in gram.y
static void deparseExprList(DeparseState *state, List *exprs)
{
ListCell *lc;