-
Notifications
You must be signed in to change notification settings - Fork 180
/
createMaterializedView.ts
60 lines (48 loc) · 1.96 KB
/
createMaterializedView.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
import type { MigrationOptions } from '../../types';
import { toArray } from '../../utils';
import type { IfNotExistsOption, Name, Reversible } from '../generalTypes';
import type { DropMaterializedViewOptions } from './dropMaterializedView';
import { dropMaterializedView } from './dropMaterializedView';
import type { StorageParameters } from './shared';
import { dataClause, storageParameterStr } from './shared';
export interface CreateMaterializedViewOptions extends IfNotExistsOption {
columns?: string | string[];
tablespace?: string;
storageParameters?: StorageParameters;
data?: boolean;
}
export type CreateMaterializedViewFn = (
viewName: Name,
materializedViewOptions: CreateMaterializedViewOptions &
DropMaterializedViewOptions,
definition: string
) => string;
export type CreateMaterializedView = Reversible<CreateMaterializedViewFn>;
export function createMaterializedView(
mOptions: MigrationOptions
): CreateMaterializedView {
const _create: CreateMaterializedView = (viewName, options, definition) => {
const {
ifNotExists = false,
columns = [],
tablespace,
storageParameters = {},
data,
} = options;
const columnNames = toArray(columns).map(mOptions.literal).join(', ');
const withOptions = Object.keys(storageParameters)
.map(storageParameterStr(storageParameters))
.join(', ');
const ifNotExistsStr = ifNotExists ? ' IF NOT EXISTS' : '';
const columnsStr = columnNames ? `(${columnNames})` : '';
const withOptionsStr = withOptions ? ` WITH (${withOptions})` : '';
const tablespaceStr = tablespace
? ` TABLESPACE ${mOptions.literal(tablespace)}`
: '';
const dataStr = dataClause(data);
const viewNameStr = mOptions.literal(viewName);
return `CREATE MATERIALIZED VIEW${ifNotExistsStr} ${viewNameStr}${columnsStr}${withOptionsStr}${tablespaceStr} AS ${definition}${dataStr};`;
};
_create.reverse = dropMaterializedView(mOptions);
return _create;
}