-
Notifications
You must be signed in to change notification settings - Fork 180
/
createFunction.ts
95 lines (79 loc) · 2.39 KB
/
createFunction.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
85
86
87
88
89
90
91
92
93
94
95
import type { MigrationOptions } from '../../types';
import { escapeValue, formatParams } from '../../utils';
import type { DropOptions, Name, Reversible, Value } from '../generalTypes';
import type { DropFunctionOptions } from './dropFunction';
import { dropFunction } from './dropFunction';
import type { FunctionOptions, FunctionParam } from './shared';
export type CreateFunctionOptions = FunctionOptions & DropOptions;
export type CreateFunctionFn = (
functionName: Name,
functionParams: FunctionParam[],
functionOptions: CreateFunctionOptions & DropFunctionOptions,
definition: Value
) => string;
export type CreateFunction = Reversible<CreateFunctionFn>;
export function createFunction(mOptions: MigrationOptions): CreateFunction {
const _create: CreateFunction = (
functionName,
functionParams = [],
functionOptions,
definition
) => {
const {
replace = false,
returns = 'void',
language,
window = false,
behavior = 'VOLATILE',
security = 'INVOKER',
onNull = false,
parallel,
set,
} = functionOptions;
const options: string[] = [];
if (behavior) {
options.push(behavior);
}
if (language) {
options.push(`LANGUAGE ${language}`);
} else {
throw new Error(
`Language for function ${functionName} have to be specified`
);
}
if (security !== 'INVOKER') {
options.push(`SECURITY ${security}`);
}
if (window) {
options.push('WINDOW');
}
if (onNull) {
options.push('RETURNS NULL ON NULL INPUT');
}
if (parallel) {
options.push(`PARALLEL ${parallel}`);
}
if (set) {
for (const { configurationParameter, value } of set) {
if (value === 'FROM CURRENT') {
options.push(
`SET ${mOptions.literal(configurationParameter)} FROM CURRENT`
);
} else {
options.push(
`SET ${mOptions.literal(configurationParameter)} TO ${value}`
);
}
}
}
const replaceStr = replace ? ' OR REPLACE' : '';
const paramsStr = formatParams(functionParams, mOptions);
const functionNameStr = mOptions.literal(functionName);
return `CREATE${replaceStr} FUNCTION ${functionNameStr}${paramsStr}
RETURNS ${returns}
AS ${escapeValue(definition)}
${options.join('\n ')};`;
};
_create.reverse = dropFunction(mOptions);
return _create;
}