-
Notifications
You must be signed in to change notification settings - Fork 180
/
createType.ts
37 lines (28 loc) · 1.18 KB
/
createType.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
import type { MigrationOptions } from '../../types';
import { applyType, escapeValue } from '../../utils';
import type { Name, Reversible, Type, Value } from '../generalTypes';
import type { DropTypeOptions } from './dropType';
import { dropType } from './dropType';
export type CreateTypeFn = (
typeName: Name,
values: (Value[] | { [name: string]: Type }) & DropTypeOptions
) => string;
export type CreateType = Reversible<CreateTypeFn>;
export function createType(mOptions: MigrationOptions): CreateType {
const _create: CreateType = (typeName, options) => {
if (Array.isArray(options)) {
const optionsStr = options.map(escapeValue).join(', ');
const typeNameStr = mOptions.literal(typeName);
return `CREATE TYPE ${typeNameStr} AS ENUM (${optionsStr});`;
}
const attributes = Object.entries(options)
.map(([attributeName, attribute]) => {
const typeStr = applyType(attribute, mOptions.typeShorthands).type;
return `${mOptions.literal(attributeName)} ${typeStr}`;
})
.join(',\n');
return `CREATE TYPE ${mOptions.literal(typeName)} AS (\n${attributes}\n);`;
};
_create.reverse = dropType(mOptions);
return _create;
}