forked from drizzle-team/drizzle-orm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunique-constraint.ts
64 lines (50 loc) · 1.57 KB
/
unique-constraint.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
import { entityKind } from '~/entity';
import type { AnyMySqlColumn } from './columns';
import { type AnyMySqlTable, MySqlTable } from './table';
export function unique(name?: string): UniqueOnConstraintBuilder {
return new UniqueOnConstraintBuilder(name);
}
export function uniqueKeyName(table: AnyMySqlTable, columns: string[]) {
return `${table[MySqlTable.Symbol.Name]}_${columns.join('_')}_unique`
}
export class UniqueConstraintBuilder {
static readonly [entityKind]: string = 'MySqlUniqueConstraintBuilder';
/** @internal */
columns: AnyMySqlColumn<{}>[];
constructor(
columns: AnyMySqlColumn[],
private name?: string,
) {
this.columns = columns;
}
/** @internal */
build(table: AnyMySqlTable): UniqueConstraint {
return new UniqueConstraint(table, this.columns, this.name);
}
}
export class UniqueOnConstraintBuilder {
static readonly [entityKind]: string = 'MySqlUniqueOnConstraintBuilder';
/** @internal */
name?: string;
constructor(
name?: string,
) {
this.name = name;
}
on(...columns: [AnyMySqlColumn, ...AnyMySqlColumn[]]) {
return new UniqueConstraintBuilder(columns, this.name);
}
}
export class UniqueConstraint {
static readonly [entityKind]: string = 'MySqlUniqueConstraint';
readonly columns: AnyMySqlColumn<{}>[];
readonly name?: string;
readonly nullsNotDistinct: boolean = false;
constructor(readonly table: AnyMySqlTable, columns: AnyMySqlColumn<{}>[], name?: string) {
this.columns = columns;
this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));
}
getName() {
return this.name;
}
}