-
Notifications
You must be signed in to change notification settings - Fork 180
/
createDomain.ts
67 lines (53 loc) · 1.87 KB
/
createDomain.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
import type { MigrationOptions } from '../../types';
import { applyType, escapeValue } from '../../utils';
import type { Name, Reversible, Type } from '../generalTypes';
import type { DropDomainOptions } from './dropDomain';
import { dropDomain } from './dropDomain';
import type { DomainOptions } from './shared';
export interface CreateDomainOptions extends DomainOptions {
collation?: string;
}
export type CreateDomainFn = (
domainName: Name,
type: Type,
domainOptions?: CreateDomainOptions & DropDomainOptions
) => string;
export type CreateDomain = Reversible<CreateDomainFn>;
export function createDomain(mOptions: MigrationOptions): CreateDomain {
const _create: CreateDomain = (domainName, type, options = {}) => {
const {
default: defaultValue,
collation,
notNull = false,
check,
constraintName,
} = options;
const constraints: string[] = [];
if (collation) {
constraints.push(`COLLATE ${collation}`);
}
if (defaultValue !== undefined) {
constraints.push(`DEFAULT ${escapeValue(defaultValue)}`);
}
if (notNull && check) {
throw new Error('"notNull" and "check" can\'t be specified together');
} else if (notNull || check) {
if (constraintName) {
constraints.push(`CONSTRAINT ${mOptions.literal(constraintName)}`);
}
if (notNull) {
constraints.push('NOT NULL');
} else if (check) {
constraints.push(`CHECK (${check})`);
}
}
const constraintsStr =
constraints.length > 0 ? ` ${constraints.join(' ')}` : '';
const typeStr = applyType(type, mOptions.typeShorthands).type;
const domainNameStr = mOptions.literal(domainName);
return `CREATE DOMAIN ${domainNameStr} AS ${typeStr}${constraintsStr};`;
};
_create.reverse = (domainName, type, options) =>
dropDomain(mOptions)(domainName, options);
return _create;
}