-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathdeparser.ts
More file actions
11436 lines (9958 loc) Β· 373 KB
/
deparser.ts
File metadata and controls
11436 lines (9958 loc) Β· 373 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
import { Node } from '@pgsql/types';
import { DeparserContext, DeparserVisitor } from './visitors/base';
import { SqlFormatter } from './utils/sql-formatter';
import { QuoteUtils } from '@pgsql/quotes';
import { ListUtils } from './utils/list-utils';
import * as t from '@pgsql/types';
/**
* List of real PostgreSQL built-in types as they appear in pg_catalog.pg_type.typname.
* These are stored in lowercase in PostgreSQL system catalogs.
* Use these for lookups, validations, or introspection logic.
*/
const pgCatalogTypes = [
// Integers
'int2', // smallint
'int4', // integer
'int8', // bigint
// Floating-point & numeric
'float4', // real
'float8', // double precision
'numeric', // arbitrary precision (aka "decimal")
// Text & string
'varchar', // variable-length string
'char', // internal one-byte type (used in special cases)
'bpchar', // blank-padded char(n)
'text', // unlimited string
'bool', // boolean
// Dates & times
'date', // calendar date
'time', // time without time zone
'timetz', // time with time zone
'timestamp', // timestamp without time zone
'timestamptz', // timestamp with time zone
'interval', // duration
// Binary & structured
'bytea', // binary data
'uuid', // universally unique identifier
// JSON & XML
'json', // textual JSON
'jsonb', // binary JSON
'xml', // XML format
// Money & bitstrings
'money', // currency value
'bit', // fixed-length bit string
'varbit', // variable-length bit string
// Network types
'inet', // IPv4 or IPv6 address
'cidr', // network address
'macaddr', // MAC address (6 bytes)
'macaddr8' // MAC address (8 bytes)
];
/**
* Parser-level type aliases accepted by PostgreSQL SQL syntax,
* but not present in pg_catalog.pg_type. These are resolved to
* real types during parsing and never appear in introspection.
*/
const pgCatalogTypeAliases: [string, string[]][] = [
['numeric', ['decimal', 'dec']],
['int4', ['int', 'integer']],
['float8', ['float']],
['bpchar', ['character']],
['varchar', ['character varying']]
];
export interface DeparserOptions {
newline?: string;
tab?: string;
// Function body delimiter options
functionDelimiter?: string; // Default: '$$'
// Alternative delimiter when the default is found in the body
functionDelimiterFallback?: string; // Default: '$EOFCODE$'
pretty?: boolean; // Default: true
}
// Type guards for better type safety
function isParseResult(obj: any): obj is t.ParseResult {
// A ParseResult is an object that could have stmts (but not required)
// and is not already wrapped as a Node
// IMPORTANT: ParseResult.stmts is "repeated RawStmt" in protobuf, meaning
// the array contains RawStmt objects inline (not wrapped as { RawStmt: ... })
// Example: { version: 170004, stmts: [{ stmt: {...}, stmt_len: 32 }] }
return obj && typeof obj === 'object' &&
!Array.isArray(obj) &&
!('ParseResult' in obj) &&
!('RawStmt' in obj) &&
// Check if it looks like a ParseResult (has stmts or version)
('stmts' in obj || 'version' in obj);
}
function isWrappedParseResult(obj: any): obj is { ParseResult: t.ParseResult } {
return obj && typeof obj === 'object' && 'ParseResult' in obj;
}
/**
* Deparser - Converts PostgreSQL AST nodes back to SQL strings
*
* Entry Points:
* 1. ParseResult (from libpg-query) - The complete parse result
* Structure: { version: number, stmts: RawStmt[] }
* Note: stmts is "repeated RawStmt" in protobuf, so array contains RawStmt
* objects inline (not wrapped as { RawStmt: ... } nodes)
* Example: { version: 170004, stmts: [{ stmt: {...}, stmt_len: 32 }] }
*
* 2. Wrapped ParseResult - When explicitly wrapped as a Node
* Structure: { ParseResult: { version: number, stmts: RawStmt[] } }
*
* 3. Wrapped RawStmt - When explicitly wrapped as a Node
* Structure: { RawStmt: { stmt: Node, stmt_len?: number } }
*
* 4. Array of Nodes - Multiple statements to deparse
* Can be: Node[] (e.g., SelectStmt, InsertStmt, etc.)
*
* 5. Single Node - Individual statement node
* Example: { SelectStmt: {...} }, { InsertStmt: {...} }, etc.
*
* The deparser automatically detects bare ParseResult objects for backward
* compatibility and wraps them internally for consistent processing.
*/
export class Deparser implements DeparserVisitor {
private tree: Node[];
private options: DeparserOptions;
constructor(tree: Node | Node[] | t.ParseResult, opts: DeparserOptions = {}) {
// Set default options
this.options = {
functionDelimiter: '$$',
functionDelimiterFallback: '$EOFCODE$',
...opts
};
// Handle different input types
if (isParseResult(tree)) {
// Duck-typed ParseResult (backward compatibility)
// Wrap it as a proper Node for consistent handling
this.tree = [{ ParseResult: tree } as Node];
} else if (Array.isArray(tree)) {
// Array of Nodes
this.tree = tree;
} else {
// Single Node (including wrapped ParseResult)
this.tree = [tree as Node];
}
}
/**
* Static method to deparse PostgreSQL AST nodes to SQL
* @param query - Can be:
* - ParseResult from libpg-query (e.g., { version: 170004, stmts: [...] })
* - Wrapped ParseResult node (e.g., { ParseResult: {...} })
* - Wrapped RawStmt node (e.g., { RawStmt: {...} })
* - Array of Nodes
* - Single Node (e.g., { SelectStmt: {...} })
* @param opts - Deparser options for formatting
* @returns The deparsed SQL string
*/
static deparse(query: Node | Node[] | t.ParseResult, opts: DeparserOptions = {}): string {
return new Deparser(query, opts).deparseQuery();
}
deparseQuery(): string {
const formatter = new SqlFormatter(this.options.newline, this.options.tab, this.options.pretty);
const context = new DeparserContext({ formatter, prettyMode: this.options.pretty });
return this.tree
.map(node => {
// All nodes should go through the standard deparse method
// which will route to the appropriate handler
const result = this.deparse(node, context);
return result || '';
})
.filter(result => result !== '')
.join(context.newline() + context.newline());
}
/**
* Get the appropriate function delimiter based on the body content
* @param body The function body to check
* @returns The delimiter to use
*/
private getFunctionDelimiter(body: string): string {
const delimiter = this.options.functionDelimiter || '$$';
if (body.includes(delimiter)) {
return this.options.functionDelimiterFallback || '$EOFCODE$';
}
return delimiter;
}
/**
* Maps ObjectType enum values to their corresponding SQL keywords
* Used by AlterOwnerStmt, AlterObjectSchemaStmt, and other statements that need object type keywords
*/
private getObjectTypeKeyword(objectType: string): string {
switch (objectType) {
case 'OBJECT_TABLE':
return 'TABLE';
case 'OBJECT_VIEW':
return 'VIEW';
case 'OBJECT_INDEX':
return 'INDEX';
case 'OBJECT_SEQUENCE':
return 'SEQUENCE';
case 'OBJECT_FUNCTION':
return 'FUNCTION';
case 'OBJECT_PROCEDURE':
return 'PROCEDURE';
case 'OBJECT_SCHEMA':
return 'SCHEMA';
case 'OBJECT_DATABASE':
return 'DATABASE';
case 'OBJECT_DOMAIN':
return 'DOMAIN';
case 'OBJECT_AGGREGATE':
return 'AGGREGATE';
case 'OBJECT_CONVERSION':
return 'CONVERSION';
case 'OBJECT_LANGUAGE':
return 'LANGUAGE';
case 'OBJECT_OPERATOR':
return 'OPERATOR';
case 'OBJECT_OPFAMILY':
return 'OPERATOR FAMILY';
case 'OBJECT_OPCLASS':
return 'OPERATOR CLASS';
case 'OBJECT_TSDICTIONARY':
return 'TEXT SEARCH DICTIONARY';
case 'OBJECT_TSCONFIGURATION':
return 'TEXT SEARCH CONFIGURATION';
case 'OBJECT_EVENT_TRIGGER':
return 'EVENT TRIGGER';
case 'OBJECT_FDW':
return 'FOREIGN DATA WRAPPER';
case 'OBJECT_FOREIGN_SERVER':
return 'SERVER';
case 'OBJECT_TYPE':
return 'TYPE';
case 'OBJECT_COLLATION':
return 'COLLATION';
case 'OBJECT_PUBLICATION':
return 'PUBLICATION';
case 'OBJECT_ACCESS_METHOD':
return 'ACCESS METHOD';
case 'OBJECT_AMOP':
return 'OPERATOR CLASS';
case 'OBJECT_AMPROC':
return 'OPERATOR CLASS';
case 'OBJECT_ATTRIBUTE':
return 'ATTRIBUTE';
case 'OBJECT_CAST':
return 'CAST';
case 'OBJECT_COLUMN':
return 'COLUMN';
case 'OBJECT_DEFAULT':
return 'DEFAULT';
case 'OBJECT_DEFACL':
return 'DEFAULT PRIVILEGES';
case 'OBJECT_DOMCONSTRAINT':
return 'DOMAIN';
case 'OBJECT_EXTENSION':
return 'EXTENSION';
case 'OBJECT_FOREIGN_TABLE':
return 'FOREIGN TABLE';
case 'OBJECT_LARGEOBJECT':
return 'LARGE OBJECT';
case 'OBJECT_MATVIEW':
return 'MATERIALIZED VIEW';
case 'OBJECT_PARAMETER_ACL':
return 'PARAMETER';
case 'OBJECT_POLICY':
return 'POLICY';
case 'OBJECT_PUBLICATION_NAMESPACE':
return 'PUBLICATION';
case 'OBJECT_PUBLICATION_REL':
return 'PUBLICATION';
case 'OBJECT_ROLE':
return 'ROLE';
case 'OBJECT_ROUTINE':
return 'ROUTINE';
case 'OBJECT_RULE':
return 'RULE';
case 'OBJECT_STATISTIC_EXT':
return 'STATISTICS';
case 'OBJECT_SUBSCRIPTION':
return 'SUBSCRIPTION';
case 'OBJECT_TABCONSTRAINT':
return 'CONSTRAINT';
case 'OBJECT_TABLESPACE':
return 'TABLESPACE';
case 'OBJECT_TRANSFORM':
return 'TRANSFORM';
case 'OBJECT_TRIGGER':
return 'TRIGGER';
case 'OBJECT_TSPARSER':
return 'TEXT SEARCH PARSER';
case 'OBJECT_TSTEMPLATE':
return 'TEXT SEARCH TEMPLATE';
case 'OBJECT_USER_MAPPING':
return 'USER MAPPING';
default:
throw new Error(`Unsupported objectType: ${objectType}`);
}
}
deparse(node: Node, context?: DeparserContext): string | null {
if (node == null) {
return null;
}
if (!context) {
const formatter = new SqlFormatter(this.options.newline, this.options.tab, this.options.pretty);
context = new DeparserContext({ formatter, prettyMode: this.options.pretty });
}
if (typeof node === 'number' || node instanceof Number) {
return node.toString();
}
try {
return this.visit(node, context);
} catch (error) {
const nodeType = Object.keys(node)[0];
throw new Error(`Error deparsing ${nodeType}: ${(error as Error).message}`);
}
}
visit(node: Node, context?: DeparserContext): string {
if (!context) {
const formatter = new SqlFormatter(this.options.newline, this.options.tab, this.options.pretty);
context = new DeparserContext({ formatter, prettyMode: this.options.pretty });
}
const nodeType = this.getNodeType(node);
// Handle empty objects
if (!nodeType) {
return '';
}
const nodeData = this.getNodeData(node);
const methodName = nodeType as keyof this;
if (typeof this[methodName] === 'function') {
const result = (this[methodName] as any)(nodeData, context);
return result;
}
throw new Error(`Deparser does not handle node type: ${nodeType}`);
}
getNodeType(node: Node): string {
return Object.keys(node)[0];
}
getNodeData(node: Node): any {
const keys = Object.keys(node);
if (keys.length === 1 && typeof (node as any)[keys[0]] === 'object') {
return (node as any)[keys[0]];
}
return node;
}
ParseResult(node: t.ParseResult, context: DeparserContext): string {
if (!node.stmts || node.stmts.length === 0) {
return '';
}
// Deparse each RawStmt in the ParseResult
// Note: node.stmts is "repeated RawStmt" so contains RawStmt objects inline
// Each element has structure: { stmt: Node, stmt_len?: number, stmt_location?: number }
return node.stmts
.filter((rawStmt: t.RawStmt) => rawStmt != null)
.map((rawStmt: t.RawStmt) => this.RawStmt(rawStmt, context))
.filter((result: string) => result !== '')
.join(context.newline() + context.newline());
}
RawStmt(node: t.RawStmt, context: DeparserContext): string {
if (!node.stmt) {
return '';
}
const deparsedStmt = this.deparse(node.stmt, context);
// Add semicolon if stmt_len is provided (indicates it had one in original)
if (node.stmt_len) {
return deparsedStmt + ';';
}
return deparsedStmt;
}
SelectStmt(node: t.SelectStmt, context: DeparserContext): string {
const output: string[] = [];
if (node.withClause) {
output.push(this.WithClause(node.withClause, context));
}
if (!node.op || node.op === 'SETOP_NONE') {
if (node.valuesLists == null) {
if (!context.isPretty() || !node.targetList) {
output.push('SELECT');
}
}
}else {
const leftStmt = this.SelectStmt(node.larg as t.SelectStmt, context);
const rightStmt = this.SelectStmt(node.rarg as t.SelectStmt, context);
// Add parentheses if the operand is a set operation OR has ORDER BY/LIMIT clauses OR has WITH clause
const leftNeedsParens = node.larg && (
((node.larg as t.SelectStmt).op && (node.larg as t.SelectStmt).op !== 'SETOP_NONE') ||
(node.larg as t.SelectStmt).sortClause ||
(node.larg as t.SelectStmt).limitCount ||
(node.larg as t.SelectStmt).limitOffset ||
(node.larg as t.SelectStmt).withClause
);
const rightNeedsParens = node.rarg && (
((node.rarg as t.SelectStmt).op && (node.rarg as t.SelectStmt).op !== 'SETOP_NONE') ||
(node.rarg as t.SelectStmt).sortClause ||
(node.rarg as t.SelectStmt).limitCount ||
(node.rarg as t.SelectStmt).limitOffset ||
(node.rarg as t.SelectStmt).withClause
);
if (leftNeedsParens) {
output.push(context.parens(leftStmt));
} else {
output.push(leftStmt);
}
switch (node.op) {
case 'SETOP_UNION':
output.push('UNION');
break;
case 'SETOP_INTERSECT':
output.push('INTERSECT');
break;
case 'SETOP_EXCEPT':
output.push('EXCEPT');
break;
default:
throw new Error(`Bad SelectStmt op: ${node.op}`);
}
if (node.all) {
output.push('ALL');
}
if (rightNeedsParens) {
output.push(context.parens(rightStmt));
} else {
output.push(rightStmt);
}
}
// Handle DISTINCT clause - in pretty mode, we'll include it in the SELECT clause
let distinctPart = '';
if (node.distinctClause) {
const distinctClause = ListUtils.unwrapList(node.distinctClause);
if (distinctClause.length > 0 && Object.keys(distinctClause[0]).length > 0) {
const clause = distinctClause
.map(e => this.visit(e as Node, context.spawn('SelectStmt', { select: true })))
.join(', ');
distinctPart = ' DISTINCT ON ' + context.parens(clause);
} else {
distinctPart = ' DISTINCT';
}
if (!context.isPretty()) {
if (distinctClause.length > 0 && Object.keys(distinctClause[0]).length > 0) {
output.push('DISTINCT ON');
const clause = distinctClause
.map(e => this.visit(e as Node, context.spawn('SelectStmt', { select: true })))
.join(', ');
output.push(context.parens(clause));
} else {
output.push('DISTINCT');
}
}
}
if (node.targetList) {
const targetList = ListUtils.unwrapList(node.targetList);
if (context.isPretty()) {
if (targetList.length === 1) {
const targetNode = targetList[0] as Node;
const target = this.visit(targetNode, context.spawn('SelectStmt', { select: true }));
// Check if single target is complex - if so, use multiline format
if (this.isComplexSelectTarget(targetNode)) {
output.push('SELECT' + distinctPart);
if (this.containsMultilineStringLiteral(target)) {
output.push(target);
} else {
output.push(context.indent(target));
}
} else {
output.push('SELECT' + distinctPart + ' ' + target);
}
} else {
const targetStrings = targetList
.map(e => {
const targetStr = this.visit(e as Node, context.spawn('SelectStmt', { select: true }));
if (this.containsMultilineStringLiteral(targetStr)) {
return targetStr;
}
return context.indent(targetStr);
});
const formattedTargets = targetStrings.join(',' + context.newline());
output.push('SELECT' + distinctPart);
output.push(formattedTargets);
}
} else {
const targets = targetList
.map(e => this.visit(e as Node, context.spawn('SelectStmt', { select: true })))
.join(', ');
output.push(targets);
}
}
if (node.intoClause) {
output.push('INTO');
output.push(this.IntoClause(node.intoClause, context));
}
if (node.fromClause) {
const fromList = ListUtils.unwrapList(node.fromClause);
const fromItems = fromList
.map(e => this.deparse(e as Node, context.spawn('SelectStmt', { from: true })))
.join(', ');
output.push('FROM ' + fromItems.trim());
}
if (node.whereClause) {
if (context.isPretty()) {
output.push('WHERE');
const whereExpr = this.visit(node.whereClause as Node, context);
const lines = whereExpr.split(context.newline());
const indentedLines = lines.map((line, index) => {
if (index === 0) {
return context.indent(line);
}
return line;
});
output.push(indentedLines.join(context.newline()));
} else {
output.push('WHERE');
output.push(this.visit(node.whereClause as Node, context));
}
}
if (node.valuesLists) {
if (context.isPretty()) {
output.push('VALUES');
const lists = ListUtils.unwrapList(node.valuesLists).map(list => {
const values = ListUtils.unwrapList(list).map(val => this.visit(val as Node, context));
// Put each value on its own line for pretty printing
const indentedValues = values.map(val => context.indent(val));
return '(\n' + indentedValues.join(',\n') + '\n)';
});
const indentedTuples = lists.map(tuple => {
if (this.containsMultilineStringLiteral(tuple)) {
return tuple;
}
return context.indent(tuple);
});
output.push(indentedTuples.join(',\n'));
} else {
output.push('VALUES');
const lists = ListUtils.unwrapList(node.valuesLists).map(list => {
const values = ListUtils.unwrapList(list).map(val => this.visit(val as Node, context));
return context.parens(values.join(', '));
});
output.push(lists.join(', '));
}
}
if (node.groupClause) {
const groupList = ListUtils.unwrapList(node.groupClause);
if (context.isPretty()) {
const groupItems = groupList
.map(e => {
const groupStr = this.visit(e as Node, context.spawn('SelectStmt', { group: true, indentLevel: context.indentLevel + 1 }));
if (this.containsMultilineStringLiteral(groupStr)) {
return groupStr;
}
return context.indent(groupStr);
})
.join(',' + context.newline());
output.push('GROUP BY');
output.push(groupItems);
} else {
output.push('GROUP BY');
const groupItems = groupList
.map(e => this.visit(e as Node, context.spawn('SelectStmt', { group: true })))
.join(', ');
output.push(groupItems);
}
}
if (node.havingClause) {
if (context.isPretty()) {
output.push('HAVING');
const havingStr = this.visit(node.havingClause as Node, context);
if (this.containsMultilineStringLiteral(havingStr)) {
output.push(havingStr);
} else {
output.push(context.indent(havingStr));
}
} else {
output.push('HAVING');
output.push(this.visit(node.havingClause as Node, context));
}
}
if (node.windowClause) {
output.push('WINDOW');
const windowList = ListUtils.unwrapList(node.windowClause);
const windowClauses = windowList
.map(e => this.visit(e as Node, context))
.join(', ');
output.push(windowClauses);
}
if (node.sortClause) {
const sortList = ListUtils.unwrapList(node.sortClause);
if (context.isPretty()) {
const sortItems = sortList
.map(e => {
const sortStr = this.visit(e as Node, context.spawn('SelectStmt', { sort: true, indentLevel: context.indentLevel + 1 }));
if (this.containsMultilineStringLiteral(sortStr)) {
return sortStr;
}
return context.indent(sortStr);
})
.join(',' + context.newline());
output.push('ORDER BY');
output.push(sortItems);
} else {
output.push('ORDER BY');
const sortItems = sortList
.map(e => this.visit(e as Node, context.spawn('SelectStmt', { sort: true })))
.join(', ');
output.push(sortItems);
}
}
if (node.limitCount) {
output.push('LIMIT ' + this.visit(node.limitCount as Node, context));
}
if (node.limitOffset) {
output.push('OFFSET ' + this.visit(node.limitOffset as Node, context));
}
if (node.lockingClause) {
const lockingList = ListUtils.unwrapList(node.lockingClause);
const lockingClauses = lockingList
.map(e => this.visit(e as Node, context))
.join(' ');
output.push(lockingClauses);
}
if (context.isPretty()) {
const filteredOutput = output.filter(item => item.trim() !== '');
return filteredOutput.join(context.newline());
}
return output.join(' ');
}
A_Expr(node: t.A_Expr, context: DeparserContext): string {
const kind = node.kind as string;
const name = ListUtils.unwrapList(node.name);
const lexpr = node.lexpr;
const rexpr = node.rexpr;
switch (kind) {
case 'AEXPR_OP':
if (lexpr && rexpr) {
const operator = this.deparseOperatorName(name, context);
let leftExpr = this.visit(lexpr, context);
let rightExpr = this.visit(rexpr, context);
// Check if left expression needs parentheses
let leftNeedsParens = false;
if (lexpr && 'A_Expr' in lexpr && lexpr.A_Expr?.kind === 'AEXPR_OP') {
const leftOp = this.deparseOperatorName(ListUtils.unwrapList(lexpr.A_Expr.name), context);
if (this.needsParentheses(leftOp, operator, 'left')) {
leftNeedsParens = true;
}
}
if (lexpr && this.isComplexExpression(lexpr)) {
leftNeedsParens = true;
}
if (leftNeedsParens) {
leftExpr = context.parens(leftExpr);
}
// Check if right expression needs parentheses
let rightNeedsParens = false;
if (rexpr && 'A_Expr' in rexpr && rexpr.A_Expr?.kind === 'AEXPR_OP') {
const rightOp = this.deparseOperatorName(ListUtils.unwrapList(rexpr.A_Expr.name), context);
if (this.needsParentheses(rightOp, operator, 'right')) {
rightNeedsParens = true;
}
}
if (rexpr && this.isComplexExpression(rexpr)) {
rightNeedsParens = true;
}
if (rightNeedsParens) {
rightExpr = context.parens(rightExpr);
}
return context.format([leftExpr, operator, rightExpr]);
}else if (rexpr) {
return context.format([
this.deparseOperatorName(name, context),
this.visit(rexpr, context)
]);
}
break;
case 'AEXPR_OP_ANY':
return context.format([
this.visit(lexpr, context),
this.deparseOperatorName(name, context),
'ANY',
context.parens(this.visit(rexpr, context))
]);
case 'AEXPR_OP_ALL':
return context.format([
this.visit(lexpr, context),
this.deparseOperatorName(name, context),
'ALL',
context.parens(this.visit(rexpr, context))
]);
case 'AEXPR_DISTINCT': {
let leftExpr = this.visit(lexpr, context);
let rightExpr = this.visit(rexpr, context);
// Add parentheses for complex expressions
if (lexpr && this.isComplexExpression(lexpr)) {
leftExpr = context.parens(leftExpr);
}
if (rexpr && this.isComplexExpression(rexpr)) {
rightExpr = context.parens(rightExpr);
}
return context.format([
leftExpr,
'IS DISTINCT FROM',
rightExpr
]);
}
case 'AEXPR_NOT_DISTINCT': {
let leftExpr = this.visit(lexpr, context);
let rightExpr = this.visit(rexpr, context);
// Add parentheses for complex expressions
if (lexpr && this.isComplexExpression(lexpr)) {
leftExpr = context.parens(leftExpr);
}
if (rexpr && this.isComplexExpression(rexpr)) {
rightExpr = context.parens(rightExpr);
}
return context.format([
leftExpr,
'IS NOT DISTINCT FROM',
rightExpr
]);
}
case 'AEXPR_NULLIF':
return context.format([
'NULLIF',
context.parens([
this.visit(lexpr, context),
this.visit(rexpr, context)
].join(', '))
]);
case 'AEXPR_IN':
const inOperator = this.deparseOperatorName(name, context);
if (inOperator === '<>' || inOperator === '!=') {
return context.format([
this.visit(lexpr, context),
'NOT IN',
context.parens(this.visit(rexpr, context))
]);
} else {
return context.format([
this.visit(lexpr, context),
'IN',
context.parens(this.visit(rexpr, context))
]);
}
case 'AEXPR_LIKE':
const likeOp = this.deparseOperatorName(name, context);
if (likeOp === '!~~') {
return context.format([
this.visit(lexpr, context),
'NOT LIKE',
this.visit(rexpr, context)
]);
} else {
return context.format([
this.visit(lexpr, context),
'LIKE',
this.visit(rexpr, context)
]);
}
case 'AEXPR_ILIKE':
const ilikeOp = this.deparseOperatorName(name, context);
if (ilikeOp === '!~~*') {
return context.format([
this.visit(lexpr, context),
'NOT ILIKE',
this.visit(rexpr, context)
]);
} else {
return context.format([
this.visit(lexpr, context),
'ILIKE',
this.visit(rexpr, context)
]);
}
case 'AEXPR_SIMILAR':
const similarOp = this.deparseOperatorName(name, context);
let rightExpr: string;
if (rexpr && 'FuncCall' in rexpr &&
rexpr.FuncCall?.funcname?.length === 2 &&
(rexpr.FuncCall.funcname[0] as any)?.String?.sval === 'pg_catalog' &&
(rexpr.FuncCall.funcname[1] as any)?.String?.sval === 'similar_to_escape') {
const args = rexpr.FuncCall.args || [];
rightExpr = this.visit(args[0], context);
if (args.length > 1) {
rightExpr += ` ESCAPE ${this.visit(args[1], context)}`;
}
} else {
rightExpr = this.visit(rexpr, context);
}
if (similarOp === '!~') {
return context.format([
this.visit(lexpr, context),
'NOT SIMILAR TO',
rightExpr
]);
} else {
return context.format([
this.visit(lexpr, context),
'SIMILAR TO',
rightExpr
]);
}
case 'AEXPR_BETWEEN':
return context.format([
this.visit(lexpr, context),
'BETWEEN',
this.visitBetweenRange(rexpr, context)
]);
case 'AEXPR_NOT_BETWEEN':
return context.format([
this.visit(lexpr, context),
'NOT BETWEEN',
this.visitBetweenRange(rexpr, context)
]);
case 'AEXPR_BETWEEN_SYM':
return context.format([
this.visit(lexpr, context),
'BETWEEN SYMMETRIC',
this.visitBetweenRange(rexpr, context)
]);
case 'AEXPR_NOT_BETWEEN_SYM':
return context.format([
this.visit(lexpr, context),
'NOT BETWEEN SYMMETRIC',
this.visitBetweenRange(rexpr, context)
]);
}
throw new Error(`Unhandled A_Expr kind: ${kind}`);
}
deparseOperatorName(name: t.Node[], context: DeparserContext): string {
if (!name || name.length === 0) {
return '';
}
const parts = name.map((n: any) => {
if (n.String) {
return n.String.sval || n.String.str;
}
return this.visit(n, context);
});
if (parts.length > 1) {
return `OPERATOR(${parts.join('.')})`;
}
return parts.join('.');
}
private getOperatorPrecedence(operator: string): number {
const precedence: { [key: string]: number } = {
'||': 1, // string concatenation
'OR': 2, // logical OR
'AND': 3, // logical AND
'NOT': 4, // logical NOT
'IS': 5, // IS NULL, IS NOT NULL, etc.
'IN': 5, // IN, NOT IN
'BETWEEN': 5, // BETWEEN, NOT BETWEEN
'LIKE': 5, // LIKE, ILIKE, SIMILAR TO
'ILIKE': 5,
'SIMILAR': 5,
'<': 6, // comparison operators
'<=': 6,
'>': 6,
'>=': 6,
'=': 6,
'<>': 6,
'!=': 6,
'+': 7, // addition, subtraction
'-': 7,
'*': 8, // multiplication, division, modulo
'/': 8,
'%': 8,
'^': 9, // exponentiation
'~': 10, // bitwise operators
'&': 10,
'|': 10,
'#': 10,
'<<': 10,
'>>': 10
};
return precedence[operator] || 0;
}
private needsParentheses(childOp: string, parentOp: string, position: 'left' | 'right'): boolean {
const childPrec = this.getOperatorPrecedence(childOp);
const parentPrec = this.getOperatorPrecedence(parentOp);
if (childPrec < parentPrec) {
return true;
}
if (childPrec === parentPrec && position === 'right') {
if (parentOp === '-' || parentOp === '/') {
return true;
}
}
return false;
}
private isComplexExpression(node: any): boolean {
return !!(
node.NullTest ||
node.BooleanTest ||
node.BoolExpr ||
node.CaseExpr ||
node.CoalesceExpr ||
node.SubLink ||
node.A_Expr
);
}
private isComplexSelectTarget(node: any): boolean {
if (!node) return false;
if (node.ResTarget?.val) {
return this.isComplexExpression(node.ResTarget.val);
}
// Always complex: CASE expressions
if (node.CaseExpr) return true;
// Always complex: Subqueries and subselects
if (node.SubLink) return true;
// Always complex: Boolean tests and expressions
if (node.NullTest || node.BooleanTest || node.BoolExpr) return true;
// COALESCE and similar functions - complex if multiple arguments
if (node.CoalesceExpr) {
const args = node.CoalesceExpr.args;
if (args && Array.isArray(args) && args.length > 1) return true;
}
// Function calls - complex if multiple args or has clauses
if (node.FuncCall) {