-
Notifications
You must be signed in to change notification settings - Fork 168
/
createMaterializedView.ts
64 lines (52 loc) · 1.88 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
61
62
63
64
import type { MigrationOptions } from '../../types';
import type {
DropOptions,
IfNotExistsOption,
Name,
Reversible,
} from '../generalTypes';
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,
options: CreateMaterializedViewOptions & DropOptions,
definition: string
) => string | string[];
export type CreateMaterializedView = Reversible<CreateMaterializedViewFn>;
export function createMaterializedView(
mOptions: MigrationOptions
): CreateMaterializedView {
const _create: CreateMaterializedView = (viewName, options, definition) => {
const {
ifNotExists,
columns = [],
tablespace,
storageParameters = {},
data,
} = options;
const columnNames = (Array.isArray(columns) ? columns : [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;
}