-
Notifications
You must be signed in to change notification settings - Fork 180
/
createTable.ts
84 lines (71 loc) · 2.54 KB
/
createTable.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
import type { MigrationOptions } from '../../types';
import { formatLines, intersection, makeComment } from '../../utils';
import type { Name, Reversible } from '../generalTypes';
import type { DropTableOptions } from './dropTable';
import { dropTable } from './dropTable';
import type {
ColumnDefinitions,
ConstraintOptions,
TableOptions,
} from './shared';
import { parseColumns, parseConstraints, parseLike } from './shared';
export type CreateTableFn = (
tableName: Name,
columns: ColumnDefinitions,
options?: TableOptions & DropTableOptions
) => string;
export type CreateTable = Reversible<CreateTableFn>;
export function createTable(mOptions: MigrationOptions): CreateTable {
const _create: CreateTable = (tableName, columns, options = {}) => {
const {
temporary = false,
ifNotExists = false,
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,
...(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 (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;
}