-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathschema.ts
250 lines (224 loc) · 6.52 KB
/
schema.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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import type { Adapter } from "../adapters/adapter.ts";
import { CreateTableOptions, TableBuilder } from "./tablebuilder.ts";
import type { ColumnBuilder } from "./columnbuilder.ts";
/**
* Database schema migration helper
*/
export class Schema {
constructor(
/** The database adapter */
private adapter: Adapter,
) {}
/**
* Create a table
*
* @param name the table name
*/
public async createTable(
name: string,
fn: (builder: TableBuilder) => void,
options?: CreateTableOptions,
) {
const builder = new TableBuilder(name, this.adapter, options);
fn(builder);
await builder.execute();
}
/**
* Rename a table
*
* @param name the previous table name
* @param newName a new name for the table
*/
public async renameTable(name: string, newName: string) {
await this.adapter.query(`ALTER TABLE ${name} RENAME TO ${newName}`);
}
/**
* Drop a single table
*
* @param tableName table to be dropped
* @param options advanced options
*/
public dropTable(
tableName: string,
options?: { ifExists?: boolean },
): Promise<void>;
/**
* Drop multiple tables
*
* @param tableNames tables to be dropped
* @param options advanced options
*/
public dropTable(
tableNames: string[],
options?: { ifExists?: boolean },
): Promise<void>;
/** Drop table from the database */
public async dropTable(
tableName: string | string[],
options?: { ifExists?: boolean },
): Promise<void> {
// Populate options with default values
options = Object.assign({}, { ifExists: false }, options);
// Build query string
const query = [`DROP TABLE`];
if (options.ifExists) query.push(`IF EXISTS`);
if (Array.isArray(tableName)) {
// SQLite doesn't support dropping multiple tables at once.
// So, we need to execute multiple queries for it.
if (this.adapter.dialect === "sqlite") {
for (const table of tableName) {
const tableQuery = query.join(" ") + ` ${table}`;
await this.adapter.query(tableQuery);
}
} else {
// Add the table name
query.push(tableName.join(", "));
// Perform query
await this.adapter.query(query.join(" "));
}
} else {
// Add the table name
query.push(tableName);
// Perform query
await this.adapter.query(query.join(" "));
}
}
/**
* Check if a table exists in the database
*
* @param tableName the table name you want to check
*/
public async hasTable(tableName: string): Promise<boolean> {
let query: string;
// Decide the query
switch (this.adapter.dialect) {
case "sqlite":
query =
`SELECT EXISTS (SELECT name FROM sqlite_master WHERE type='table' AND name='${tableName}')`;
break;
case "postgres":
query =
`SELECT EXISTS (SELECT FROM pg_tables WHERE tablename = '${tableName}')`;
break;
case "mysql":
query =
`SELECT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = '${tableName}' LIMIT 1)`;
break;
default:
return false;
}
// Execute query
const result = await this.adapter.query(query);
// Get the result
switch (this.adapter.dialect) {
case "postgres":
return result[0] && result[0].exists ? true : false;
case "mysql":
case "sqlite":
default:
return !!result[0][Object.keys(result[0])[0]];
}
}
/**
* Check if a column exists in a table
*
* @param tableName the table name you want to check
* @param columnName the column name you're looking for
*/
public async hasColumn(
tableName: string,
columnName: string,
): Promise<boolean> {
let query: string;
// Decide the query
switch (this.adapter.dialect) {
case "sqlite":
query = `PRAGMA table_info(${tableName});`;
break;
case "mysql":
case "postgres":
default:
query =
`SELECT EXISTS (SELECT column_name FROM information_schema.columns WHERE table_name='${tableName}' and column_name='${columnName}');`;
break;
}
// Execute the query
const result = await this.adapter.query(query);
// Extract the result
switch (this.adapter.dialect) {
case "sqlite":
return !!result.find((item) => item.name === columnName);
case "postgres":
return result[0] && result[0].exists ? true : false;
case "mysql":
return !!result[0][Object.keys(result[0])[0]];
default:
throw new Error("Database dialect not implemented!");
}
}
// --------------------------------------------------------------------------------
// ALTER TABLE
// --------------------------------------------------------------------------------
/** Create an index */
public addIndex(index: string) {
throw new Error("Not implemented yet!");
}
/** Remove an index */
public removeIndex(index: string) {
throw new Error("Not implemented yet!");
}
/**
* Rename a column
*
* @param tableName the table name where the column exists
* @param columnName the column you want to rename
* @param newColumnName the new column name
*/
public async renameColumn(
tableName: string,
columnName: string,
newColumnName: string,
) {
await this.adapter.query(
`ALTER TABLE ${tableName} RENAME ${columnName} TO ${newColumnName}`,
);
}
/**
* Create a new column
*
* @param tableName the table name where the column should be added
* @param column the column builder
*/
public async addColumn(tableName: string, column: ColumnBuilder) {
await this.adapter.query(
`ALTER TABLE ${tableName} ADD ${column.toSQL(this.adapter.dialect)}`,
);
}
/** Update a column's datatype */
public alterColumn(column: string, newColumn: string) {
throw new Error("Not implemented yet!");
}
/**
* Remove a column
*
* @param tableName the table name where the column exists
* @param columnName the name of the column you want to remove
*/
public async dropColumn(tableName: string, columnName: string) {
switch (this.adapter.dialect) {
case "sqlite":
throw new Error("SQLite doesn't support DROP COLUMN at the moment!");
case "mysql":
case "postgres":
default:
await this.adapter.query(
`ALTER TABLE ${tableName} DROP COLUMN ${columnName}`,
);
break;
}
}
/** Execute SQL query */
public query(query: string) {
return this.adapter.query(query);
}
}