-
Notifications
You must be signed in to change notification settings - Fork 180
/
shared.ts
68 lines (59 loc) · 1.75 KB
/
shared.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
import type { Literal, MigrationOptions } from '../../types';
import type { Name } from '../generalTypes';
import type { CreateIndexOptions } from './createIndex';
import type { DropIndexOptions } from './dropIndex';
export interface IndexColumn {
name: string;
opclass?: Name;
sort?: 'ASC' | 'DESC';
}
export function generateIndexName(
table: Name,
columns: Array<string | IndexColumn>,
options: CreateIndexOptions | DropIndexOptions,
schemalize: Literal
): Name {
if (options.name) {
return typeof table === 'object'
? { schema: table.schema, name: options.name }
: options.name;
}
const cols = columns
.map((col) => schemalize(typeof col === 'string' ? col : col.name))
.join('_');
const uniq = 'unique' in options && options.unique ? '_unique' : '';
return typeof table === 'object'
? {
schema: table.schema,
name: `${table.name}_${cols}${uniq}_index`,
}
: `${table}_${cols}${uniq}_index`;
}
export function generateColumnString(
column: Name,
mOptions: MigrationOptions
): string {
const name = mOptions.schemalize(column);
const isSpecial = /[ ().]/.test(name);
return isSpecial
? name // expression
: mOptions.literal(name); // single column
}
export function generateColumnsString(
columns: Array<string | IndexColumn>,
mOptions: MigrationOptions
): string {
return columns
.map((column) =>
typeof column === 'string'
? generateColumnString(column, mOptions)
: [
generateColumnString(column.name, mOptions),
column.opclass ? mOptions.literal(column.opclass) : undefined,
column.sort,
]
.filter((s) => typeof s === 'string' && s !== '')
.join(' ')
)
.join(', ');
}