Repository navigation
Expand file tree
/
Copy pathcolumn.ts
More file actions
107 lines (91 loc) · 2.08 KB
/
Copy pathcolumn.ts
File metadata and controls
107 lines (91 loc) · 2.08 KB
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
106
107
export class Column {
private _nullable: boolean = true;
private _primaryKey: boolean = false;
private _generateUUID: boolean = false;
private _unique: boolean = false;
private _default?: any;
private _references?: {
table: string;
column: string;
onDelete?:
| "CASCADE"
| "SET NULL"
| "NO ACTION"
| "RESTRICT"
| "SET DEFAULT";
};
constructor(
public readonly name: string,
public readonly type: string
) {}
notNull(): this {
this._nullable = false;
return this;
}
primaryKey(): this {
this._primaryKey = true;
this._nullable = false;
return this;
}
unique(): this {
this._unique = true;
return this;
}
default(value: any): this {
this._default = value;
return this;
}
$defaultUUID(): this {
this._generateUUID = true;
return this;
}
$defaultNOW(): this {
this._default = `now()`;
return this;
}
references({
table,
column = "id",
onDelete
}: {
table: string;
column?: string;
onDelete?:
| "CASCADE"
| "SET NULL"
| "NO ACTION"
| "RESTRICT"
| "SET DEFAULT";
}): this {
this._references = { table, column, onDelete };
return this;
}
toString(): string {
let definition = `"${this.name}" ${this.type}`;
if (this._primaryKey) {
definition += " PRIMARY KEY";
}
if (!this._nullable) {
definition += " NOT NULL";
}
if (this._unique) {
definition += " UNIQUE";
}
if (this._default !== undefined) {
if (typeof this._default === "string") {
definition += ` DEFAULT '${this._default}'`;
} else if (this._default === null) {
definition += " DEFAULT NULL";
} else {
definition += ` DEFAULT ${this._default}`;
}
}
if (this._generateUUID) {
definition += " DEFAULT gen_random_uuid()";
}
if (this._references) {
definition += ` REFERENCES ${this._references.table}(${this._references.column}) ON DELETE ${this._references.onDelete ?? "SET NULL"}`;
}
return definition;
}
}