-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathplpgsql-deparser.ts
More file actions
2104 lines (1870 loc) Β· 67.7 KB
/
plpgsql-deparser.ts
File metadata and controls
2104 lines (1870 loc) Β· 67.7 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
/**
* PL/pgSQL Deparser
*
* Converts PL/pgSQL function ASTs back to SQL strings.
* This deparser handles the internal PL/pgSQL AST structure returned by
* parsePlPgSQL from libpg-query, which is different from the regular SQL AST.
*
* Note: The PL/pgSQL AST represents the internal structure of function bodies,
* not the CREATE FUNCTION statement itself. To get a complete function definition,
* you would need to combine this with the regular SQL deparser for the outer
* CREATE FUNCTION statement.
*/
import { Deparser as SqlDeparser, QuoteUtils } from 'pgsql-deparser';
import {
PLpgSQLParseResult,
PLpgSQLFunctionNode,
PLpgSQL_function,
PLpgSQLDatum,
PLpgSQL_var,
PLpgSQL_rec,
PLpgSQL_row,
PLpgSQLStmtNode,
PLpgSQL_stmt_block,
PLpgSQL_stmt_assign,
PLpgSQL_stmt_if,
PLpgSQL_stmt_case,
PLpgSQL_stmt_loop,
PLpgSQL_stmt_while,
PLpgSQL_stmt_fori,
PLpgSQL_stmt_fors,
PLpgSQL_stmt_forc,
PLpgSQL_stmt_foreach_a,
PLpgSQL_stmt_exit,
PLpgSQL_stmt_return,
PLpgSQL_stmt_return_next,
PLpgSQL_stmt_return_query,
PLpgSQL_stmt_raise,
PLpgSQL_stmt_assert,
PLpgSQL_stmt_execsql,
PLpgSQL_stmt_dynexecute,
PLpgSQL_stmt_dynfors,
PLpgSQL_stmt_getdiag,
PLpgSQL_stmt_open,
PLpgSQL_stmt_fetch,
PLpgSQL_stmt_close,
PLpgSQL_stmt_perform,
PLpgSQL_stmt_call,
PLpgSQL_stmt_commit,
PLpgSQL_stmt_rollback,
PLpgSQL_stmt_set,
PLpgSQLExprNode,
PLpgSQLTypeNode,
PLpgSQLCaseWhenNode,
PLpgSQLElsifNode,
ElogLevel,
FetchDirection,
DiagItemKind,
RaiseOptionType,
} from './types';
export interface PLpgSQLDeparserOptions {
indent?: string;
newline?: string;
uppercase?: boolean;
}
/**
* Return type information for a PL/pgSQL function.
* Used to determine the correct RETURN statement syntax:
* - void/setof/trigger/out_params: bare RETURN is valid
* - scalar: RETURN NULL is required for empty returns
*/
export type ReturnInfoKind = 'void' | 'setof' | 'trigger' | 'scalar' | 'out_params';
export interface ReturnInfo {
kind: ReturnInfoKind;
}
export interface PLpgSQLDeparserContext {
indentLevel: number;
options: PLpgSQLDeparserOptions;
datums?: PLpgSQLDatum[];
returnInfo?: ReturnInfo;
/** Set of linenos for loop-introduced variables (to exclude from DECLARE) */
loopVarLinenos?: Set<number>;
/** Map of block lineno to the set of datum indices that belong to that block */
blockDatumMap?: Map<number, Set<number>>;
}
/**
* PL/pgSQL Deparser class
*
* Converts PL/pgSQL AST nodes back to SQL strings using a visitor pattern.
*/
export class PLpgSQLDeparser {
private options: PLpgSQLDeparserOptions;
constructor(options: PLpgSQLDeparserOptions = {}) {
this.options = {
indent: ' ',
newline: '\n',
uppercase: true,
...options,
};
}
/**
* Static method to deparse a PL/pgSQL parse result
* @param parseResult - The PL/pgSQL parse result
* @param options - Deparser options
* @param returnInfo - Optional return type info for correct RETURN statement handling
*/
static deparse(parseResult: PLpgSQLParseResult, options?: PLpgSQLDeparserOptions, returnInfo?: ReturnInfo): string {
return new PLpgSQLDeparser(options).deparseResult(parseResult, returnInfo);
}
/**
* Static method to deparse a single PL/pgSQL function body
* @param func - The PL/pgSQL function AST
* @param options - Deparser options
* @param returnInfo - Optional return type info for correct RETURN statement handling
*/
static deparseFunction(func: PLpgSQL_function, options?: PLpgSQLDeparserOptions, returnInfo?: ReturnInfo): string {
return new PLpgSQLDeparser(options).deparseFunction(func, returnInfo);
}
/**
* Deparse a complete PL/pgSQL parse result
* @param parseResult - The PL/pgSQL parse result
* @param returnInfo - Optional return type info for correct RETURN statement handling
*/
deparseResult(parseResult: PLpgSQLParseResult, returnInfo?: ReturnInfo): string {
if (!parseResult.plpgsql_funcs || parseResult.plpgsql_funcs.length === 0) {
return '';
}
return parseResult.plpgsql_funcs
.map(func => this.deparseFunctionNode(func, returnInfo))
.join(this.options.newline + this.options.newline);
}
/**
* Deparse a PLpgSQL_function node wrapper
* @param node - The PLpgSQL_function node wrapper
* @param returnInfo - Optional return type info for correct RETURN statement handling
*/
deparseFunctionNode(node: PLpgSQLFunctionNode, returnInfo?: ReturnInfo): string {
if ('PLpgSQL_function' in node) {
return this.deparseFunction(node.PLpgSQL_function, returnInfo);
}
throw new Error('Unknown function node type');
}
/**
* Deparse a PL/pgSQL function body
* @param func - The PL/pgSQL function AST
* @param returnInfo - Optional return type info for correct RETURN statement handling
*/
deparseFunction(func: PLpgSQL_function, returnInfo?: ReturnInfo): string {
// Collect loop-introduced variables before generating DECLARE section
const loopVarLinenos = new Set<number>();
if (func.action) {
this.collectLoopVariables(func.action, loopVarLinenos);
}
// Build the block-to-datum mapping for nested DECLARE sections
const blockDatumMap = this.buildBlockDatumMap(func.datums, func.action, loopVarLinenos);
// Collect all datum indices that belong to nested blocks (to exclude from top-level)
const nestedDatumIndices = new Set<number>();
for (const indices of blockDatumMap.values()) {
for (const idx of indices) {
nestedDatumIndices.add(idx);
}
}
const context: PLpgSQLDeparserContext = {
indentLevel: 0,
options: this.options,
datums: func.datums,
returnInfo,
loopVarLinenos,
blockDatumMap,
};
const parts: string[] = [];
// Extract label from action block - it should come before DECLARE
// In PL/pgSQL, the syntax is: <<label>> DECLARE ... BEGIN ... END label
let blockLabel: string | undefined;
if (func.action && 'PLpgSQL_stmt_block' in func.action) {
blockLabel = func.action.PLpgSQL_stmt_block.label;
}
// Output label before DECLARE if present
if (blockLabel) {
parts.push(`<<${blockLabel}>>`);
}
// Deparse DECLARE section (local variables, excluding loop variables and nested block variables)
const declareSection = this.deparseDeclareSection(
func.datums,
context,
loopVarLinenos,
undefined, // includedIndices - not used for top-level
nestedDatumIndices // excludedIndices - exclude datums that belong to nested blocks
);
if (declareSection) {
parts.push(declareSection);
}
// Deparse the action block (BEGIN...END)
// Pass skipLabel=true since we already output the label
if (func.action) {
parts.push(this.deparseStmt(func.action, context, blockLabel ? true : false));
}
return parts.join(this.options.newline);
}
/**
* Collect line numbers of variables introduced by loop constructs.
* Only adds a variable's lineno if it matches the loop statement's lineno,
* indicating the variable was implicitly declared by the loop (not explicitly in DECLARE).
*/
private collectLoopVariables(stmt: PLpgSQLStmtNode, loopVarLinenos: Set<number>): void {
if ('PLpgSQL_stmt_block' in stmt) {
const block = stmt.PLpgSQL_stmt_block;
if (block.body) {
for (const s of block.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_fori' in stmt) {
// Integer FOR loop - only exclude if var.lineno matches stmt.lineno (implicit declaration)
const fori = stmt.PLpgSQL_stmt_fori;
const stmtLineno = fori.lineno;
if (fori.var && 'PLpgSQL_var' in fori.var) {
const varLineno = fori.var.PLpgSQL_var.lineno;
if (varLineno !== undefined && varLineno === stmtLineno) {
loopVarLinenos.add(varLineno);
}
}
if (fori.body) {
for (const s of fori.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_fors' in stmt) {
// Query FOR loop - only exclude if var.lineno matches stmt.lineno (implicit declaration)
const fors = stmt.PLpgSQL_stmt_fors;
const stmtLineno = fors.lineno;
if (fors.var && 'PLpgSQL_rec' in fors.var) {
const varLineno = fors.var.PLpgSQL_rec.lineno;
if (varLineno !== undefined && varLineno === stmtLineno) {
loopVarLinenos.add(varLineno);
}
}
if (fors.var && 'PLpgSQL_row' in fors.var) {
const varLineno = fors.var.PLpgSQL_row.lineno;
if (varLineno !== undefined && varLineno === stmtLineno) {
loopVarLinenos.add(varLineno);
}
}
if (fors.body) {
for (const s of fors.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_forc' in stmt) {
// Cursor FOR loop - only exclude if var.lineno matches stmt.lineno (implicit declaration)
const forc = stmt.PLpgSQL_stmt_forc;
const stmtLineno = forc.lineno;
if (forc.var && 'PLpgSQL_rec' in forc.var) {
const varLineno = forc.var.PLpgSQL_rec.lineno;
if (varLineno !== undefined && varLineno === stmtLineno) {
loopVarLinenos.add(varLineno);
}
}
if (forc.body) {
for (const s of forc.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_foreach_a' in stmt) {
// FOREACH loop - uses varno reference, not embedded var
// The variable is referenced by index, so we can't easily exclude it here
// Just recurse into the body
const foreach = stmt.PLpgSQL_stmt_foreach_a;
if (foreach.body) {
for (const s of foreach.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_dynfors' in stmt) {
// Dynamic FOR loop - only exclude if var.lineno matches stmt.lineno (implicit declaration)
const dynfors = stmt.PLpgSQL_stmt_dynfors;
const stmtLineno = dynfors.lineno;
if (dynfors.var && 'PLpgSQL_rec' in dynfors.var) {
const varLineno = dynfors.var.PLpgSQL_rec.lineno;
if (varLineno !== undefined && varLineno === stmtLineno) {
loopVarLinenos.add(varLineno);
}
}
if (dynfors.body) {
for (const s of dynfors.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_if' in stmt) {
const ifStmt = stmt.PLpgSQL_stmt_if;
if (ifStmt.then_body) {
for (const s of ifStmt.then_body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
if (ifStmt.elsif_list) {
for (const elsif of ifStmt.elsif_list) {
if ('PLpgSQL_if_elsif' in elsif && elsif.PLpgSQL_if_elsif.stmts) {
for (const s of elsif.PLpgSQL_if_elsif.stmts) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
}
}
if (ifStmt.else_body) {
for (const s of ifStmt.else_body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_case' in stmt) {
const caseStmt = stmt.PLpgSQL_stmt_case;
if (caseStmt.case_when_list) {
for (const when of caseStmt.case_when_list) {
if ('PLpgSQL_case_when' in when && when.PLpgSQL_case_when.stmts) {
for (const s of when.PLpgSQL_case_when.stmts) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
}
}
if (caseStmt.have_else && caseStmt.else_stmts) {
for (const s of caseStmt.else_stmts) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_loop' in stmt) {
const loop = stmt.PLpgSQL_stmt_loop;
if (loop.body) {
for (const s of loop.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
} else if ('PLpgSQL_stmt_while' in stmt) {
const whileStmt = stmt.PLpgSQL_stmt_while;
if (whileStmt.body) {
for (const s of whileStmt.body) {
this.collectLoopVariables(s, loopVarLinenos);
}
}
}
}
/**
* Build a mapping of block linenos to the datum indices that belong to each block.
* This is used to emit DECLARE sections at the correct nesting level.
*
* The algorithm:
* 1. Get the top-level block's lineno (the BEGIN line of the function body)
* 2. Collect all nested PLpgSQL_stmt_block linenos from the AST
* 3. For each datum with a lineno GREATER than the top-level block's lineno:
* - Assign it to the nested block whose lineno is the smallest value greater than the datum's lineno
* 4. Datums with lineno <= top-level block lineno belong to the top-level DECLARE (not added to map)
*/
private buildBlockDatumMap(
datums: PLpgSQLDatum[] | undefined,
action: PLpgSQLStmtNode | undefined,
loopVarLinenos: Set<number>
): Map<number, Set<number>> {
const blockDatumMap = new Map<number, Set<number>>();
if (!datums || !action) {
return blockDatumMap;
}
// Get the top-level block's lineno
let topLevelBlockLineno: number | undefined;
if ('PLpgSQL_stmt_block' in action) {
topLevelBlockLineno = action.PLpgSQL_stmt_block.lineno;
}
// Collect all nested block linenos (excluding the top-level block)
const nestedBlockLinenos: number[] = [];
this.collectNestedBlockLinenos(action, nestedBlockLinenos, true);
nestedBlockLinenos.sort((a, b) => a - b);
// For each datum, find which block it belongs to
datums.forEach((datum, index) => {
let lineno: number | undefined;
if ('PLpgSQL_var' in datum) {
lineno = datum.PLpgSQL_var.lineno;
} else if ('PLpgSQL_rec' in datum) {
lineno = datum.PLpgSQL_rec.lineno;
} else if ('PLpgSQL_row' in datum) {
lineno = datum.PLpgSQL_row.lineno;
}
// Skip datums without lineno or loop variables
if (lineno === undefined || loopVarLinenos.has(lineno)) {
return;
}
// Only consider datums declared AFTER the top-level BEGIN for nested blocks
// Datums declared before the top-level BEGIN belong to the top-level DECLARE
// If topLevelBlockLineno is undefined, we can't determine scope, so keep all at top-level
if (topLevelBlockLineno === undefined || lineno <= topLevelBlockLineno) {
return; // This datum belongs to top-level DECLARE
}
// Find the block this datum belongs to (the next BEGIN after the datum's lineno)
for (const blockLineno of nestedBlockLinenos) {
if (blockLineno > lineno) {
// This datum belongs to this block
if (!blockDatumMap.has(blockLineno)) {
blockDatumMap.set(blockLineno, new Set());
}
blockDatumMap.get(blockLineno)!.add(index);
return;
}
}
// If no nested block found, datum belongs to top-level (not added to map)
});
return blockDatumMap;
}
/**
* Collect linenos of all nested PLpgSQL_stmt_block nodes in the AST.
* @param isTopLevel - If true, skip the current block (it's the top-level block)
*/
private collectNestedBlockLinenos(
stmt: PLpgSQLStmtNode,
linenos: number[],
isTopLevel: boolean = false
): void {
if ('PLpgSQL_stmt_block' in stmt) {
const block = stmt.PLpgSQL_stmt_block;
// Only add nested blocks, not the top-level block
if (!isTopLevel && block.lineno !== undefined) {
linenos.push(block.lineno);
}
if (block.body) {
for (const s of block.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_fori' in stmt) {
const fori = stmt.PLpgSQL_stmt_fori;
if (fori.body) {
for (const s of fori.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_fors' in stmt) {
const fors = stmt.PLpgSQL_stmt_fors;
if (fors.body) {
for (const s of fors.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_forc' in stmt) {
const forc = stmt.PLpgSQL_stmt_forc;
if (forc.body) {
for (const s of forc.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_foreach_a' in stmt) {
const foreach = stmt.PLpgSQL_stmt_foreach_a;
if (foreach.body) {
for (const s of foreach.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_loop' in stmt) {
const loop = stmt.PLpgSQL_stmt_loop;
if (loop.body) {
for (const s of loop.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_while' in stmt) {
const whileStmt = stmt.PLpgSQL_stmt_while;
if (whileStmt.body) {
for (const s of whileStmt.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_if' in stmt) {
const ifStmt = stmt.PLpgSQL_stmt_if;
if (ifStmt.then_body) {
for (const s of ifStmt.then_body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
if (ifStmt.elsif_list) {
for (const elsif of ifStmt.elsif_list) {
if ('PLpgSQL_if_elsif' in elsif && elsif.PLpgSQL_if_elsif.stmts) {
for (const s of elsif.PLpgSQL_if_elsif.stmts) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
}
}
if (ifStmt.else_body) {
for (const s of ifStmt.else_body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_case' in stmt) {
const caseStmt = stmt.PLpgSQL_stmt_case;
if (caseStmt.case_when_list) {
for (const when of caseStmt.case_when_list) {
if ('PLpgSQL_case_when' in when && when.PLpgSQL_case_when.stmts) {
for (const s of when.PLpgSQL_case_when.stmts) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
}
}
if (caseStmt.have_else && caseStmt.else_stmts) {
for (const s of caseStmt.else_stmts) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
} else if ('PLpgSQL_stmt_dynfors' in stmt) {
const dynfors = stmt.PLpgSQL_stmt_dynfors;
if (dynfors.body) {
for (const s of dynfors.body) {
this.collectNestedBlockLinenos(s, linenos, false);
}
}
}
}
/**
* Deparse the DECLARE section
* @param datums - All datums from the function
* @param context - Deparser context
* @param loopVarLinenos - Set of linenos for loop-introduced variables to exclude
* @param includedIndices - Optional set of datum indices to include (for nested blocks).
* If provided, only datums at these indices are included.
* @param excludedIndices - Optional set of datum indices to exclude (for top-level).
* If provided, datums at these indices are excluded.
*/
private deparseDeclareSection(
datums: PLpgSQLDatum[] | undefined,
context: PLpgSQLDeparserContext,
loopVarLinenos: Set<number> = new Set(),
includedIndices?: Set<number>,
excludedIndices?: Set<number>
): string {
if (!datums || datums.length === 0) {
return '';
}
// Filter out internal variables (like 'found', parameters, etc.) and loop variables
const localVars = datums.filter((datum, index) => {
// If includedIndices is provided, only include datums at those indices
if (includedIndices !== undefined && !includedIndices.has(index)) {
return false;
}
// If excludedIndices is provided, exclude datums at those indices
if (excludedIndices !== undefined && excludedIndices.has(index)) {
return false;
}
if ('PLpgSQL_var' in datum) {
const v = datum.PLpgSQL_var;
// Skip internal variables:
// - 'found' is the implicit FOUND variable
// - 'sqlstate' and 'sqlerrm' are implicit exception handling variables
// - variables starting with '__' are internal
if (v.refname === 'found' || v.refname === 'sqlstate' || v.refname === 'sqlerrm' || v.refname.startsWith('__')) {
return false;
}
// Skip variables without lineno (usually parameters or internal)
if (v.lineno === undefined) {
return false;
}
// Skip loop-introduced variables
if (loopVarLinenos.has(v.lineno)) {
return false;
}
return true;
}
if ('PLpgSQL_rec' in datum) {
const rec = datum.PLpgSQL_rec;
if (rec.lineno === undefined) {
return false;
}
// Skip loop-introduced records
if (loopVarLinenos.has(rec.lineno)) {
return false;
}
return true;
}
return false;
});
if (localVars.length === 0) {
return '';
}
const kw = this.keyword;
const parts: string[] = [kw('DECLARE')];
for (const datum of localVars) {
const varDecl = this.deparseDatum(datum, context);
if (varDecl) {
parts.push(this.indent(varDecl + ';', context.indentLevel + 1));
}
}
return parts.join(this.options.newline);
}
/**
* Deparse a datum (variable declaration)
*/
private deparseDatum(datum: PLpgSQLDatum, context: PLpgSQLDeparserContext): string {
if ('PLpgSQL_var' in datum) {
return this.deparseVar(datum.PLpgSQL_var, context);
}
if ('PLpgSQL_rec' in datum) {
return this.deparseRec(datum.PLpgSQL_rec, context);
}
if ('PLpgSQL_row' in datum) {
return this.deparseRow(datum.PLpgSQL_row, context);
}
return '';
}
/**
* Deparse a variable declaration
*/
private deparseVar(v: PLpgSQL_var, context: PLpgSQLDeparserContext): string {
const kw = this.keyword;
const parts: string[] = [v.refname];
if (v.isconst) {
parts.push(kw('CONSTANT'));
}
// Handle cursor declarations - don't output the type for cursors
// The syntax is: cursor_name CURSOR FOR query
if (v.cursor_explicit_expr) {
parts.push(kw('CURSOR FOR'));
parts.push(this.deparseExpr(v.cursor_explicit_expr));
return parts.join(' ');
}
if (v.datatype) {
parts.push(this.deparseType(v.datatype));
}
if (v.notnull) {
parts.push(kw('NOT NULL'));
}
if (v.default_val) {
parts.push(':=');
parts.push(this.deparseExpr(v.default_val));
}
return parts.join(' ');
}
/**
* Deparse a record declaration
*/
private deparseRec(rec: PLpgSQL_rec, context: PLpgSQLDeparserContext): string {
return `${rec.refname} ${this.keyword('RECORD')}`;
}
/**
* Deparse a row declaration
*/
private deparseRow(row: PLpgSQL_row, context: PLpgSQLDeparserContext): string {
// Row types are usually internal, but we can represent them
return `${row.refname} ${this.keyword('RECORD')}`;
}
/**
* Deparse a type reference
*
* For schema-qualified types (containing a dot), uses QuoteUtils from pgsql-deparser
* for proper identifier quoting. For simple types, preserves the original format
* to maintain round-trip consistency.
*/
private deparseType(typeNode: PLpgSQLTypeNode): string {
if ('PLpgSQL_type' in typeNode) {
let typname = typeNode.PLpgSQL_type.typname;
// Strip pg_catalog. prefix for built-in types, but preserve schema qualification
// for %rowtype and %type references where the schema is part of the table/variable reference
if (!typname.includes('%rowtype') && !typname.includes('%type')) {
typname = typname.replace(/^"?pg_catalog"?\./, '');
}
// For %rowtype and %type references, preserve as-is after stripping quotes
// These are special PL/pgSQL type references that shouldn't be re-quoted
if (typname.includes('%rowtype') || typname.includes('%type')) {
// Strip quotes and return as-is
return typname.replace(/"/g, '').trim();
}
// Check if this is a schema-qualified type (contains a dot outside of quotes)
// Only apply QuoteUtils for schema-qualified types to ensure consistent quoting
// For simple types, preserve the original format for round-trip consistency
const isSchemaQualified = this.isSchemaQualifiedType(typname);
if (!isSchemaQualified) {
// Simple type - just strip quotes and return as-is
return typname.replace(/"/g, '').trim();
}
// Schema-qualified type - apply proper quoting
const trimmedTypname = typname.trim();
// Handle array types - extract the array suffix (e.g., [], [3], [][])
// Array notation should not be quoted, only the base type
const arrayMatch = trimmedTypname.match(/(\[[\d]*\])+$/);
const arraySuffix = arrayMatch ? arrayMatch[0] : '';
const baseTypeName = arraySuffix ? trimmedTypname.slice(0, -arraySuffix.length) : trimmedTypname;
// Parse the base type name into parts, handling quoted identifiers
// Type names can be: "schema"."type", schema.type, or just type
const parts = this.parseQualifiedTypeName(baseTypeName);
// Use QuoteUtils to properly quote the type name parts
const quotedType = QuoteUtils.quoteTypeDottedName(parts);
// Re-add the array suffix (unquoted)
return quotedType + arraySuffix;
}
return '';
}
/**
* Check if a type name is schema-qualified (contains a dot outside of quotes).
*/
private isSchemaQualifiedType(typname: string): boolean {
let inQuotes = false;
for (let i = 0; i < typname.length; i++) {
const ch = typname[i];
if (ch === '"') {
if (inQuotes && typname[i + 1] === '"') {
i++; // Skip escaped quote
} else {
inQuotes = !inQuotes;
}
} else if (ch === '.' && !inQuotes) {
return true;
}
}
return false;
}
/**
* Parse a qualified type name into its component parts.
* Handles both quoted ("schema"."type") and unquoted (schema.type) identifiers.
*
* @param typname - The type name string, possibly with quotes and dots
* @returns Array of unquoted identifier parts
*/
private parseQualifiedTypeName(typname: string): string[] {
const parts: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < typname.length; i++) {
const ch = typname[i];
if (ch === '"') {
if (inQuotes && typname[i + 1] === '"') {
// Escaped quote ("") inside quoted identifier
current += '"';
i++; // Skip the next quote
} else {
// Toggle quote state
inQuotes = !inQuotes;
}
} else if (ch === '.' && !inQuotes) {
// Dot outside quotes - separator
if (current) {
parts.push(current.trim());
current = '';
}
} else {
current += ch;
}
}
// Add the last part
if (current) {
parts.push(current.trim());
}
return parts;
}
/**
* Deparse an expression
*/
private deparseExpr(exprNode: PLpgSQLExprNode): string {
if ('PLpgSQL_expr' in exprNode) {
return exprNode.PLpgSQL_expr.query;
}
return '';
}
/**
* Deparse a statement node
* @param skipLabel - If true, skip outputting the label (used when label is output before DECLARE)
*/
private deparseStmt(stmt: PLpgSQLStmtNode, context: PLpgSQLDeparserContext, skipLabel?: boolean): string {
const nodeType = Object.keys(stmt)[0];
const nodeData = (stmt as any)[nodeType];
switch (nodeType) {
case 'PLpgSQL_stmt_block':
return this.deparseBlock(nodeData, context, skipLabel);
case 'PLpgSQL_stmt_assign':
return this.deparseAssign(nodeData, context);
case 'PLpgSQL_stmt_if':
return this.deparseIf(nodeData, context);
case 'PLpgSQL_stmt_case':
return this.deparseCase(nodeData, context);
case 'PLpgSQL_stmt_loop':
return this.deparseLoop(nodeData, context);
case 'PLpgSQL_stmt_while':
return this.deparseWhile(nodeData, context);
case 'PLpgSQL_stmt_fori':
return this.deparseFori(nodeData, context);
case 'PLpgSQL_stmt_fors':
return this.deparseFors(nodeData, context);
case 'PLpgSQL_stmt_forc':
return this.deparseForc(nodeData, context);
case 'PLpgSQL_stmt_foreach_a':
return this.deparseForeach(nodeData, context);
case 'PLpgSQL_stmt_exit':
return this.deparseExit(nodeData, context);
case 'PLpgSQL_stmt_return':
return this.deparseReturn(nodeData, context);
case 'PLpgSQL_stmt_return_next':
return this.deparseReturnNext(nodeData, context);
case 'PLpgSQL_stmt_return_query':
return this.deparseReturnQuery(nodeData, context);
case 'PLpgSQL_stmt_raise':
return this.deparseRaise(nodeData, context);
case 'PLpgSQL_stmt_assert':
return this.deparseAssert(nodeData, context);
case 'PLpgSQL_stmt_execsql':
return this.deparseExecSql(nodeData, context);
case 'PLpgSQL_stmt_dynexecute':
return this.deparseDynExecute(nodeData, context);
case 'PLpgSQL_stmt_dynfors':
return this.deparseDynFors(nodeData, context);
case 'PLpgSQL_stmt_getdiag':
return this.deparseGetDiag(nodeData, context);
case 'PLpgSQL_stmt_open':
return this.deparseOpen(nodeData, context);
case 'PLpgSQL_stmt_fetch':
return this.deparseFetch(nodeData, context);
case 'PLpgSQL_stmt_close':
return this.deparseClose(nodeData, context);
case 'PLpgSQL_stmt_perform':
return this.deparsePerform(nodeData, context);
case 'PLpgSQL_stmt_call':
return this.deparseCall(nodeData, context);
case 'PLpgSQL_stmt_commit':
return this.deparseCommit(nodeData, context);
case 'PLpgSQL_stmt_rollback':
return this.deparseRollback(nodeData, context);
case 'PLpgSQL_stmt_set':
return this.deparseSet(nodeData, context);
default:
throw new Error(`Unknown PL/pgSQL statement type: ${nodeType}`);
}
}
/**
* Deparse a block statement (BEGIN...END)
* @param skipLabel - If true, skip outputting the label (used when label is output before DECLARE)
*/
private deparseBlock(block: PLpgSQL_stmt_block, context: PLpgSQLDeparserContext, skipLabel?: boolean): string {
const kw = this.keyword;
const parts: string[] = [];
// Label - skip if already output before DECLARE
if (block.label && !skipLabel) {
parts.push(`<<${block.label}>>`);
}
// Check if this block has any datums assigned to it (nested DECLARE)
if (block.lineno !== undefined && context.blockDatumMap?.has(block.lineno)) {
const includedIndices = context.blockDatumMap.get(block.lineno)!;
const declareSection = this.deparseDeclareSection(
context.datums,
context,
context.loopVarLinenos || new Set(),
includedIndices
);
if (declareSection) {
parts.push(declareSection);
}
}
parts.push(kw('BEGIN'));
// Body statements
if (block.body) {
const bodyContext = { ...context, indentLevel: context.indentLevel + 1 };
for (const stmt of block.body) {
const stmtStr = this.deparseStmt(stmt, bodyContext);
parts.push(this.indent(stmtStr + ';', bodyContext.indentLevel));
}
}
// Exception handlers
// The exceptions property can be either:
// - { exc_list: [...] } (direct)
// - { PLpgSQL_exception_block: { exc_list: [...] } } (wrapped)
const excList = block.exceptions?.exc_list ||
(block.exceptions as any)?.PLpgSQL_exception_block?.exc_list;
if (excList) {
parts.push(kw('EXCEPTION'));
for (const exc of excList) {
if ('PLpgSQL_exception' in exc) {
const excData = exc.PLpgSQL_exception;
const conditions = excData.conditions?.map((c: any) => {
if ('PLpgSQL_condition' in c) {
return c.PLpgSQL_condition.condname || c.PLpgSQL_condition.sqlerrstate || 'OTHERS';
}
return 'OTHERS';
}).join(' OR ') || 'OTHERS';
parts.push(this.indent(`${kw('WHEN')} ${conditions} ${kw('THEN')}`, context.indentLevel + 1));
if (excData.action) {
const excContext = { ...context, indentLevel: context.indentLevel + 2 };
for (const stmt of excData.action) {
const stmtStr = this.deparseStmt(stmt, excContext);
parts.push(this.indent(stmtStr + ';', excContext.indentLevel));
}
}
}
}
}
parts.push(kw('END'));
if (block.label) {
parts[parts.length - 1] += ` ${block.label}`;
}
return parts.join(this.options.newline);
}
/**
* Deparse an assignment statement
*/
private deparseAssign(assign: PLpgSQL_stmt_assign, context: PLpgSQLDeparserContext): string {
const varName = this.getVarName(assign.varno, context);
const expr = assign.expr ? this.deparseExpr(assign.expr) : '';
// The expression already contains the assignment in the query
// e.g., "sum := sum + n"
if (expr.includes(':=')) {
return expr;
}
return `${varName} := ${expr}`;
}
/**
* Deparse an IF statement
*/
private deparseIf(ifStmt: PLpgSQL_stmt_if, context: PLpgSQLDeparserContext): string {
const kw = this.keyword;
const parts: string[] = [];
// IF condition THEN
const cond = ifStmt.cond ? this.deparseExpr(ifStmt.cond) : 'TRUE';
parts.push(`${kw('IF')} ${cond} ${kw('THEN')}`);
// THEN body
if (ifStmt.then_body) {