forked from oguimbal/pgsql-ast-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast-mapper.ts
1310 lines (1170 loc) · 40.3 KB
/
ast-mapper.ts
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 * as a from './syntax/ast';
import { nil, NotSupported, trimNullish } from './utils';
export interface IAstPartialMapper {
statement?: (val: a.Statement) => a.Statement | nil;
update?: (val: a.UpdateStatement) => a.Statement | nil
insert?: (val: a.InsertStatement) => a.Statement | nil
delete?: (val: a.DeleteStatement) => a.Statement | nil
comment?: (val: a.CommentStatement) => a.Statement | nil
do?: (val: a.DoStatement) => a.Statement | nil
createFunction?: (val: a.CreateFunctionStatement) => a.Statement | nil
dropFunction?: (val: a.DropFunctionStatement) => a.Statement | nil
raise?: (val: a.RaiseStatement) => a.Statement | nil
createSchema?: (val: a.CreateSchemaStatement) => a.Statement | nil
createEnum?(val: a.CreateEnumType): a.Statement | nil
createCompositeType?(val: a.CreateCompositeType): a.Statement | nil
drop?: (val: a.DropStatement) => a.Statement | nil
show?: (val: a.ShowStatement) => a.Statement | nil
createTable?: (val: a.CreateTableStatement) => a.Statement | nil
truncateTable?: (val: a.TruncateTableStatement) => a.Statement | nil
createExtension?: (val: a.CreateExtensionStatement) => a.Statement | nil
set?: (st: a.SetStatement) => a.SetStatement | nil
dataType?: (dataType: a.DataTypeDef) => a.DataTypeDef
prepare?: (st: a.PrepareStatement) => a.Statement | nil
deallocate?: (st: a.DeallocateStatement) => a.Statement | nil
parameter?: (st: a.ExprParameter) => a.Expr | nil
tableRef?: (st: a.QNameAliased) => a.QNameAliased | nil
transaction?: (val: a.CommitStatement | a.RollbackStatement | a.StartTransactionStatement) => a.Statement | nil
createIndex?: (val: a.CreateIndexStatement) => a.Statement | nil
alterTable?: (st: a.AlterTableStatement) => a.Statement | nil
tableAlteration?: (change: a.TableAlteration, table: a.QNameAliased) => a.TableAlteration | nil
dropColumn?: (change: a.TableAlterationDropColumn, table: a.QNameAliased) => a.TableAlteration | nil
dropConstraint?: (change: a.TableAlterationDropConstraint, table: a.QNameAliased) => a.TableAlteration | nil
renameConstraint?: (change: a.TableAlterationRenameConstraint, table: a.QNameAliased) => a.TableAlteration | nil
setTableOwner?: (change: a.TableAlterationOwner, table: a.QNameAliased) => a.TableAlteration | nil
renameColumn?: (change: a.TableAlterationRenameColumn, table: a.QNameAliased) => a.TableAlteration | nil
renameTable?: (change: a.TableAlterationRename, table: a.QNameAliased) => a.TableAlteration | nil
alterColumn?: (change: a.TableAlterationAlterColumn, inTable: a.QNameAliased) => a.TableAlteration | nil
setColumnType?: (alter: a.AlterColumnSetType, inTable: a.QName, inColumn: a.Name) => a.AlterColumn | nil
alterColumnSimple?: (alter: a.AlterColumnSimple, inTable: a.QName, inColumn: a.Name) => a.AlterColumn | nil
alterColumnAddGenerated?: (alter: a.AlterColumnAddGenerated, inTable: a.QName, inColumn: a.Name) => a.AlterColumn | nil
setColumnDefault?: (alter: a.AlterColumnSetDefault, inTable: a.QName, inColumn: a.Name) => a.AlterColumn | nil
addConstraint?: (change: a.TableAlterationAddConstraint, inTable: a.QName) => a.TableAlteration | nil
addColumn?: (change: a.TableAlterationAddColumn, inTable: a.QName) => a.TableAlteration | nil
createColumn?: (col: a.CreateColumnDef) => a.CreateColumnDef | nil
likeTable?: (col: a.CreateColumnsLikeTable) => a.CreateColumnDef | a.CreateColumnsLikeTable | nil
with?: (val: a.WithStatement) => a.SelectStatement | nil
withRecursive?: (val: a.WithRecursiveStatement) => a.SelectStatement | nil;
union?: (val: a.SelectFromUnion) => a.SelectStatement | nil
select?: (val: a.SelectStatement) => a.SelectStatement | nil
selection?: (val: a.SelectFromStatement) => a.SelectStatement | nil
createView?: (val: a.CreateViewStatement) => a.Statement | nil
createMaterializedView?: (val: a.CreateMaterializedViewStatement) => a.Statement | nil
refreshMaterializedView?: (val: a.RefreshMaterializedViewStatement) => a.Statement | nil
from?: (from: a.From) => a.From | nil
fromCall?: (from: a.FromCall) => a.From | nil
fromStatement?: (from: a.FromStatement) => a.From | nil
values?: (from: a.ValuesStatement) => a.SelectStatement | nil;
fromTable?: (from: a.FromTable) => a.From | nil
selectionColumn?: (val: a.SelectedColumn) => a.SelectedColumn | nil
expr?: (val: a.Expr) => a.Expr | nil
ternary?: (val: a.ExprTernary) => a.Expr | nil
arraySelect?: (val: a.ExprArrayFromSelect) => a.Expr | nil
arrayIndex?: (val: a.ExprArrayIndex) => a.Expr | nil
member?: (val: a.ExprMember) => a.Expr | nil
extract?: (st: a.ExprExtract) => a.Expr | nil
case?: (val: a.ExprCase) => a.Expr | nil
cast?: (val: a.ExprCast) => a.Expr | nil
call?: (val: a.ExprCall) => a.Expr | nil
callSubstring?: (val: a.ExprSubstring) => a.Expr | nil
callOverlay?: (val: a.ExprOverlay) => a.Expr | nil
array?: (val: a.ExprList) => a.Expr | nil
constant?: (value: a.ExprLiteral) => a.Expr | nil
default?: (value: a.ExprDefault) => a.Expr | nil;
ref?: (val: a.ExprRef) => a.Expr | nil
unary?: (val: a.ExprUnary) => a.Expr | nil
binary?: (val: a.ExprBinary) => a.Expr | nil
join?(join: a.JoinClause): a.JoinClause | nil
constraint?: (constraint: a.ColumnConstraint) => a.ColumnConstraint | nil
valueKeyword?(val: a.ExprValueKeyword): a.Expr | nil
tablespace?(val: a.TablespaceStatement): a.Statement | nil
setGlobal?(val: a.SetGlobalStatement): a.Statement | nil
setTimezone?(val: a.SetTimezone): a.Statement | nil
createSequence?(seq: a.CreateSequenceStatement): a.Statement | nil
alterSequence?(seq: a.AlterSequenceStatement): a.Statement | nil
begin?(begin: a.BeginStatement): a.Statement | nil
}
export type IAstFullMapper = {
[key in keyof IAstPartialMapper]-?: IAstPartialMapper[key];
};
export type IAstMapper = IAstFullMapper & {
/** Forces the next call to use the default implementation, not yours */
super(): IAstMapper;
}
/**
* Builds an AST modifier based on the default implementation, merged with the one you provide.
*
* Example of a modifier that renames all reference to columns 'foo' to 'bar'
* ```ts
* const mapper = astMapper(b => ({
* ref: a => assignChanged(a, {
* name: a.name === 'foo'
* ? 'bar'
* : a.name
* })
* }));
*
* const modified = mapper.statement(myStatementToModify);
* ```
*/
export function astMapper(modifierBuilder: MapperBuilder): IAstMapper {
const instance = new AstDefaultMapper();
instance.wrapped = modifierBuilder(instance);
return instance;
}
export type MapperBuilder = (defaultImplem: IAstMapper) => IAstPartialMapper;
type PartialNil<T> = {
[P in keyof T]?: T[P] | nil;
};
/**
* An helper function that returns a copy of an object with modified properties
* (similar to Object.assign()), but ONLY if thos properties have changed.
* Will return the original object if not.
*/
export function assignChanged<T>(orig: T, assign: PartialNil<T>): T {
if (!orig) {
return orig;
}
let changed = false;
for (const k of Object.keys(assign)) {
if ((orig as any)[k] !== (assign as any)[k]) {
changed = true;
break;
}
}
if (!changed) {
return orig;
}
return trimNullish({
...orig,
...assign,
}, 0);
}
/**
* An helper function that returns a map of an array, but:
* - It will return the original array if it is null-ish
* - It will remove all null-ish entries
* - It will return the original array if nothing has changed
*/
export function arrayNilMap<T extends Object>(this: void, collection: T[] | nil, mapper: (v: T) => T | nil): T[] | nil {
if (!collection?.length) {
return collection;
}
let changed = false;
let ret: T[] = collection;
for (let i = 0; i < collection.length; i++) {
const orig = collection[i];
const val = mapper(orig);
if (!val || val !== orig) {
changed = true;
ret = collection.slice(0, i);
}
if (!val) {
continue;
}
if (changed) {
ret.push(val);
}
}
return ret;
}
function withAccepts(val: a.Statement | nil): val is a.WithStatementBinding {
switch (val?.type) {
case 'select':
case 'delete':
case 'insert':
case 'update':
case 'union':
case 'union all':
case 'with':
return true;
default:
return false;
}
}
/**
* Can be used to modify an AST.
*
* You will have to override functions that you're interested in to use this class.
*
* Example: Will remove all references in
*/
export class AstDefaultMapper implements IAstMapper {
wrapped?: IAstPartialMapper;
skipNext?: boolean;
super() {
return new SkipModifier(this);
}
statement(val: a.Statement): a.Statement | nil {
switch (val.type) {
case 'alter table':
return this.alterTable(val);
case 'commit':
case 'start transaction':
case 'rollback':
return this.transaction(val);
case 'create index':
return this.createIndex(val);
case 'create table':
return this.createTable(val);
case 'truncate table':
return this.truncateTable(val);
case 'delete':
return this.delete(val);
case 'insert':
return this.insert(val);
case 'with':
return this.with(val);
case 'with recursive':
return this.withRecursive(val);
case 'select':
return this.selection(val);
case 'update':
return this.update(val);
case 'create extension':
return this.createExtension(val);
case 'tablespace':
return this.tablespace(val);
case 'set':
return this.setGlobal(val);
case 'set timezone':
return this.setTimezone(val);
case 'create sequence':
return this.createSequence(val);
case 'alter sequence':
return this.alterSequence(val);
case 'begin':
return this.begin(val);
case 'drop table':
case 'drop index':
case 'drop sequence':
case 'drop type':
return this.drop(val);
case 'create enum':
return this.createEnum(val);
case 'create composite type':
return this.createCompositeType(val);
case 'union':
case 'union all':
return this.union(val);
case 'show':
return this.show(val);
case 'prepare':
return this.prepare(val);
case 'deallocate':
return this.deallocate(val);
case 'create view':
return this.createView(val);
case 'create materialized view':
return this.createMaterializedView(val);
case 'refresh materialized view':
return this.refreshMaterializedView(val);
case 'create schema':
return this.createSchema(val);
case 'raise':
return this.raise(val);
case 'comment':
return this.comment(val);
case 'do':
return this.do(val);
case 'create function':
return this.createFunction(val);
case 'drop function':
return this.dropFunction(val);
case 'values':
return this.values(val);
default:
throw NotSupported.never(val);
}
}
comment(val: a.CommentStatement): a.Statement | nil {
// not really supported :/
return val;
}
createView(val: a.CreateViewStatement): a.Statement | nil {
const query = this.select(val.query);
if (!query) {
return null;
}
const ref = this.tableRef(val.name);
if (!ref) {
return null;
}
return assignChanged(val, {
query,
name: ref,
});
}
createMaterializedView(val: a.CreateMaterializedViewStatement): a.Statement | nil {
const query = this.select(val.query);
if (!query) {
return null;
}
const ref = this.tableRef(val.name);
if (!ref) {
return null;
}
return assignChanged(val, {
query,
name: ref,
});
}
refreshMaterializedView(val: a.RefreshMaterializedViewStatement): a.Statement | nil {
return val;
}
do(val: a.DoStatement): a.Statement | nil {
return val;
}
createFunction(val: a.CreateFunctionStatement): a.Statement | nil {
// process arguments
const args = arrayNilMap(val.arguments, a => {
const type = this.dataType(a.type);
return assignChanged(a, { type });
});
// process return type
let returns: typeof val.returns;
if (val.returns) {
switch (val.returns.kind) {
case 'table':
returns = assignChanged(val.returns, {
columns: arrayNilMap(val.returns.columns, v => {
const type = this.dataType(v.type);
return type && assignChanged(v, { type })
})
});
break;
case undefined:
case null:
case 'array':
returns = this.dataType(val.returns);
break;
default:
throw NotSupported.never(val.returns);
}
}
return assignChanged(val, {
returns,
arguments: args,
});
}
dropFunction(val: a.DropFunctionStatement): a.Statement | nil {
const args = arrayNilMap(val.arguments, a => {
const type = this.dataType(a.type);
return assignChanged(a, { type });
});
return assignChanged(val, {
arguments: args,
});
}
show(val: a.ShowStatement): a.Statement | nil {
return val;
}
createEnum(val: a.CreateEnumType): a.Statement | nil {
return val;
}
createCompositeType(val: a.CreateCompositeType): a.Statement | nil {
const attributes = arrayNilMap(val.attributes, a => assignChanged(a, {
dataType: this.dataType(a.dataType),
}));
return assignChanged(val, { attributes });
}
drop(val: a.DropStatement): a.Statement | nil {
return val;
}
alterSequence(seq: a.AlterSequenceStatement): a.Statement | nil {
if (seq.change.type === 'set options') {
if (seq.change.as) {
this.dataType(seq.change.as);
}
}
return seq;
}
begin(begin: a.BeginStatement): a.Statement | nil {
return begin;
}
createSequence(seq: a.CreateSequenceStatement): a.Statement | nil {
if (seq.options.as) {
this.dataType(seq.options.as);
}
return seq;
}
tablespace(val: a.TablespaceStatement): a.Statement | nil {
return val;
}
setGlobal(val: a.SetGlobalStatement): a.Statement | nil {
return val;
}
setTimezone(val: a.SetTimezone): a.Statement | nil {
return val;
}
update(val: a.UpdateStatement): a.Statement | nil {
if (!val) {
return val;
}
const table = this.tableRef(val.table);
if (!table) {
return null; // nothing to update
}
const where = val.where && this.expr(val.where);
const sets = arrayNilMap(val.sets, x => this.set(x));
if (!sets?.length) {
return null; // nothing to update
}
const returning = arrayNilMap(val.returning, c => this.selectionColumn(c));
return assignChanged(val, {
table,
where,
sets,
returning,
});
}
insert(val: a.InsertStatement): a.Statement | nil {
const into = this.tableRef(val.into);
if (!into) {
return null; // nowhere to insert into
}
const select = val.insert && this.select(val.insert);
if (!select) {
// nothing to insert
return null;
}
const returning = arrayNilMap(val.returning, c => this.selectionColumn(c));
const onConflictOn = arrayNilMap(val.onConflict?.on, e => this.expr(e));
let ocdo = val.onConflict?.do;
if (ocdo && ocdo !== 'do nothing') {
const sets = arrayNilMap(ocdo.sets, x => this.set(x));
if (!sets?.length) {
ocdo = 'do nothing';
} else if (ocdo.sets !== sets) {
ocdo = { sets };
}
}
return assignChanged(val, {
into,
insert: select,
returning,
onConflict: !ocdo ? val.onConflict : assignChanged(val.onConflict, {
do: ocdo,
on: onConflictOn,
}),
});
}
raise(val: a.RaiseStatement): a.Statement | nil {
return assignChanged(val, {
formatExprs: val.formatExprs && arrayNilMap(val.formatExprs, x => this.expr(x)),
using: val.using && arrayNilMap(val.using, u => {
return assignChanged(u, {
value: this.expr(u.value),
})
}),
});
}
delete(val: a.DeleteStatement): a.Statement | nil {
const from = this.tableRef(val.from);
if (!from) {
return null; // nothing to delete
}
const where = val.where && this.expr(val.where);
const returning = arrayNilMap(val.returning, c => this.selectionColumn(c));
return assignChanged(val, {
where,
returning,
from,
});
}
createSchema(val: a.CreateSchemaStatement): a.Statement | nil {
return val;
}
createTable(val: a.CreateTableStatement): a.Statement | nil {
const columns = arrayNilMap(val.columns, col => {
switch (col.kind) {
case 'column':
return this.createColumn(col);
case 'like table':
return this.likeTable(col);
default:
throw NotSupported.never(col);
}
})
if (!columns?.length) {
return null; // no column to create
}
return assignChanged(val, {
columns,
});
}
likeTable(col: a.CreateColumnsLikeTable): a.CreateColumnDef | a.CreateColumnsLikeTable | nil {
const like = this.tableRef(col.like);
if (!like) {
return null;
}
return assignChanged(col, { like });
}
truncateTable(val: a.TruncateTableStatement): a.Statement | nil {
return val;
}
constraint(c: a.ColumnConstraint): a.ColumnConstraint | nil {
switch (c.type) {
case 'not null':
case 'null':
case 'primary key':
case 'unique':
case 'add generated':
return c;
case 'default': {
const def = this.expr(c.default);
if (!def) {
return null;
}
return assignChanged(c, {
default: def,
});
}
case 'check': {
const def = this.expr(c.expr);
if (!def) {
return null;
}
return assignChanged(c, {
expr: def,
});
}
default:
throw NotSupported.never(c);
}
}
set(st: a.SetStatement): a.SetStatement | nil {
const value = this.expr(st.value);
if (!value) {
return null;
}
return assignChanged(st, {
value,
});
}
// =========================================
// ================ STUFF ==================
// =========================================
/** Called when a data type definition is encountered */
dataType(dataType: a.DataTypeDef): a.DataTypeDef {
return dataType;
}
/** Called when an alias of a table is created */
tableRef(st: a.QNameAliased): a.QNameAliased | nil {
return st;
}
transaction(val: a.CommitStatement | a.RollbackStatement | a.StartTransactionStatement): a.Statement | nil {
return val;
}
createExtension(val: a.CreateExtensionStatement): a.Statement | nil {
return val;
}
createIndex(val: a.CreateIndexStatement): a.Statement | nil {
const expressions = arrayNilMap(val.expressions, e => {
const expression = this.expr(e.expression);
if (expression === e.expression) {
return e;
}
if (!expression) {
return null; // no more index expression
}
return {
...e,
expression,
};
});
if (!expressions?.length) {
return null; // no columns to create index on
}
return assignChanged(val, {
expressions,
});
}
prepare(st: a.PrepareStatement): a.Statement | nil {
const statement = this.statement(st.statement);
if (!statement) {
return null;
}
return assignChanged(st, {
args: arrayNilMap(st.args, a => this.dataType(a)),
statement,
})
}
deallocate(st: a.DeallocateStatement): a.Statement | nil {
return st;
}
// =========================================
// ============== ALTER TABLE ==============
// =========================================
alterTable(st: a.AlterTableStatement): a.Statement | nil {
const table = this.tableRef(st.table);
if (!table) {
return null; // no table
}
let changes: a.TableAlteration[] = [];
let hasChanged: boolean = false;
for (let i = 0; i < (st.changes?.length || 0); i++) {
const currentChange: a.TableAlteration = st.changes[i];
const change: a.TableAlteration | nil = this.tableAlteration(currentChange, st.table);
hasChanged = hasChanged || (change != currentChange);
if (!!change) {
changes.push(change);
}
}
if (!changes.length) {
return null; // no change left
}
if (!hasChanged) {
return st;
}
return assignChanged(st, {
table,
changes,
});
}
tableAlteration(change: a.TableAlteration, table: a.QNameAliased): a.TableAlteration | nil {
switch (change.type) {
case 'add column':
return this.addColumn(change, table);
case 'add constraint':
return this.addConstraint(change, table);
case 'alter column':
return this.alterColumn(change, table);
case 'rename':
return this.renameTable(change, table);
case 'rename column':
return this.renameColumn(change, table);
case 'rename constraint':
return this.renameConstraint(change, table);
case 'drop column':
return this.dropColumn(change, table);
case 'drop constraint':
return this.dropConstraint(change, table);
case 'owner':
return this.setTableOwner(change, table);
default:
throw NotSupported.never(change);
}
}
dropColumn(change: a.TableAlterationDropColumn, table: a.QNameAliased): a.TableAlteration | nil {
return change;
}
dropConstraint(change: a.TableAlterationDropConstraint, table: a.QNameAliased): a.TableAlteration | nil {
return change;
}
setTableOwner(change: a.TableAlterationOwner, table: a.QNameAliased): a.TableAlteration | nil {
return change;
}
renameConstraint(change: a.TableAlterationRenameConstraint, table: a.QNameAliased): a.TableAlteration | nil {
return change;
}
renameColumn(change: a.TableAlterationRenameColumn, table: a.QNameAliased): a.TableAlteration | nil {
return change;
}
renameTable(change: a.TableAlterationRename, table: a.QNameAliased): a.TableAlteration | nil {
return change;
}
alterColumn(change: a.TableAlterationAlterColumn, inTable: a.QNameAliased): a.TableAlteration | nil {
let alter: a.AlterColumn | nil;
switch (change.alter.type) {
case 'set default':
alter = this.setColumnDefault(change.alter, inTable, change.column);
break;
case 'set type':
alter = this.setColumnType(change.alter, inTable, change.column);
break;
case 'drop default':
case 'set not null':
case 'drop not null':
alter = this.alterColumnSimple(change.alter, inTable, change.column);
break;
case 'add generated':
alter = this.alterColumnAddGenerated(change.alter, inTable, change.column);
break;
default:
throw NotSupported.never(change.alter);
}
if (!alter) {
return null; // no more alter
}
return assignChanged(change, {
alter,
});
}
setColumnType(alter: a.AlterColumnSetType, inTable: a.QName, inColumn: a.Name): a.AlterColumn | nil {
const dataType = this.dataType(alter.dataType);
return assignChanged(alter, {
dataType,
});
}
alterColumnAddGenerated(alter: a.AlterColumnAddGenerated, inTable: a.QName, inColumn: a.Name): a.AlterColumn | nil {
return alter;
}
alterColumnSimple(alter: a.AlterColumnSimple, inTable: a.QName, inColumn: a.Name): a.AlterColumn | nil {
return alter;
}
setColumnDefault(alter: a.AlterColumnSetDefault, inTable: a.QName, inColumn: a.Name): a.AlterColumn | nil {
const def = this.expr(alter.default);
if (!def) {
return null; // no more default to set
}
return assignChanged(alter, {
default: def,
});
}
addConstraint(change: a.TableAlterationAddConstraint, inTable: a.QName): a.TableAlteration | nil {
return change;
}
addColumn(change: a.TableAlterationAddColumn, inTable: a.QName): a.TableAlteration | nil {
const column = this.createColumn(change.column);
if (!column) {
return null; // no more column to add
}
return assignChanged(change, {
column,
});
}
createColumn(col: a.CreateColumnDef): a.CreateColumnDef | nil {
// to be overriden
const dataType = this.dataType(col.dataType);
if (!dataType) {
return null; // no data type => remove column
}
const constraints = arrayNilMap(col.constraints, m => this.constraint(m))
?? undefined;
return assignChanged(col, {
dataType,
constraints,
});
}
// =========================================
// ============== SELECTIONS ==============
// =========================================
select(val: a.SelectStatement): a.SelectStatement | nil {
switch (val.type) {
case 'select':
return this.selection(val);
case 'union':
case 'union all':
return this.union(val);
case 'with':
return this.with(val);
case 'values':
return this.values(val);
case 'with recursive':
return this.withRecursive(val);
default:
throw NotSupported.never(val);
}
}
selection(val: a.SelectFromStatement): a.SelectStatement | nil {
const from = arrayNilMap(val.from, c => this.from(c));
const columns = arrayNilMap(val.columns, c => this.selectionColumn(c));
const where = val.where && this.expr(val.where);
const groupBy = arrayNilMap(val.groupBy, c => this.expr(c));
const orderBy = this.orderBy(val.orderBy);
const limit = assignChanged(val.limit, {
limit: this.expr(val.limit?.limit),
offset: this.expr(val.limit?.offset),
});
return assignChanged(val, {
from,
columns,
where,
groupBy,
orderBy,
limit,
});
}
orderBy(orderBy: a.OrderByStatement[] | null | undefined) {
return arrayNilMap(orderBy, c => {
const by = this.expr(c.by);
if (!by) {
return null;
}
if (by === c.by) {
return c;
}
return {
...c,
by,
};
});
}
union(val: a.SelectFromUnion): a.SelectStatement | nil {
const left = this.select(val.left);
const right = this.select(val.right);
if (!left || !right) {
return left ?? right;
}
return assignChanged(val, {
left,
right
})
}
with(val: a.WithStatement): a.SelectStatement | nil {
const bind = arrayNilMap(val.bind, s => {
const statement = this.statement(s.statement);
return withAccepts(statement)
? assignChanged(s, { statement })
: null;
});
// no bindngs
if (!bind) {
return null;
}
const _in = this.statement(val.in);
if (!withAccepts(_in)) {
return null;
}
return assignChanged(val, {
bind,
in: _in,
})
}
withRecursive(val: a.WithRecursiveStatement): a.SelectStatement | nil {
const statement = this.union(val.bind);
if (!statement) {
return null;
}
// 'with recursive' only accepts unions
if (statement.type !== 'union' && statement.type !== 'union all') {
return null;
}
const _in = this.statement(val.in);
if (!withAccepts(_in)) {
return null;
}
return assignChanged(val, {
bind: statement,
in: _in,
});
}
from(from: a.From): a.From | nil {
switch (from.type) {
case 'table':
return this.fromTable(from);
case 'statement':
return this.fromStatement(from);
case 'call':
return this.fromCall(from);
default:
throw NotSupported.never(from);
}
}
fromCall(from: a.FromCall): a.From | nil {
const call = this.call(from);
if (!call || call.type !== 'call') {
return null;
}
return assignChanged(from, call);
}
fromStatement(from: a.FromStatement): a.From | nil {
const statement = this.select(from.statement);
if (!statement) {
return null; // nothing to select from
}
const join = from.join && this.join(from.join);
return assignChanged(from, {
statement,
join,
})
}
values(from: a.ValuesStatement): a.SelectStatement | nil {
const values = arrayNilMap(from.values, x => arrayNilMap(x, y => this.expr(y)));
if (!values?.length) {
return null; // nothing to select from
}
return assignChanged(from, {
values,
});
}
join(join: a.JoinClause): a.JoinClause | nil {
const on = join.on && this.expr(join.on);
if (!on && !join.using) {
return join;
}
return assignChanged(join, {
on,