-
Notifications
You must be signed in to change notification settings - Fork 180
/
Copy pathtables.ts
693 lines (577 loc) · 18.4 KB
/
tables.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
import type { Literal, MigrationOptions } from '../types';
import {
applyType,
applyTypeAdapters,
escapeValue,
formatLines,
intersection,
makeComment,
} from '../utils';
import type { FunctionParamType } from './functionsTypes';
import type { Name } from './generalTypes';
import { parseSequenceOptions } from './sequences';
import type {
AddColumns,
AlterColumn,
AlterTable,
ColumnDefinition,
ColumnDefinitions,
ConstraintOptions,
CreateConstraint,
CreateTable,
DropColumns,
DropConstraint,
DropTable,
Like,
LikeOptions,
ReferencesOptions,
RenameColumn,
RenameConstraint,
RenameTable,
} from './tablesTypes';
export type {
CreateTable,
DropTable,
AlterTable,
RenameTable,
AddColumns,
DropColumns,
AlterColumn,
RenameColumn,
CreateConstraint,
DropConstraint,
RenameConstraint,
};
const parseReferences = (options: ReferencesOptions, literal: Literal) => {
const { references, match, onDelete, onUpdate } = options;
const clauses: string[] = [];
clauses.push(
typeof references === 'string' &&
(references.startsWith('"') || references.endsWith(')'))
? `REFERENCES ${references}`
: `REFERENCES ${literal(references)}`
);
if (match) {
clauses.push(`MATCH ${match}`);
}
if (onDelete) {
clauses.push(`ON DELETE ${onDelete}`);
}
if (onUpdate) {
clauses.push(`ON UPDATE ${onUpdate}`);
}
return clauses.join(' ');
};
const parseDeferrable = (options: { deferred?: boolean }) =>
`DEFERRABLE INITIALLY ${options.deferred ? 'DEFERRED' : 'IMMEDIATE'}`;
const parseColumns = (
tableName: Name,
columns: ColumnDefinitions,
mOptions: MigrationOptions
): {
columns: string[];
constraints: ConstraintOptions;
comments: string[];
} => {
const extendingTypeShorthands = mOptions.typeShorthands;
let columnsWithOptions = Object.keys(columns).reduce<{
[x: string]: ColumnDefinition & FunctionParamType;
}>(
(previous, column) => ({
...previous,
[column]: applyType(columns[column], extendingTypeShorthands),
}),
{}
);
const primaryColumns = Object.entries(columnsWithOptions)
.filter(([, { primaryKey }]) => Boolean(primaryKey))
.map(([columnName]) => columnName);
const multiplePrimaryColumns = primaryColumns.length > 1;
if (multiplePrimaryColumns) {
columnsWithOptions = Object.entries(columnsWithOptions).reduce(
(previous, [columnName, options]) => ({
...previous,
[columnName]: {
...options,
primaryKey: false,
},
}),
{}
);
}
const comments = Object.entries(columnsWithOptions)
.map(([columnName, { comment }]) => {
return (
typeof comment !== 'undefined' &&
makeComment(
'COLUMN',
`${mOptions.literal(tableName)}.${mOptions.literal(columnName)}`,
comment
)
);
})
.filter((comment): comment is string => Boolean(comment));
return {
columns: Object.entries(columnsWithOptions).map(([columnName, options]) => {
const {
type,
collation,
default: defaultValue,
unique,
primaryKey,
notNull,
check,
references,
referencesConstraintName,
referencesConstraintComment,
deferrable,
expressionGenerated,
}: ColumnDefinition = options;
const sequenceGenerated =
options.sequenceGenerated === undefined
? options.generated
: options.sequenceGenerated;
const constraints: string[] = [];
if (collation) {
constraints.push(`COLLATE ${collation}`);
}
if (defaultValue !== undefined) {
constraints.push(`DEFAULT ${escapeValue(defaultValue)}`);
}
if (unique) {
constraints.push('UNIQUE');
}
if (primaryKey) {
constraints.push('PRIMARY KEY');
}
if (notNull) {
constraints.push('NOT NULL');
}
if (check) {
constraints.push(`CHECK (${check})`);
}
if (references) {
const name =
referencesConstraintName ||
(referencesConstraintComment ? `${tableName}_fk_${columnName}` : '');
const constraintName = name
? `CONSTRAINT ${mOptions.literal(name)} `
: '';
constraints.push(
`${constraintName}${parseReferences(options as ReferencesOptions, mOptions.literal)}`
);
if (referencesConstraintComment) {
comments.push(
makeComment(
`CONSTRAINT ${mOptions.literal(name)} ON`,
mOptions.literal(tableName),
referencesConstraintComment
)
);
}
}
if (deferrable) {
constraints.push(parseDeferrable(options));
}
if (sequenceGenerated) {
const sequenceOptions = parseSequenceOptions(
extendingTypeShorthands,
sequenceGenerated
).join(' ');
constraints.push(
`GENERATED ${sequenceGenerated.precedence} AS IDENTITY${sequenceOptions ? ` (${sequenceOptions})` : ''}`
);
}
if (expressionGenerated) {
constraints.push(`GENERATED ALWAYS AS (${expressionGenerated}) STORED`);
}
const constraintsStr = constraints.length
? ` ${constraints.join(' ')}`
: '';
const sType = typeof type === 'object' ? mOptions.literal(type) : type;
return `${mOptions.literal(columnName)} ${sType}${constraintsStr}`;
}),
constraints: multiplePrimaryColumns ? { primaryKey: primaryColumns } : {},
comments,
};
};
const parseConstraints = (
table: Name,
options: ConstraintOptions,
optionName: string | null,
literal: Literal
) => {
const {
check,
unique,
primaryKey,
foreignKeys,
exclude,
deferrable,
comment,
}: ConstraintOptions = options;
const tableName = typeof table === 'object' ? table.name : table;
let constraints: string[] = [];
const comments: string[] = [];
if (check) {
if (Array.isArray(check)) {
check.forEach((ch, i) => {
const name = literal(optionName || `${tableName}_chck_${i + 1}`);
constraints.push(`CONSTRAINT ${name} CHECK (${ch})`);
});
} else {
const name = literal(optionName || `${tableName}_chck`);
constraints.push(`CONSTRAINT ${name} CHECK (${check})`);
}
}
if (unique) {
const uniqueArray: Array<Name | Name[]> = Array.isArray(unique)
? unique
: [unique];
const isArrayOfArrays = uniqueArray.some((uniqueSet) =>
Array.isArray(uniqueSet)
);
(
(isArrayOfArrays ? uniqueArray : [uniqueArray]) as Array<Name | Name[]>
).forEach((uniqueSet) => {
const cols = Array.isArray(uniqueSet) ? uniqueSet : [uniqueSet];
const name = literal(optionName || `${tableName}_uniq_${cols.join('_')}`);
constraints.push(
`CONSTRAINT ${name} UNIQUE (${cols.map(literal).join(', ')})`
);
});
}
if (primaryKey) {
const name = literal(optionName || `${tableName}_pkey`);
const key = (Array.isArray(primaryKey) ? primaryKey : [primaryKey])
.map(literal)
.join(', ');
constraints.push(`CONSTRAINT ${name} PRIMARY KEY (${key})`);
}
if (foreignKeys) {
(Array.isArray(foreignKeys) ? foreignKeys : [foreignKeys]).forEach((fk) => {
const { columns, referencesConstraintName, referencesConstraintComment } =
fk;
const cols = Array.isArray(columns) ? columns : [columns];
const name = literal(
referencesConstraintName ||
optionName ||
`${tableName}_fk_${cols.join('_')}`
);
const key = cols.map(literal).join(', ');
const referencesStr = parseReferences(fk, literal);
constraints.push(
`CONSTRAINT ${name} FOREIGN KEY (${key}) ${referencesStr}`
);
if (referencesConstraintComment) {
comments.push(
makeComment(
`CONSTRAINT ${name} ON`,
literal(tableName),
referencesConstraintComment
)
);
}
});
}
if (exclude) {
const name = literal(optionName || `${tableName}_excl`);
constraints.push(`CONSTRAINT ${name} EXCLUDE ${exclude}`);
}
if (deferrable) {
constraints = constraints.map(
(constraint) => `${constraint} ${parseDeferrable(options)}`
);
}
if (comment) {
if (!optionName) {
throw new Error('cannot comment on unspecified constraints');
}
comments.push(
makeComment(
`CONSTRAINT ${literal(optionName)} ON`,
literal(tableName),
comment
)
);
}
return {
constraints,
comments,
};
};
const parseLike = (
like: Name | { table: Name; options?: LikeOptions },
literal: Literal
) => {
const formatOptions = (
name: 'INCLUDING' | 'EXCLUDING',
options?: Like | Like[]
) =>
(Array.isArray(options) ? options : [options])
.filter((option): option is Like => option !== undefined)
.map((option) => ` ${name} ${option}`)
.join('');
const table =
typeof like === 'string' || !('table' in like) ? like : like.table;
const options =
typeof like === 'string' ||
!('options' in like) ||
like.options === undefined
? ''
: [
formatOptions('INCLUDING', like.options.including),
formatOptions('EXCLUDING', like.options.excluding),
].join('');
return `LIKE ${literal(table)}${options}`;
};
export function dropTable(mOptions: MigrationOptions): DropTable {
const _drop: DropTable = (tableName, options = {}) => {
const { ifExists, cascade } = options;
const ifExistsStr = ifExists ? ' IF EXISTS' : '';
const cascadeStr = cascade ? ' CASCADE' : '';
const tableNameStr = mOptions.literal(tableName);
return `DROP TABLE${ifExistsStr} ${tableNameStr}${cascadeStr};`;
};
return _drop;
}
export function createTable(mOptions: MigrationOptions): CreateTable {
const _create: CreateTable = (tableName, columns, options = {}) => {
const {
temporary,
ifNotExists,
inherits,
like,
constraints: optionsConstraints = {},
comment,
} = options;
const {
columns: columnLines,
constraints: crossColumnConstraints,
comments: columnComments = [],
} = parseColumns(tableName, columns, mOptions);
const dupes = intersection(
Object.keys(optionsConstraints),
Object.keys(crossColumnConstraints)
);
if (dupes.length > 0) {
const dupesStr = dupes.join(', ');
throw new Error(
`There is duplicate constraint definition in table and columns options: ${dupesStr}`
);
}
const constraints: ConstraintOptions = {
...optionsConstraints,
...crossColumnConstraints,
};
const { constraints: constraintLines, comments: constraintComments } =
parseConstraints(tableName, constraints, '', mOptions.literal);
const tableDefinition = [...columnLines, ...constraintLines].concat(
like ? [parseLike(like, mOptions.literal)] : []
);
const temporaryStr = temporary ? ' TEMPORARY' : '';
const ifNotExistsStr = ifNotExists ? ' IF NOT EXISTS' : '';
const inheritsStr = inherits
? ` INHERITS (${mOptions.literal(inherits)})`
: '';
const tableNameStr = mOptions.literal(tableName);
const createTableQuery = `CREATE${temporaryStr} TABLE${ifNotExistsStr} ${tableNameStr} (
${formatLines(tableDefinition)}
)${inheritsStr};`;
const comments = [...columnComments, ...constraintComments];
if (typeof comment !== 'undefined') {
comments.push(makeComment('TABLE', mOptions.literal(tableName), comment));
}
return `${createTableQuery}${comments.length > 0 ? `\n${comments.join('\n')}` : ''}`;
};
_create.reverse = dropTable(mOptions);
return _create;
}
export function alterTable(mOptions: MigrationOptions): AlterTable {
const _alter: AlterTable = (tableName, options) => {
const alterDefinition: string[] = [];
if (options.levelSecurity) {
alterDefinition.push(`${options.levelSecurity} ROW LEVEL SECURITY`);
}
return `ALTER TABLE ${mOptions.literal(tableName)}
${formatLines(alterDefinition)};`;
};
return _alter;
}
export function dropColumns(mOptions: MigrationOptions): DropColumns {
const _drop: DropColumns = (tableName, columns, options = {}) => {
const { ifExists, cascade } = options;
if (typeof columns === 'string') {
columns = [columns];
} else if (!Array.isArray(columns) && typeof columns === 'object') {
columns = Object.keys(columns);
}
const columnsStr = formatLines(
columns.map(mOptions.literal),
` DROP ${ifExists ? ' IF EXISTS' : ''}`,
`${cascade ? ' CASCADE' : ''},`
);
return `ALTER TABLE ${mOptions.literal(tableName)}
${columnsStr};`;
};
return _drop;
}
export function addColumns(mOptions: MigrationOptions): AddColumns {
const _add: AddColumns = (tableName, columns, options = {}) => {
const { ifNotExists } = options;
const { columns: columnLines, comments: columnComments = [] } =
parseColumns(tableName, columns, mOptions);
const columnsStr = formatLines(
columnLines,
` ADD ${ifNotExists ? 'IF NOT EXISTS ' : ''}`
);
const tableNameStr = mOptions.literal(tableName);
const alterTableQuery = `ALTER TABLE ${tableNameStr}\n${columnsStr};`;
const columnCommentsStr =
columnComments.length > 0 ? `\n${columnComments.join('\n')}` : '';
return `${alterTableQuery}${columnCommentsStr}`;
};
_add.reverse = dropColumns(mOptions);
return _add;
}
export function alterColumn(mOptions: MigrationOptions): AlterColumn {
return (tableName, columnName, options) => {
const {
default: defaultValue,
type,
collation,
using,
notNull,
allowNull,
comment,
} = options;
const sequenceGenerated =
options.sequenceGenerated === undefined
? options.generated
: options.sequenceGenerated;
const actions: string[] = [];
if (defaultValue === null) {
actions.push('DROP DEFAULT');
} else if (defaultValue !== undefined) {
actions.push(`SET DEFAULT ${escapeValue(defaultValue)}`);
}
if (type) {
const typeStr = applyTypeAdapters(type);
const collationStr = collation ? ` COLLATE ${collation}` : '';
const usingStr = using ? ` USING ${using}` : '';
actions.push(`SET DATA TYPE ${typeStr}${collationStr}${usingStr}`);
}
if (notNull) {
actions.push('SET NOT NULL');
} else if (notNull === false || allowNull) {
actions.push('DROP NOT NULL');
}
if (sequenceGenerated !== undefined) {
if (!sequenceGenerated) {
actions.push('DROP IDENTITY');
} else {
const sequenceOptions = parseSequenceOptions(
mOptions.typeShorthands,
sequenceGenerated
).join(' ');
actions.push(
`ADD GENERATED ${sequenceGenerated.precedence} AS IDENTITY${sequenceOptions ? ` (${sequenceOptions})` : ''}`
);
}
}
const queries: string[] = [];
if (actions.length > 0) {
const columnsStr = formatLines(
actions,
` ALTER ${mOptions.literal(columnName)} `
);
queries.push(
`ALTER TABLE ${mOptions.literal(tableName)}\n${columnsStr};`
);
}
if (typeof comment !== 'undefined') {
queries.push(
makeComment(
'COLUMN',
`${mOptions.literal(tableName)}.${mOptions.literal(columnName)}`,
comment
)
);
}
return queries.join('\n');
};
}
export function renameTable(mOptions: MigrationOptions): RenameTable {
const _rename: RenameTable = (tableName, newName) => {
const tableNameStr = mOptions.literal(tableName);
const newNameStr = mOptions.literal(newName);
return `ALTER TABLE ${tableNameStr} RENAME TO ${newNameStr};`;
};
_rename.reverse = (tableName, newName) => _rename(newName, tableName);
return _rename;
}
export function renameColumn(mOptions: MigrationOptions): RenameColumn {
const _rename: RenameColumn = (tableName, columnName, newName) => {
const tableNameStr = mOptions.literal(tableName);
const columnNameStr = mOptions.literal(columnName);
const newNameStr = mOptions.literal(newName);
return `ALTER TABLE ${tableNameStr} RENAME ${columnNameStr} TO ${newNameStr};`;
};
_rename.reverse = (tableName, columnName, newName) =>
_rename(tableName, newName, columnName);
return _rename;
}
export function renameConstraint(mOptions: MigrationOptions): RenameConstraint {
const _rename: RenameConstraint = (tableName, constraintName, newName) => {
const tableNameStr = mOptions.literal(tableName);
const constraintNameStr = mOptions.literal(constraintName);
const newNameStr = mOptions.literal(newName);
return `ALTER TABLE ${tableNameStr} RENAME CONSTRAINT ${constraintNameStr} TO ${newNameStr};`;
};
_rename.reverse = (tableName, constraintName, newName) =>
_rename(tableName, newName, constraintName);
return _rename;
}
export function dropConstraint(mOptions: MigrationOptions): DropConstraint {
const _drop: DropConstraint = (tableName, constraintName, options = {}) => {
const { ifExists, cascade } = options;
const ifExistsStr = ifExists ? ' IF EXISTS' : '';
const cascadeStr = cascade ? ' CASCADE' : '';
const tableNameStr = mOptions.literal(tableName);
const constraintNameStr = mOptions.literal(constraintName);
return `ALTER TABLE ${tableNameStr} DROP CONSTRAINT${ifExistsStr} ${constraintNameStr}${cascadeStr};`;
};
return _drop;
}
export function addConstraint(mOptions: MigrationOptions): CreateConstraint {
const _add: CreateConstraint = (tableName, constraintName, expression) => {
const { constraints, comments } =
typeof expression === 'string'
? {
constraints: [
`${constraintName ? `CONSTRAINT ${mOptions.literal(constraintName)} ` : ''}${expression}`,
],
comments: [],
}
: parseConstraints(
tableName,
expression,
constraintName,
mOptions.literal
);
const constraintStr = formatLines(constraints, ' ADD ');
return [
`ALTER TABLE ${mOptions.literal(tableName)}\n${constraintStr};`,
...comments,
].join('\n');
};
_add.reverse = (tableName, constraintName, options) => {
if (constraintName === null) {
throw new Error(
'Impossible to automatically infer down migration for addConstraint without naming constraint'
);
}
return dropConstraint(mOptions)(tableName, constraintName, options);
};
return _add;
}