-
Notifications
You must be signed in to change notification settings - Fork 180
/
createView.ts
63 lines (49 loc) · 1.81 KB
/
createView.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
import type { MigrationOptions } from '../../types';
import { toArray } from '../../utils';
import type { Name, Reversible } from '../generalTypes';
import type { DropViewOptions } from './dropView';
import { dropView } from './dropView';
import type { ViewOptions } from './shared';
import { viewOptionStr } from './shared';
export interface CreateViewOptions {
temporary?: boolean;
replace?: boolean;
recursive?: boolean;
columns?: string | string[];
checkOption?: 'CASCADED' | 'LOCAL';
options?: ViewOptions;
}
export type CreateViewFn = (
viewName: Name,
options: CreateViewOptions & DropViewOptions,
definition: string
) => string;
export type CreateView = Reversible<CreateViewFn>;
export function createView(mOptions: MigrationOptions): CreateView {
const _create: CreateView = (viewName, viewOptions, definition) => {
const {
temporary = false,
replace = false,
recursive = false,
columns = [],
options = {},
checkOption,
} = viewOptions;
const columnNames = toArray(columns).map(mOptions.literal).join(', ');
const withOptions = Object.keys(options)
.map(viewOptionStr(options))
.join(', ');
const replaceStr = replace ? ' OR REPLACE' : '';
const temporaryStr = temporary ? ' TEMPORARY' : '';
const recursiveStr = recursive ? ' RECURSIVE' : '';
const columnStr = columnNames ? `(${columnNames})` : '';
const withOptionsStr = withOptions ? ` WITH (${withOptions})` : '';
const checkOptionStr = checkOption
? ` WITH ${checkOption} CHECK OPTION`
: '';
const viewNameStr = mOptions.literal(viewName);
return `CREATE${replaceStr}${temporaryStr}${recursiveStr} VIEW ${viewNameStr}${columnStr}${withOptionsStr} AS ${definition}${checkOptionStr};`;
};
_create.reverse = dropView(mOptions);
return _create;
}