-
Notifications
You must be signed in to change notification settings - Fork 180
/
addColumns.ts
38 lines (30 loc) · 1.38 KB
/
addColumns.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
import type { MigrationOptions } from '../../types';
import { formatLines } from '../../utils';
import type { IfNotExistsOption, Name, Reversible } from '../generalTypes';
import type { DropColumnsOptions } from './dropColumns';
import { dropColumns } from './dropColumns';
import type { ColumnDefinitions } from './shared';
import { parseColumns } from './shared';
export type AddColumnsOptions = IfNotExistsOption;
export type AddColumnsFn = (
tableName: Name,
newColumns: ColumnDefinitions,
addOptions?: AddColumnsOptions & DropColumnsOptions
) => string;
export type AddColumns = Reversible<AddColumnsFn>;
export function addColumns(mOptions: MigrationOptions): AddColumns {
const _add: AddColumns = (tableName, columns, options = {}) => {
const { ifNotExists = false } = options;
const { columns: columnLines, comments: columnComments = [] } =
parseColumns(tableName, columns, mOptions);
const ifNotExistsStr = ifNotExists ? 'IF NOT EXISTS ' : '';
const columnsStr = formatLines(columnLines, ` ADD ${ifNotExistsStr}`);
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;
}