-
Notifications
You must be signed in to change notification settings - Fork 167
/
functions.ts
105 lines (85 loc) · 2.64 KB
/
functions.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
96
97
98
99
100
101
102
103
104
105
import type { MigrationOptions } from '../types';
import { escapeValue, formatParams } from '../utils';
import type {
CreateFunction,
DropFunction,
RenameFunction,
} from './functionsTypes';
export type { CreateFunction, DropFunction, RenameFunction };
export function dropFunction(mOptions: MigrationOptions): DropFunction {
const _drop: DropFunction = (
functionName,
functionParams = [],
options = {}
) => {
const { ifExists, cascade } = options;
const ifExistsStr = ifExists ? ' IF EXISTS' : '';
const cascadeStr = cascade ? ' CASCADE' : '';
const paramsStr = formatParams(functionParams, mOptions);
const functionNameStr = mOptions.literal(functionName);
return `DROP FUNCTION${ifExistsStr} ${functionNameStr}${paramsStr}${cascadeStr};`;
};
return _drop;
}
export function createFunction(mOptions: MigrationOptions): CreateFunction {
const _create: CreateFunction = (
functionName,
functionParams = [],
functionOptions,
definition
) => {
const {
replace,
returns = 'void',
language,
window,
behavior = 'VOLATILE',
onNull,
parallel,
} = 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 (window) {
options.push('WINDOW');
}
if (onNull) {
options.push('RETURNS NULL ON NULL INPUT');
}
if (parallel) {
options.push(`PARALLEL ${parallel}`);
}
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;
}
export function renameFunction(mOptions: MigrationOptions): RenameFunction {
const _rename: RenameFunction = (
oldFunctionName,
functionParams = [],
newFunctionName
) => {
const paramsStr = formatParams(functionParams, mOptions);
const oldFunctionNameStr = mOptions.literal(oldFunctionName);
const newFunctionNameStr = mOptions.literal(newFunctionName);
return `ALTER FUNCTION ${oldFunctionNameStr}${paramsStr} RENAME TO ${newFunctionNameStr};`;
};
_rename.reverse = (oldFunctionName, functionParams, newFunctionName) =>
_rename(newFunctionName, functionParams, oldFunctionName);
return _rename;
}