sqlmorpheus 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/index.cjs +1861 -0
- package/dist/index.d.cts +450 -0
- package/dist/index.d.mts +364 -294
- package/dist/index.mjs +1767 -1638
- package/package.json +25 -15
- package/dist/index.d.ts +0 -380
- package/dist/index.js +0 -1744
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1861 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region \0rolldown/runtime.js
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
//#endregion
|
|
24
|
+
let escape_sql_string = require("escape-sql-string");
|
|
25
|
+
escape_sql_string = __toESM(escape_sql_string, 1);
|
|
26
|
+
require("polyfill-symbol-metadata");
|
|
27
|
+
//#region src/lib/Logger.ts
|
|
28
|
+
/**
|
|
29
|
+
* A simple LoggerClass which provides functionality for logging messages
|
|
30
|
+
* in different modes such as normal, debug, silent, and noLog.
|
|
31
|
+
* It allows controlling the verbosity of logs based on the mode.
|
|
32
|
+
*/
|
|
33
|
+
var LoggerClass = class {
|
|
34
|
+
mode = "log";
|
|
35
|
+
setMode(mode) {
|
|
36
|
+
this.mode = mode ?? "log";
|
|
37
|
+
}
|
|
38
|
+
debug(text) {
|
|
39
|
+
if (this.mode == "debug") console.debug(`\x1b[90m${(/* @__PURE__ */ new Date()).toLocaleTimeString()}\x1b[0m ${text}`);
|
|
40
|
+
}
|
|
41
|
+
log(text) {
|
|
42
|
+
if (this.mode == "log" || this.mode == "debug") console.log(`\x1b[90m${(/* @__PURE__ */ new Date()).toLocaleTimeString()}\x1b[0m ${text}`);
|
|
43
|
+
}
|
|
44
|
+
warn(text) {
|
|
45
|
+
if (this.mode == "warn" || this.mode == "log" || this.mode == "debug") console.warn(`\x1b[90m${(/* @__PURE__ */ new Date()).toLocaleTimeString()}\x1b[0m ${text}`);
|
|
46
|
+
}
|
|
47
|
+
error(text) {
|
|
48
|
+
if (this.mode == "error" || this.mode == "warn" || this.mode == "log" || this.mode == "debug") console.error(`\x1b[90m${(/* @__PURE__ */ new Date()).toLocaleTimeString()}\x1b[0m ${text}`);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const Logger = new LoggerClass();
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/lib/tableInfo/TableObjHelper.ts
|
|
54
|
+
var TableObjHelper = class TableObjHelper {
|
|
55
|
+
static isTableObj(obj) {
|
|
56
|
+
return !!obj?.IS_TABLE_OBJ;
|
|
57
|
+
}
|
|
58
|
+
static getEmptyColumnEntry(key) {
|
|
59
|
+
return {
|
|
60
|
+
name: key,
|
|
61
|
+
sqlType: "",
|
|
62
|
+
defaultValue: "",
|
|
63
|
+
isPrimaryKey: false
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
static getColumnEntry(key, value) {
|
|
67
|
+
let dataType = typeof value;
|
|
68
|
+
switch (typeof value) {
|
|
69
|
+
case "function": return null;
|
|
70
|
+
case "object":
|
|
71
|
+
if (value instanceof Date) {
|
|
72
|
+
dataType = "date";
|
|
73
|
+
break;
|
|
74
|
+
} else if (value !== null) {
|
|
75
|
+
Logger.warn(`${key} was skipped because its type (${typeof value}) is not supported`);
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
dataType = "string";
|
|
79
|
+
break;
|
|
80
|
+
case "undefined":
|
|
81
|
+
case "symbol":
|
|
82
|
+
Logger.warn(`${key} was skipped because its type (${typeof value}) is not supported`);
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
...TableObjHelper.getEmptyColumnEntry(key),
|
|
87
|
+
inputType: dataType,
|
|
88
|
+
inputDefaultValue: value
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/lib/tableInfo/getTableStructure.ts
|
|
94
|
+
const TABLE_INFO_PROPERTY_NAME = Symbol("tableInfo");
|
|
95
|
+
function getInputColumnInfo(table, context) {
|
|
96
|
+
const metadata = context?.metadata ? getTableStructureFromMetadata(context.metadata) : getTableStructure(table);
|
|
97
|
+
const key = context.name ?? context;
|
|
98
|
+
if (!metadata.columns.hasOwnProperty(key)) metadata.columns[key] = TableObjHelper.getEmptyColumnEntry(key);
|
|
99
|
+
return metadata.columns[key];
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Retrieves table information based on the provided class and their decorators.
|
|
103
|
+
* If the table metadata property does not exist in the metadata,
|
|
104
|
+
* it initializes a default structure.
|
|
105
|
+
*
|
|
106
|
+
* @param table - The class representing the table.
|
|
107
|
+
* @return The table information as a `TableInfo` object.
|
|
108
|
+
*/
|
|
109
|
+
function getTableStructure(table) {
|
|
110
|
+
let metadata = table[Symbol.metadata] ?? table.prototype?.[Symbol.metadata];
|
|
111
|
+
if (!metadata) {
|
|
112
|
+
metadata = {};
|
|
113
|
+
table[Symbol.metadata] = metadata;
|
|
114
|
+
}
|
|
115
|
+
return getTableStructureFromMetadata(metadata);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Extracts and returns table information from the provided metadata object.
|
|
119
|
+
* If the specified table information property does not exist in the metadata,
|
|
120
|
+
* it initializes a default structure.
|
|
121
|
+
*
|
|
122
|
+
* @param metadata - The metadata object which potentially contains table information.
|
|
123
|
+
* @return {InputTableStructure} The table information retrieved or initialized from the metadata.
|
|
124
|
+
*/
|
|
125
|
+
function getTableStructureFromMetadata(metadata) {
|
|
126
|
+
if (!metadata[TABLE_INFO_PROPERTY_NAME]) metadata[TABLE_INFO_PROPERTY_NAME] = {
|
|
127
|
+
table: "",
|
|
128
|
+
primaryKey: "",
|
|
129
|
+
foreignKeys: [],
|
|
130
|
+
columns: {}
|
|
131
|
+
};
|
|
132
|
+
return metadata[TABLE_INFO_PROPERTY_NAME];
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/lib/TableStructureGenerator.ts
|
|
136
|
+
/**
|
|
137
|
+
* Postgres silently truncates longer identifiers, which would lead to differing index names in each migration
|
|
138
|
+
*/
|
|
139
|
+
const MAX_INDEX_NAME_LENGTH = 63;
|
|
140
|
+
/**
|
|
141
|
+
* Represents a generator for creating table structures based on specified database instructions
|
|
142
|
+
*/
|
|
143
|
+
var TableStructureGenerator = class {
|
|
144
|
+
dialect;
|
|
145
|
+
dbInstructions;
|
|
146
|
+
constructor(dbInstructions, dialect) {
|
|
147
|
+
this.dialect = dialect;
|
|
148
|
+
this.dbInstructions = dbInstructions;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Generates the structure of tables based on database instructions.
|
|
152
|
+
*
|
|
153
|
+
* @return An object where keys are table names, and values are their corresponding table structures.
|
|
154
|
+
*/
|
|
155
|
+
generateTableStructure() {
|
|
156
|
+
const tables = {};
|
|
157
|
+
const indexNames = {};
|
|
158
|
+
for (const table of this.dbInstructions.tables) {
|
|
159
|
+
let structure;
|
|
160
|
+
let tableName;
|
|
161
|
+
if (TableObjHelper.isTableObj(table)) {
|
|
162
|
+
structure = table.tableStructure;
|
|
163
|
+
tableName = table.tableName;
|
|
164
|
+
} else {
|
|
165
|
+
const classTable = table;
|
|
166
|
+
structure = getTableStructure(classTable);
|
|
167
|
+
tableName = classTable.name;
|
|
168
|
+
}
|
|
169
|
+
for (const key in structure.columns) {
|
|
170
|
+
const entry = structure.columns[key];
|
|
171
|
+
entry.defaultValue = entry.inputDefaultValue === null ? this.dialect.nullType : this.dialect.formatValueToSql(entry.inputDefaultValue, entry.inputType);
|
|
172
|
+
entry.sqlType = this.dialect.getSqlType(entry.inputType, entry);
|
|
173
|
+
}
|
|
174
|
+
const indexes = this.getIndexes(tableName, structure);
|
|
175
|
+
for (const index of indexes) {
|
|
176
|
+
if (indexNames[index.name]) throw new Error(`Index name "${index.name}" is used in ${indexNames[index.name]} and ${tableName}. Index names need to be unique.`);
|
|
177
|
+
indexNames[index.name] = tableName;
|
|
178
|
+
}
|
|
179
|
+
tables[tableName] = {
|
|
180
|
+
...structure,
|
|
181
|
+
indexes
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
return tables;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Validates the index definitions of a table and generates names for indexes that have none.
|
|
188
|
+
*
|
|
189
|
+
* @param tableName - The name of the table the indexes belong to.
|
|
190
|
+
* @param structure - The table structure containing the index definitions.
|
|
191
|
+
* @return The index definitions including their names.
|
|
192
|
+
*/
|
|
193
|
+
getIndexes(tableName, structure) {
|
|
194
|
+
return (structure.indexes ?? []).map((index) => {
|
|
195
|
+
if (!index.columns.length) throw new Error(`An index in ${tableName} has no columns.`);
|
|
196
|
+
for (const column of index.columns) if (!structure.columns[column]) throw new Error(`Index in ${tableName} uses column "${column}", which does not exist.`);
|
|
197
|
+
const name = index.name ?? `${tableName}_${index.columns.join("_")}_idx`;
|
|
198
|
+
if (name.length > MAX_INDEX_NAME_LENGTH) throw new Error(`Index name "${name}" is longer than ${MAX_INDEX_NAME_LENGTH} characters. Please provide a shorter name.`);
|
|
199
|
+
return {
|
|
200
|
+
name,
|
|
201
|
+
columns: index.columns,
|
|
202
|
+
isUnique: index.isUnique
|
|
203
|
+
};
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
//#endregion
|
|
208
|
+
//#region src/lib/typings/AllowedMigrations.ts
|
|
209
|
+
const ALLOWED = "allowed";
|
|
210
|
+
const USED = "allowedAndUsed";
|
|
211
|
+
const NO_COLUMN = "noColumn";
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/lib/exceptions/NotAllowedException.ts
|
|
214
|
+
var NotAllowedException = class extends Error {
|
|
215
|
+
constructor(entries) {
|
|
216
|
+
let message = "Some destructive changes need to be confirmed. To confirm, add to preMigration():\n";
|
|
217
|
+
for (const entry of entries) message += `\t\tmigrations.allowMigration(${entry.version}, "${entry.tableName}", "${entry.type.toString()}"${entry.column != "noColumn" ? `, "${entry.column}"` : ""});\n`;
|
|
218
|
+
super(message);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
//#endregion
|
|
222
|
+
//#region src/lib/Migrations.ts
|
|
223
|
+
/**
|
|
224
|
+
* The Migrations class is responsible for managing manual database schema migrations.
|
|
225
|
+
*/
|
|
226
|
+
var Migrations = class {
|
|
227
|
+
fromVersion = 0;
|
|
228
|
+
toVersion = 0;
|
|
229
|
+
lastUsedVersion = 0;
|
|
230
|
+
migrationData = {};
|
|
231
|
+
migrationDataForOldTableNames = {};
|
|
232
|
+
alwaysAllowed = [];
|
|
233
|
+
notAllowedChanges = [];
|
|
234
|
+
/**
|
|
235
|
+
* Resets the migration state to its initial values.
|
|
236
|
+
* Only used internally.
|
|
237
|
+
*
|
|
238
|
+
* @param dbInstructions - The instructions containing database metadata and migration details.
|
|
239
|
+
* @param fromVersion - The version of the actual database.
|
|
240
|
+
*/
|
|
241
|
+
reset(dbInstructions, fromVersion) {
|
|
242
|
+
this.fromVersion = fromVersion;
|
|
243
|
+
this.toVersion = dbInstructions.version;
|
|
244
|
+
this.migrationData = {};
|
|
245
|
+
this.migrationDataForOldTableNames = {};
|
|
246
|
+
this.alwaysAllowed = dbInstructions.alwaysAllowedMigrations ?? [];
|
|
247
|
+
this.notAllowedChanges = [];
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Retrieves the migration instructions for the specified table.
|
|
251
|
+
*
|
|
252
|
+
* @param tableName - The name of the table for which the entry is to be retrieved or created.
|
|
253
|
+
* @return The migration instructions corresponding to the given table input.
|
|
254
|
+
*/
|
|
255
|
+
getEntryFromTableName(tableName) {
|
|
256
|
+
if (!this.migrationData.hasOwnProperty(tableName)) this.migrationData[tableName] = {
|
|
257
|
+
recreate: false,
|
|
258
|
+
renamedColumns: [],
|
|
259
|
+
allowedMigrations: {}
|
|
260
|
+
};
|
|
261
|
+
return this.migrationData[tableName];
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Checks whether a provided version is relevant based on database version ({@link fromVersion}) and target version ({@link toVersion}).
|
|
265
|
+
* Also makes sure that version checks happen in order.
|
|
266
|
+
*
|
|
267
|
+
* @param version - The version to check for relevance.
|
|
268
|
+
* @return Returns true if the version is relevant, otherwise false.
|
|
269
|
+
* @throws Error if versions are not properly ordered
|
|
270
|
+
*/
|
|
271
|
+
versionIsRelevant(version) {
|
|
272
|
+
if (version <= this.fromVersion || version > this.toVersion) return false;
|
|
273
|
+
if (version < this.lastUsedVersion) throw new Error("Migrations in preMigration() have to be ordered by version (beginning with the lowest version).");
|
|
274
|
+
this.lastUsedVersion = version;
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Verifies the renaming tasks specified in {@link DatabaseInstructions.preMigration} that were considered are valid.
|
|
279
|
+
* Called after all SQL queries have been generated.
|
|
280
|
+
* Only used internally.
|
|
281
|
+
*
|
|
282
|
+
* @param newTables - The table structures extracted from {@link DatabaseInstructions.tables}.
|
|
283
|
+
* @throws Error if a renaming task is invalid.
|
|
284
|
+
*/
|
|
285
|
+
verifyRenamingTasks(newTables) {
|
|
286
|
+
for (const tableName in this.migrationData) {
|
|
287
|
+
const migrationEntry = this.migrationData[tableName];
|
|
288
|
+
if (migrationEntry.tableRenaming) {
|
|
289
|
+
if (migrationEntry.tableRenaming.oldName == tableName) return /* @__PURE__ */ new Error(`You set table "${tableName}" to be renamed to itself!`);
|
|
290
|
+
if (migrationEntry.tableRenaming.newName != tableName) return /* @__PURE__ */ new Error(`You set table "${tableName}" to be renamed to a different name than the one in your structure (${migrationEntry.tableRenaming.newName})!`);
|
|
291
|
+
else if (!newTables[tableName]) return /* @__PURE__ */ new Error(`You set migrations for "${tableName}". But "${tableName}" does not exist in your structure.`);
|
|
292
|
+
}
|
|
293
|
+
for (const renamingData of migrationEntry.renamedColumns) {
|
|
294
|
+
const oldColumnName = renamingData.oldName;
|
|
295
|
+
const newColumnName = renamingData.newName;
|
|
296
|
+
if (oldColumnName == newColumnName) return /* @__PURE__ */ new Error(`You set column ${tableName}.${oldColumnName} to be renamed to itself!`);
|
|
297
|
+
else if (!newTables[tableName]?.columns[newColumnName]) return /* @__PURE__ */ new Error(`You set column ${tableName}.${oldColumnName} to be renamed to ${tableName}.${newColumnName}. But ${tableName}.${newColumnName} does not exist in your structure.`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Making sure all considered calls to {@link allowMigration()} where necessary to prevent input mistakes.
|
|
303
|
+
* Called after all SQL queries have been generated.
|
|
304
|
+
* Only used internally.
|
|
305
|
+
*
|
|
306
|
+
* @throws Error if unnecessary calls were discovered. All discovered calls are collected and thrown as one Error.
|
|
307
|
+
*/
|
|
308
|
+
verifyAllowedMigrations() {
|
|
309
|
+
if (this.notAllowedChanges.length) return new NotAllowedException(this.notAllowedChanges);
|
|
310
|
+
let errorMsg = "";
|
|
311
|
+
for (const tableName in this.migrationData) {
|
|
312
|
+
const migration = this.migrationData[tableName];
|
|
313
|
+
for (const type in migration.allowedMigrations) {
|
|
314
|
+
const migrationType = migration.allowedMigrations[type];
|
|
315
|
+
for (const column in migrationType) if (migrationType[column] != "allowedAndUsed") errorMsg += `Migration \"${type}\" for ${tableName}${column != "noColumn" ? `.${column}` : ""} was allowed but not needed.\n`;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (errorMsg) return new Error(errorMsg);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Called by {@link MigrationManager} to check if a specific destructive query is allowed.
|
|
322
|
+
* Only used internally.
|
|
323
|
+
*
|
|
324
|
+
* @see allowMigration()
|
|
325
|
+
* @param tableName - The name of the table to check the migration against.
|
|
326
|
+
* @param type - The type of destructive migration being checked.
|
|
327
|
+
* @param column - The column name for which the migration is allowed. Only needed for "dropColumn", "removeForeignKey" and "alterForeignKey".
|
|
328
|
+
* For "dropIndex", the index name is used instead.
|
|
329
|
+
*/
|
|
330
|
+
compareWithAllowedMigration(tableName, type, column = NO_COLUMN) {
|
|
331
|
+
const migrationEntry = this.migrationData[tableName];
|
|
332
|
+
const allowedMigrations = migrationEntry?.allowedMigrations[type];
|
|
333
|
+
if (!allowedMigrations || !allowedMigrations[column]) {
|
|
334
|
+
if (!this.alwaysAllowed.includes(type)) this.notAllowedChanges.push({
|
|
335
|
+
version: this.toVersion,
|
|
336
|
+
tableName,
|
|
337
|
+
column,
|
|
338
|
+
type
|
|
339
|
+
});
|
|
340
|
+
} else if (migrationEntry) allowedMigrations[column] = USED;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Retrieves the migration data containing instructions for data migration.
|
|
344
|
+
* Only used internally.
|
|
345
|
+
*
|
|
346
|
+
* @return An object where each key corresponds to the table name,
|
|
347
|
+
* and the value is the associated migration instructions.
|
|
348
|
+
*/
|
|
349
|
+
getMigrationData() {
|
|
350
|
+
return this.migrationData;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Iterates over renamed columns for the specified table and executes a callback for each pair of old and new column names.
|
|
354
|
+
* Only used internally.
|
|
355
|
+
*
|
|
356
|
+
* @param tableName - Name of the table whose renamed columns should be processed.
|
|
357
|
+
* @param callback - A function to execute for each renamed column, receiving the old and new column names as arguments.
|
|
358
|
+
*/
|
|
359
|
+
loopRenamedColumns(tableName, callback) {
|
|
360
|
+
const migrationEntry = this.migrationData[tableName];
|
|
361
|
+
for (const renamingData of migrationEntry.renamedColumns) callback(renamingData.oldName, renamingData.newName);
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Considers the renaming of a table and returns its (newest) name after the migration or
|
|
365
|
+
* the original name if no renaming is queued.
|
|
366
|
+
* Only used internally.
|
|
367
|
+
*
|
|
368
|
+
* @see getOldTableName()
|
|
369
|
+
* @param tableName - The current table name in the database.
|
|
370
|
+
* @return The newest table name if available, otherwise the current table name.
|
|
371
|
+
*/
|
|
372
|
+
getNewestTableName(tableName) {
|
|
373
|
+
return this.migrationDataForOldTableNames[tableName]?.tableRenaming?.newName ?? tableName;
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Retrieves the current table name in the database.
|
|
377
|
+
* Only used internally.
|
|
378
|
+
*
|
|
379
|
+
* @see getNewestTableName()
|
|
380
|
+
* @param tableName - The name of the newest table name.
|
|
381
|
+
* @return The current table name in the database.
|
|
382
|
+
*/
|
|
383
|
+
getOldTableName(tableName) {
|
|
384
|
+
return this.migrationData[tableName]?.tableRenaming?.oldName ?? tableName;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Considers the renaming of a column in a table and returns its (newest) name after the migration or
|
|
388
|
+
* the original name if no renaming is queued.
|
|
389
|
+
* Only used internally.
|
|
390
|
+
*
|
|
391
|
+
* @param tableName - The name of the table containing the column.
|
|
392
|
+
* @param oldColumnName - The current name of the column in the database.
|
|
393
|
+
* @return The newest column name if available, otherwise the original column name.
|
|
394
|
+
*/
|
|
395
|
+
getNewestColumnName(tableName, oldColumnName) {
|
|
396
|
+
const columnNames = this.migrationData[tableName]?.renamedColumns.find((columns) => columns.oldName == oldColumnName);
|
|
397
|
+
return columnNames ? columnNames.newName : oldColumnName;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Determines if the specified table is marked to be recreated.
|
|
401
|
+
* Only used internally.
|
|
402
|
+
*
|
|
403
|
+
* @param tableName The name of the table to check.
|
|
404
|
+
* @return Returns true if the table will be recreated, false otherwise.
|
|
405
|
+
*/
|
|
406
|
+
willBeRecreated(tableName) {
|
|
407
|
+
return this.migrationData[tableName]?.recreate;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Marks a table to be recreated and logs the recreation reason for the user.
|
|
411
|
+
* Only used internally.
|
|
412
|
+
*
|
|
413
|
+
* @param tableName - The name of the table to be marked for recreation.
|
|
414
|
+
* @param reason - The reason why the table is being marked for recreation.
|
|
415
|
+
*/
|
|
416
|
+
internalRecreate(tableName, reason) {
|
|
417
|
+
const entry = this.getEntryFromTableName(tableName);
|
|
418
|
+
entry.recreate = true;
|
|
419
|
+
Logger.log(`Table ${tableName} will be recreated (${reason})!`);
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* SqlMorpheus only allows destructive statements if it was specifically allowed in {@link DatabaseInstructions.preMigration()}.
|
|
423
|
+
* Use this method to allow a destructive statement for a specific version.
|
|
424
|
+
* This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
|
|
425
|
+
*
|
|
426
|
+
* @param version - The target version for which the specific migration is allowed. Must be provided to make sure this method will only have an effect when specified.
|
|
427
|
+
* @param tableName - The current table name in the database at the time of the migration version.
|
|
428
|
+
* @param allowedMigration - The keys representing the migrations to be allowed.
|
|
429
|
+
* @param column - The column name for which the migration is allowed. Only needed for "dropColumn", "removeForeignKey" and "alterForeignKey".
|
|
430
|
+
* For "dropIndex", provide the index name instead.
|
|
431
|
+
*
|
|
432
|
+
* @throws Error if the provided column name is not valid for the specified migration.
|
|
433
|
+
*/
|
|
434
|
+
allowMigration(version, tableName, allowedMigration, column) {
|
|
435
|
+
if (!this.versionIsRelevant(version)) return;
|
|
436
|
+
const entry = this.getEntryFromTableName(tableName);
|
|
437
|
+
if (!entry.allowedMigrations[allowedMigration]) entry.allowedMigrations[allowedMigration] = {};
|
|
438
|
+
entry.allowedMigrations[allowedMigration][column ?? "noColumn"] = ALLOWED;
|
|
439
|
+
if (column) switch (allowedMigration) {
|
|
440
|
+
case "recreateTable":
|
|
441
|
+
case "dropTable":
|
|
442
|
+
case "alterPrimaryKey": throw new Error(`You cannot use the ${allowedMigration} migration with a column name. Please remove the column name.`);
|
|
443
|
+
}
|
|
444
|
+
else switch (allowedMigration) {
|
|
445
|
+
case "dropColumn":
|
|
446
|
+
case "removeForeignKey":
|
|
447
|
+
case "alterForeignKey": throw new Error(`The ${allowedMigration} migration requires a column name. Please provide one.`);
|
|
448
|
+
case "dropIndex": throw new Error(`The ${allowedMigration} migration requires an index name. Please provide one.`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* When you change the name of a table, SqlMorpheus will assume the original table was meant to be dropped
|
|
453
|
+
* and the new table was meant to be added, which would lead to data loss.
|
|
454
|
+
* Use this method to mark a table to be renamed instead.
|
|
455
|
+
* This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
|
|
456
|
+
*
|
|
457
|
+
* @param version - The target version for which the table should be renamed. Must be provided to make sure this method will only have an effect when specified.
|
|
458
|
+
* @param oldTableName - The current name in the database at the time of the migration version.
|
|
459
|
+
* @param newTableName - The new table name at the time of the migration version.
|
|
460
|
+
*/
|
|
461
|
+
renameTable(version, oldTableName, newTableName) {
|
|
462
|
+
if (!this.versionIsRelevant(version)) return;
|
|
463
|
+
if (this.migrationData.hasOwnProperty(oldTableName)) {
|
|
464
|
+
this.migrationData[newTableName] = this.migrationData[oldTableName];
|
|
465
|
+
delete this.migrationData[oldTableName];
|
|
466
|
+
}
|
|
467
|
+
const entry = this.getEntryFromTableName(newTableName);
|
|
468
|
+
this.migrationDataForOldTableNames[oldTableName] = entry;
|
|
469
|
+
if (!entry.tableRenaming) entry.tableRenaming = {
|
|
470
|
+
oldName: oldTableName,
|
|
471
|
+
newName: newTableName
|
|
472
|
+
};
|
|
473
|
+
else entry.tableRenaming.newName = newTableName;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* When you change the name of a column, SqlMorpheus will assume the original column was meant to be removed
|
|
477
|
+
* and the new column was meant to be added, which would lead to data loss.
|
|
478
|
+
* Use this method to mark a column to be renamed instead.
|
|
479
|
+
* This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
|
|
480
|
+
*
|
|
481
|
+
* @param version - The target version for which the table should be renamed. Must be provided to make sure this method will only have an effect when specified.
|
|
482
|
+
* @param tableName - The current table name in the database at the time of the migration version.
|
|
483
|
+
* @param oldColumn The current name in the database at the time of the migration.
|
|
484
|
+
* @param newColumn The new name to assign to the column.
|
|
485
|
+
*/
|
|
486
|
+
renameColumn(version, tableName, oldColumn, newColumn) {
|
|
487
|
+
if (!this.versionIsRelevant(version)) return;
|
|
488
|
+
const entry = this.getEntryFromTableName(tableName);
|
|
489
|
+
const existingColumnEntry = entry.renamedColumns.find((entry) => entry.newName == oldColumn);
|
|
490
|
+
if (existingColumnEntry) existingColumnEntry.newName = newColumn;
|
|
491
|
+
else entry.renamedColumns.push({
|
|
492
|
+
oldName: oldColumn,
|
|
493
|
+
newName: newColumn
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Should not be needed most of the time.
|
|
498
|
+
* Marks a table to be recreated
|
|
499
|
+
* (a copy of the table will be created, all data will be moved over, the original table will be dropped and the new table will be renamed to the original name).
|
|
500
|
+
* This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
|
|
501
|
+
*
|
|
502
|
+
* @param version - The target version for which the table should be renamed. Must be provided to make sure this method will only have an effect when specified.
|
|
503
|
+
* @param tableName - The current table name in the database at the time of the migration version.
|
|
504
|
+
*/
|
|
505
|
+
recreateTable(version, tableName) {
|
|
506
|
+
if (!this.versionIsRelevant(version)) return;
|
|
507
|
+
const entry = this.getEntryFromTableName(tableName);
|
|
508
|
+
entry.recreate = true;
|
|
509
|
+
Logger.log(`Table ${tableName} will be recreated!`);
|
|
510
|
+
this.allowMigration(version, tableName, "recreateTable");
|
|
511
|
+
}
|
|
512
|
+
};
|
|
513
|
+
//#endregion
|
|
514
|
+
//#region src/lib/dialects/DefaultSql.ts
|
|
515
|
+
const MIGRATION_DATA_TABLE_NAME = "__sqlmorpheus_migrations";
|
|
516
|
+
/**
|
|
517
|
+
* Provides syntax for SQL queries. Specified dialects extend from this class.
|
|
518
|
+
* Needs a {@link DatabaseAccess} object for database operations
|
|
519
|
+
*/
|
|
520
|
+
var DefaultSql = class {
|
|
521
|
+
db;
|
|
522
|
+
canRecreateTable = false;
|
|
523
|
+
canAlterColumnStructure = false;
|
|
524
|
+
canAlterForeignKeys = false;
|
|
525
|
+
canAlterPrimaryKey = false;
|
|
526
|
+
types = {
|
|
527
|
+
text: "TEXT",
|
|
528
|
+
string: "TEXT",
|
|
529
|
+
number: "INTEGER",
|
|
530
|
+
bigint: "BIGINT",
|
|
531
|
+
boolean: "BOOLEAN",
|
|
532
|
+
date: "DATE",
|
|
533
|
+
time: "TIME",
|
|
534
|
+
dateTime: "DATETIME"
|
|
535
|
+
};
|
|
536
|
+
nullType = "NULL";
|
|
537
|
+
constructor(db) {
|
|
538
|
+
this.db = db;
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Formats a given value to a SQL-equivalent string based on the provided data type.
|
|
542
|
+
*
|
|
543
|
+
* @param value - The value to be formatted.
|
|
544
|
+
* @param type - The data type of the value. Either determined through typeof or {@link TableStructure} setting
|
|
545
|
+
* @return A string representation of the value formatted for SQL.
|
|
546
|
+
*/
|
|
547
|
+
formatValueToSql(value, type) {
|
|
548
|
+
function toDate(value) {
|
|
549
|
+
return value instanceof Date ? value : new Date(value);
|
|
550
|
+
}
|
|
551
|
+
switch (type) {
|
|
552
|
+
case "text":
|
|
553
|
+
case "string": return `'${value}'`;
|
|
554
|
+
case "time": return `'${toDate(value).toISOString().slice(11, 19)}'`;
|
|
555
|
+
case "date": return `'${toDate(value).toISOString().slice(0, 10)}'`;
|
|
556
|
+
case "dateTime": return `'${toDate(value).toISOString().slice(0, 19).replace("T", " ")}'`;
|
|
557
|
+
default: return value.toString();
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
formatIdentifier(identifier) {
|
|
561
|
+
return identifier;
|
|
562
|
+
}
|
|
563
|
+
getSqlType(dataType, _) {
|
|
564
|
+
return this.types[dataType];
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Changes the column type and the default value of a column in a specified table.
|
|
568
|
+
* Is only used if {@link canAlterColumnStructure} is true.
|
|
569
|
+
*
|
|
570
|
+
* @param tableName - The name of the table containing the column to be altered.
|
|
571
|
+
* @param columnName - The name of the column to be altered.
|
|
572
|
+
* @param sqlType - The new data type (specific to the SQL dialect) for the column.
|
|
573
|
+
* @param defaultValue - The new default value for the column.
|
|
574
|
+
* @return The SQL statement as a string.
|
|
575
|
+
*/
|
|
576
|
+
alterColumnStructure(tableName, columnName, sqlType, defaultValue) {
|
|
577
|
+
throw new Error("Altering column structure is not supported. Recreate the table instead!");
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Statement to add a foreign key to a specified table.
|
|
581
|
+
* Is only used if {@link canAlterForeignKeys} is true.
|
|
582
|
+
*
|
|
583
|
+
* @param fromTableName - The name of the table to which the foreign key will be added.
|
|
584
|
+
* @param foreignKey - The foreign key definition to be added, see {@link foreignKey()}.
|
|
585
|
+
* @return The SQL statement as a string.
|
|
586
|
+
*/
|
|
587
|
+
addForeignKey(fromTableName, foreignKey) {
|
|
588
|
+
throw new Error("Adding foreign keys is not supported!");
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Statement to remove a foreign key from a specified table.
|
|
592
|
+
* Is only used if {@link canAlterForeignKeys} is true.
|
|
593
|
+
*
|
|
594
|
+
* @param tableName - The name of the table to which the foreign key will be added.
|
|
595
|
+
* @param foreignKeyName - The name of the foreign key definition.
|
|
596
|
+
* @return The SQL statement as a string.
|
|
597
|
+
*/
|
|
598
|
+
removeForeignKey(tableName, foreignKeyName) {
|
|
599
|
+
throw new Error("Foreign key removal is not supported!");
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Statement to add a primary key to the specified table.
|
|
603
|
+
* Is only used if {@link canAlterPrimaryKey} is true.
|
|
604
|
+
*
|
|
605
|
+
* @param tableName - The name of the table to which the primary key will be added.
|
|
606
|
+
* @param columnName - The name of the column that will be set as the primary key.
|
|
607
|
+
* @return The SQL statement as a string.
|
|
608
|
+
*/
|
|
609
|
+
addPrimaryKey(tableName, columnName) {
|
|
610
|
+
throw new Error("Adding foreign keys is not supported!");
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Statement to remove a primary key from the specified table.
|
|
614
|
+
* Is only used if {@link canAlterPrimaryKey} is true.
|
|
615
|
+
*
|
|
616
|
+
* @param tableName - The name of the table to which the primary key will be added.
|
|
617
|
+
* @param columnName - The name of the column that will be set as the primary key.
|
|
618
|
+
* @return The SQL statement as a string.
|
|
619
|
+
*/
|
|
620
|
+
removePrimaryKey(tableName, columnName) {
|
|
621
|
+
throw new Error("Foreign key removal is not supported!");
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Constructs a SQL FOREIGN KEY constraint clause.
|
|
625
|
+
* Used in combination with {@link addForeignKey} or {@link createTable}
|
|
626
|
+
*
|
|
627
|
+
* @param column - The name of the column in the current table to apply the foreign key constraint.
|
|
628
|
+
* @param foreignTable - The name of the referenced table.
|
|
629
|
+
* @param foreignColumn - The name of the referenced column in the foreign table.
|
|
630
|
+
* @param onUpdate - Optional action to specify the behavior on update (e.g., CASCADE, SET NULL).
|
|
631
|
+
* @param onDelete - Optional action to specify the behavior on delete (e.g., CASCADE, SET NULL).
|
|
632
|
+
* @return The SQL string representing the foreign key constraint.
|
|
633
|
+
*/
|
|
634
|
+
foreignKey(column, foreignTable, foreignColumn, onUpdate, onDelete) {
|
|
635
|
+
let query = `FOREIGN KEY (${this.formatIdentifier(column)}) REFERENCES ${this.formatIdentifier(foreignTable)} (${this.formatIdentifier(foreignColumn)})`;
|
|
636
|
+
if (onUpdate) query += ` ON UPDATE ${onUpdate}`;
|
|
637
|
+
if (onDelete) query += ` ON DELETE ${onDelete}`;
|
|
638
|
+
return query;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Statement to create a table if it does not already exist.
|
|
642
|
+
*
|
|
643
|
+
* @param tableName - The name of the table to be created.
|
|
644
|
+
* @param entries - An array containing the column definitions for the table.
|
|
645
|
+
* @return The SQL statement as a string.
|
|
646
|
+
*/
|
|
647
|
+
createTable(tableName, entries) {
|
|
648
|
+
return `CREATE TABLE IF NOT EXISTS ${this.formatIdentifier(tableName)} (\n\t${entries.join(",\n ")}\n);`;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Statement to rename a table.
|
|
652
|
+
*
|
|
653
|
+
* @param tableName - The name of the existing table to be renamed.
|
|
654
|
+
* @param newTableName - The new name for the table.
|
|
655
|
+
* @return The SQL statement as a string.
|
|
656
|
+
*/
|
|
657
|
+
renameTable(tableName, newTableName) {
|
|
658
|
+
return `ALTER TABLE ${this.formatIdentifier(tableName)} RENAME TO ${this.formatIdentifier(newTableName)};`;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Statement to drop a table if it exists.
|
|
662
|
+
*
|
|
663
|
+
* @param tableName - The name of the table to be dropped.
|
|
664
|
+
* @return The SQL statement as a string.
|
|
665
|
+
*/
|
|
666
|
+
dropTable(tableName) {
|
|
667
|
+
return `DROP TABLE IF EXISTS ${this.formatIdentifier(tableName)};`;
|
|
668
|
+
}
|
|
669
|
+
recreateTable(tableName, entries) {
|
|
670
|
+
return `DROP TABLE IF EXISTS ${this.formatIdentifier(tableName)}; ${this.createTable(tableName, entries)}`;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Constructs a SQL column definition based on the provided parameters.
|
|
674
|
+
*
|
|
675
|
+
* @param columnName - The name of the column.
|
|
676
|
+
* @param type - The data type of the column.
|
|
677
|
+
* @param defaultValue - The default value for the column.
|
|
678
|
+
* @param isPrimaryKey - Indicates whether the column is a primary key.
|
|
679
|
+
* @return The constructed SQL column definition string.
|
|
680
|
+
*/
|
|
681
|
+
columnDefinition(columnName, type, isPrimaryKey, defaultValue) {
|
|
682
|
+
const query = `${this.formatIdentifier(columnName)} ${type}${defaultValue ? ` DEFAULT ${defaultValue}` : ""}`;
|
|
683
|
+
return isPrimaryKey ? `${query} PRIMARY KEY` : query;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Statement to add a new column to a specified table.
|
|
687
|
+
*
|
|
688
|
+
* @param columnTable - The name of the table to which the column will be added.
|
|
689
|
+
* @param entry - The column definition including the column name and its data type. See {@link columnDefinition()}
|
|
690
|
+
* @return The SQL statement as a string.
|
|
691
|
+
*/
|
|
692
|
+
createColumn(columnTable, entry) {
|
|
693
|
+
return `ALTER TABLE ${this.formatIdentifier(columnTable)} ADD ${entry};`;
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Statement to rename a column in an existing table.
|
|
697
|
+
*
|
|
698
|
+
* @param tableName - The name of the table containing the column to rename.
|
|
699
|
+
* @param oldColumnName - The current name of the column to be renamed.
|
|
700
|
+
* @param newColumnName - The new name for the column.
|
|
701
|
+
* @return The SQL statement as a string.
|
|
702
|
+
*/
|
|
703
|
+
renameColumn(tableName, oldColumnName, newColumnName) {
|
|
704
|
+
return `ALTER TABLE ${this.formatIdentifier(tableName)} RENAME COLUMN ${this.formatIdentifier(oldColumnName)} TO ${this.formatIdentifier(newColumnName)};`;
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Statement to drop a column from a specified table.
|
|
708
|
+
*
|
|
709
|
+
* @param tableName - The name of the table from which the column will be dropped.
|
|
710
|
+
* @param columnName - The name of the column to be dropped.
|
|
711
|
+
* @return The SQL statement as a string.
|
|
712
|
+
*/
|
|
713
|
+
dropColumn(tableName, columnName) {
|
|
714
|
+
return `ALTER TABLE ${this.formatIdentifier(tableName)} DROP COLUMN ${this.formatIdentifier(columnName)};`;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Statement to create an index on a specified table.
|
|
718
|
+
*
|
|
719
|
+
* @param tableName - The name of the table on which the index will be created.
|
|
720
|
+
* @param index - The index definition.
|
|
721
|
+
* @return The SQL statement as a string.
|
|
722
|
+
*/
|
|
723
|
+
createIndex(tableName, index) {
|
|
724
|
+
return `CREATE ${index.isUnique ? "UNIQUE " : ""}INDEX ${this.formatIdentifier(index.name)} ON ${this.formatIdentifier(tableName)} (${index.columns.map((column) => this.formatIdentifier(column)).join(", ")});`;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Statement to drop an index from a specified table.
|
|
728
|
+
*
|
|
729
|
+
* @param tableName - The name of the table the index belongs to.
|
|
730
|
+
* @param indexName - The name of the index to be dropped.
|
|
731
|
+
* @return The SQL statement as a string.
|
|
732
|
+
*/
|
|
733
|
+
dropIndex(tableName, indexName) {
|
|
734
|
+
return `DROP INDEX ${this.formatIdentifier(indexName)};`;
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Statement to return data from a table.
|
|
738
|
+
*
|
|
739
|
+
* @param tableName - The name of the database table to select data from.
|
|
740
|
+
* @param select - An array of column names to include in the SELECT clause.
|
|
741
|
+
* @param where - An optional condition.
|
|
742
|
+
* @param orderBy - Optional. the column to sort by
|
|
743
|
+
* @return The SQL statement as a string.
|
|
744
|
+
*/
|
|
745
|
+
select(tableName, select, where, orderBy) {
|
|
746
|
+
let query = `SELECT ${select.map((k) => this.formatIdentifier(k)).join(",")} FROM ${this.formatIdentifier(tableName)}`;
|
|
747
|
+
if (where) query += ` WHERE ${where}`;
|
|
748
|
+
if (orderBy) query += ` ORDER BY ${orderBy}`;
|
|
749
|
+
return `${query};`;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Statement to insert data into a table.
|
|
753
|
+
*
|
|
754
|
+
* @param tableName - The name of the table where the data will be inserted.
|
|
755
|
+
* @param content - The value query. See {@link insertValues()}.
|
|
756
|
+
* @return The SQL statement as a string.
|
|
757
|
+
*/
|
|
758
|
+
insert(tableName, content) {
|
|
759
|
+
return `INSERT INTO ${this.formatIdentifier(tableName)} ${content};`;
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* A SQL insert query string. See {@link insert()}.
|
|
763
|
+
*
|
|
764
|
+
* @param keys - An array of column names to be used in the query.
|
|
765
|
+
* @param [valueString] - An optional preformatted value string to be included in the query.
|
|
766
|
+
* If not provided, the method generates a default placeholder string with "?" for each key.
|
|
767
|
+
* @return The SQL statement as a string.
|
|
768
|
+
*/
|
|
769
|
+
insertValues(keys, valueString) {
|
|
770
|
+
return `(${keys.map((k) => this.formatIdentifier(k)).join(",")}) ${valueString ?? `VALUES (${keys.map(() => "?").join(",")})`}`;
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Returns a SQL query string to create a migration table.
|
|
774
|
+
* The table is used to store migration data, specifically the version of the migration.
|
|
775
|
+
*
|
|
776
|
+
* @return The SQL query string for creating the migration table.
|
|
777
|
+
*/
|
|
778
|
+
migrationTableQuery() {
|
|
779
|
+
return this.createTable(MIGRATION_DATA_TABLE_NAME, [
|
|
780
|
+
this.columnDefinition("fromVersion", this.getSqlType("number"), false, "0"),
|
|
781
|
+
this.columnDefinition("toVersion", this.getSqlType("number"), true, "0"),
|
|
782
|
+
this.columnDefinition("upChanges", this.getSqlType("text"), false),
|
|
783
|
+
this.columnDefinition("downChanges", this.getSqlType("text"), false)
|
|
784
|
+
]);
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Combines rows (one row per indexed column, ordered by index name and column position) into a list of {@link IndexInfo}.
|
|
788
|
+
*
|
|
789
|
+
* @param rows - Rows containing the index name, whether the index is unique and the column name.
|
|
790
|
+
* @return An array of {@link IndexInfo}.
|
|
791
|
+
*/
|
|
792
|
+
rowsToIndexInfo(rows) {
|
|
793
|
+
const indexes = {};
|
|
794
|
+
for (const row of rows) {
|
|
795
|
+
if (!indexes[row.index_name]) indexes[row.index_name] = {
|
|
796
|
+
name: row.index_name,
|
|
797
|
+
columns: [],
|
|
798
|
+
isUnique: !!Number(row.is_unique)
|
|
799
|
+
};
|
|
800
|
+
indexes[row.index_name].columns.push(row.column_name);
|
|
801
|
+
}
|
|
802
|
+
return Object.values(indexes);
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Ensures that the migration table exists in the database.
|
|
806
|
+
* If the table does not exist, it creates the table using the defined migration table query.
|
|
807
|
+
*
|
|
808
|
+
* @return A promise that resolves when the migration table is created successfully.
|
|
809
|
+
*/
|
|
810
|
+
async createMigrationTableIfNeeded() {
|
|
811
|
+
await this.db.runTransaction(this.migrationTableQuery());
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Retrieves the current version from the migration data table.
|
|
815
|
+
*
|
|
816
|
+
* @return A promise that resolves to the current version number. Returns 0 if no version is found.
|
|
817
|
+
*/
|
|
818
|
+
async getVersion() {
|
|
819
|
+
await this.createMigrationTableIfNeeded();
|
|
820
|
+
const query = this.select(MIGRATION_DATA_TABLE_NAME, ["toVersion"], void 0, `${this.formatIdentifier("toVersion")} DESC`);
|
|
821
|
+
const data = await this.db.runReadStatement(query);
|
|
822
|
+
return data.length ? data[0].toVersion : 0;
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Updates the migration version in the database. If the version entry does not exist, it inserts a new one;
|
|
826
|
+
* if it exists, it updates the version to the specified value.
|
|
827
|
+
*
|
|
828
|
+
* @param toVersion - The new migration version to set in the database.
|
|
829
|
+
* @return A promise that resolves when the operation is complete.
|
|
830
|
+
*/
|
|
831
|
+
async rollbackHistory(toVersion) {
|
|
832
|
+
const query = `${this.migrationTableQuery()}; DELETE FROM ${MIGRATION_DATA_TABLE_NAME} WHERE toVersion > ${toVersion};`;
|
|
833
|
+
await this.db.runTransaction(query);
|
|
834
|
+
}
|
|
835
|
+
async getChanges(version) {
|
|
836
|
+
await this.createMigrationTableIfNeeded();
|
|
837
|
+
const query = this.select(MIGRATION_DATA_TABLE_NAME, [
|
|
838
|
+
"fromVersion",
|
|
839
|
+
"upChanges",
|
|
840
|
+
"downChanges"
|
|
841
|
+
], `toVersion = ${version}`);
|
|
842
|
+
const data = await this.db.runReadStatement(query);
|
|
843
|
+
return data ? {
|
|
844
|
+
up: data[0].upChanges,
|
|
845
|
+
down: data[0].downChanges,
|
|
846
|
+
fromVersion: data[0].fromVersion
|
|
847
|
+
} : null;
|
|
848
|
+
}
|
|
849
|
+
async hasChanges(version) {
|
|
850
|
+
await this.createMigrationTableIfNeeded();
|
|
851
|
+
const query = this.select(MIGRATION_DATA_TABLE_NAME, ["toVersion"], `${this.formatIdentifier("toVersion")} = ${version}`);
|
|
852
|
+
return !!(await this.db.runReadStatement(query)).length;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Saves the change history to the SQLMorpheus table in the database
|
|
856
|
+
* Since we save SQL queries in the database, we need to make sure that they are properly escaped.
|
|
857
|
+
* @param fromVersion
|
|
858
|
+
* @param toVersion
|
|
859
|
+
* @param changes
|
|
860
|
+
*/
|
|
861
|
+
async setChanges(fromVersion, toVersion, changes) {
|
|
862
|
+
const escapeStringFu = escape_sql_string.default.default ?? escape_sql_string.default;
|
|
863
|
+
const downChanges = escapeStringFu(changes.down);
|
|
864
|
+
const upChanges = escapeStringFu(changes.up);
|
|
865
|
+
const query = `${this.migrationTableQuery()} ${await this.hasChanges(toVersion) ? `UPDATE ${MIGRATION_DATA_TABLE_NAME}
|
|
866
|
+
SET
|
|
867
|
+
${this.formatIdentifier("fromVersion")} = '${fromVersion}',
|
|
868
|
+
${this.formatIdentifier("upChanges")} = ${upChanges},
|
|
869
|
+
${this.formatIdentifier("downChanges")} = ${downChanges}
|
|
870
|
+
WHERE ${this.formatIdentifier("toVersion")} = '${toVersion}';` : `INSERT INTO ${MIGRATION_DATA_TABLE_NAME} (
|
|
871
|
+
${this.formatIdentifier("fromVersion")},
|
|
872
|
+
${this.formatIdentifier("toVersion")},
|
|
873
|
+
${this.formatIdentifier("upChanges")},
|
|
874
|
+
${this.formatIdentifier("downChanges")}
|
|
875
|
+
)
|
|
876
|
+
VALUES ('${fromVersion}', '${toVersion}', ${upChanges}, ${downChanges})`}`;
|
|
877
|
+
await this.db.runTransaction(query);
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
//#endregion
|
|
881
|
+
//#region src/lib/MigrationManager.ts
|
|
882
|
+
/**
|
|
883
|
+
* The MigrationManager class is responsible for managing database schema migrations.
|
|
884
|
+
* It handles tasks such as generating SQL for migrations, creating migration histories,
|
|
885
|
+
* and synchronizing database schema changes between different versions.
|
|
886
|
+
*/
|
|
887
|
+
var MigrationManager = class {
|
|
888
|
+
migrations = new Migrations();
|
|
889
|
+
newTables = {};
|
|
890
|
+
/**
|
|
891
|
+
* Table names that currently exist in the database
|
|
892
|
+
* Note: If tables are set to be renamed, then names in this array will be corrected to their future name.
|
|
893
|
+
*/
|
|
894
|
+
existingTables = [];
|
|
895
|
+
dialect;
|
|
896
|
+
constructor(dialect) {
|
|
897
|
+
this.dialect = dialect;
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* Generates the SQL changes required to migrate a database from its current version
|
|
901
|
+
* to the target version defined in the database instructions. Handles the creation
|
|
902
|
+
* and deletion of tables, migration of foreign keys and columns, renaming of columns,
|
|
903
|
+
* and recreating tables, along with executing any pre- and post-migration custom logic.
|
|
904
|
+
*
|
|
905
|
+
* @return A promise that resolves to an object containing the SQL
|
|
906
|
+
* changes for the migration (`up` and `down` changes) or null if no migration is required.
|
|
907
|
+
* Throws an error in scenarios such as attempting to migrate to a lower version
|
|
908
|
+
* or an invalid starting version.
|
|
909
|
+
*/
|
|
910
|
+
async generateSqlChanges(dbInstructions) {
|
|
911
|
+
const fromVersion = await this.dialect.getVersion();
|
|
912
|
+
const toVersion = dbInstructions.version;
|
|
913
|
+
if (toVersion <= 0) throw new Error("Cannot migrate to version 0 or lower");
|
|
914
|
+
if (fromVersion == toVersion) {
|
|
915
|
+
Logger.log("Version has not changed. No migrations needed.");
|
|
916
|
+
return null;
|
|
917
|
+
}
|
|
918
|
+
if (fromVersion > toVersion) throw new Error(`You cannot create new migrations with a lower version (from ${fromVersion} to ${toVersion})`);
|
|
919
|
+
const changes = {
|
|
920
|
+
up: "",
|
|
921
|
+
down: ""
|
|
922
|
+
};
|
|
923
|
+
this.migrations.reset(dbInstructions, fromVersion);
|
|
924
|
+
const preSQL = dbInstructions.preMigration?.(this.migrations, this.dialect.db, fromVersion, toVersion);
|
|
925
|
+
if (preSQL) {
|
|
926
|
+
changes.up += `\n\n-- Custom SQL from preMigration()\n${preSQL.up}`;
|
|
927
|
+
changes.down += `\n\n-- Custom SQL from preMigration()\n${preSQL.down}`;
|
|
928
|
+
}
|
|
929
|
+
const tableStructureGenerator = new TableStructureGenerator(dbInstructions, this.dialect);
|
|
930
|
+
this.newTables = tableStructureGenerator.generateTableStructure();
|
|
931
|
+
if (fromVersion == 0) {
|
|
932
|
+
Logger.log(`Creating initial migration to version ${dbInstructions.version}`);
|
|
933
|
+
const initialChanges = await this.createAndDropTables();
|
|
934
|
+
changes.up += initialChanges.up;
|
|
935
|
+
changes.down += initialChanges.down;
|
|
936
|
+
} else {
|
|
937
|
+
Logger.log(`Creating migration SQL from version ${fromVersion} to ${toVersion}`);
|
|
938
|
+
this.existingTables = (await this.dialect.getTableNames()).filter((oldTableName) => oldTableName != MIGRATION_DATA_TABLE_NAME).map((oldTableName) => this.migrations.getNewestTableName(oldTableName));
|
|
939
|
+
const renameTablesChanges = this.renameTables();
|
|
940
|
+
const createAndDropTablesChanges = await this.createAndDropTables();
|
|
941
|
+
const foreignKeyChanges = await this.migrateForeignKeys();
|
|
942
|
+
const columnChanges = await this.migrateColumns();
|
|
943
|
+
const renameColumnsChanges = this.renameColumns();
|
|
944
|
+
const indexChanges = await this.migrateIndexes();
|
|
945
|
+
const recreateTablesChanges = await this.recreateTables();
|
|
946
|
+
[
|
|
947
|
+
renameTablesChanges,
|
|
948
|
+
createAndDropTablesChanges,
|
|
949
|
+
indexChanges.dropped,
|
|
950
|
+
foreignKeyChanges,
|
|
951
|
+
columnChanges,
|
|
952
|
+
renameColumnsChanges,
|
|
953
|
+
indexChanges.created,
|
|
954
|
+
recreateTablesChanges
|
|
955
|
+
].forEach((entry) => {
|
|
956
|
+
changes.up += entry.up;
|
|
957
|
+
changes.down += entry.down;
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
const postSql = dbInstructions.postMigration?.(this.dialect.db, fromVersion, toVersion);
|
|
961
|
+
if (postSql) {
|
|
962
|
+
changes.up += `\n\n-- Custom SQL from postMigration()\n${postSql.up}`;
|
|
963
|
+
changes.down += `\n\n-- Custom SQL from postMigration()\n${postSql.down}`;
|
|
964
|
+
}
|
|
965
|
+
if (fromVersion != 0) {
|
|
966
|
+
const exception = this.migrations.verifyRenamingTasks(this.newTables) ?? this.migrations.verifyAllowedMigrations();
|
|
967
|
+
if (exception) {
|
|
968
|
+
Logger.debug(`\nCanceled changes:\n${changes.up}\n`);
|
|
969
|
+
if (!dbInstructions.doNotThrowIfNotAllowed) throw exception;
|
|
970
|
+
else {
|
|
971
|
+
console.error(exception.message);
|
|
972
|
+
return null;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return {
|
|
977
|
+
fromVersion,
|
|
978
|
+
toVersion,
|
|
979
|
+
changes
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
renameTables() {
|
|
983
|
+
const changes = {
|
|
984
|
+
up: "\n\n-- Rename tables\n",
|
|
985
|
+
down: "\n\n-- Rename tables\n"
|
|
986
|
+
};
|
|
987
|
+
const data = this.migrations.getMigrationData();
|
|
988
|
+
for (const tableName in data) {
|
|
989
|
+
const migrationEntry = data[tableName];
|
|
990
|
+
if (migrationEntry.tableRenaming) {
|
|
991
|
+
Logger.log(`Table "${migrationEntry.tableRenaming.oldName}" will be renamed to "${tableName}"!`);
|
|
992
|
+
changes.up += this.dialect.renameTable(migrationEntry.tableRenaming.oldName, tableName);
|
|
993
|
+
changes.down += this.dialect.renameTable(tableName, migrationEntry.tableRenaming.oldName);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
return changes;
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* Generates SQL change statements for creating and dropping tables based on the current table structure
|
|
1000
|
+
* and existing table configurations in the database. The `up` changes include SQL statements for creating
|
|
1001
|
+
* new tables, while the `down` changes include SQL statements for dropping the corresponding tables or
|
|
1002
|
+
* recreating them if necessary.
|
|
1003
|
+
*
|
|
1004
|
+
* @return {Promise<SqlChanges>} A promise that resolves to an object containing `up` and `down` SQL
|
|
1005
|
+
* change statements for migrating the database schema.
|
|
1006
|
+
*/
|
|
1007
|
+
async createAndDropTables() {
|
|
1008
|
+
let changes = {
|
|
1009
|
+
up: "\n\n-- Create and drop tables\n",
|
|
1010
|
+
down: "\n\n-- Create and drop tables\n"
|
|
1011
|
+
};
|
|
1012
|
+
for (const tableName in this.newTables) if (this.tableDoesNotExists(tableName)) {
|
|
1013
|
+
const structure = this.newTables[tableName];
|
|
1014
|
+
changes.up += `${this.createTableSql(tableName, structure.columns, structure.foreignKeys)}\n`;
|
|
1015
|
+
changes.up += this.createIndexesSql(tableName, structure.indexes);
|
|
1016
|
+
changes.down += `${this.dialect.dropTable(tableName)}\n`;
|
|
1017
|
+
}
|
|
1018
|
+
for (const tableName of this.existingTables) if (!this.newTables[tableName]) {
|
|
1019
|
+
this.migrations.compareWithAllowedMigration(tableName, "dropTable");
|
|
1020
|
+
const dbTableName = this.migrations.getOldTableName(tableName);
|
|
1021
|
+
changes.up += `${this.dialect.dropTable(tableName)}\n`;
|
|
1022
|
+
changes.down += this.createTableSql(tableName, await this.dialect.getColumnInformation(dbTableName), await this.dialect.getForeignKeys(dbTableName)) + "\n" + this.createIndexesSql(tableName, await this.dialect.getIndexes(dbTableName));
|
|
1023
|
+
}
|
|
1024
|
+
return changes;
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Generates an SQL string to create a table with the specified schema.
|
|
1028
|
+
*
|
|
1029
|
+
* @param tableName - The name of the table to be created.
|
|
1030
|
+
* @param columns - An array of objects defining the columns of the table, including their names, types
|
|
1031
|
+
* default values, and whether they are primary keys.
|
|
1032
|
+
* @param foreignKeys - An optional array of objects defining the foreign key constraints for the table,
|
|
1033
|
+
* including the source column, target table, target column, action on update, and action on delete.
|
|
1034
|
+
* @return The complete SQL string to create the table with the specified structure and constraints.
|
|
1035
|
+
*/
|
|
1036
|
+
createTableSql(tableName, columns, foreignKeys) {
|
|
1037
|
+
const queryLines = [];
|
|
1038
|
+
for (const key in columns) {
|
|
1039
|
+
const columnInfo = columns[key];
|
|
1040
|
+
queryLines.push(this.dialect.columnDefinition(columnInfo.name, columnInfo.sqlType, columnInfo.isPrimaryKey, columnInfo.defaultValue));
|
|
1041
|
+
}
|
|
1042
|
+
if (foreignKeys) for (const foreignKeyInfo of foreignKeys) queryLines.push(this.dialect.foreignKey(foreignKeyInfo.fromColumn, foreignKeyInfo.toTable, foreignKeyInfo.toColumn.toString(), foreignKeyInfo.onUpdate, foreignKeyInfo.onDelete));
|
|
1043
|
+
return this.dialect.createTable(tableName, queryLines);
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* Generates an SQL string to create all provided indexes on a table.
|
|
1047
|
+
*
|
|
1048
|
+
* @param tableName - The name of the table the indexes belong to.
|
|
1049
|
+
* @param indexes - The index definitions.
|
|
1050
|
+
* @return The SQL string to create the indexes (one statement per line).
|
|
1051
|
+
*/
|
|
1052
|
+
createIndexesSql(tableName, indexes) {
|
|
1053
|
+
return (indexes ?? []).map((index) => `${this.dialect.createIndex(tableName, index)}\n`).join("");
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Checks if the specified table does not exist in the list of existing tables.
|
|
1057
|
+
*
|
|
1058
|
+
* @param tableName - The name of the table to check.
|
|
1059
|
+
* @return Returns true if the table does not exist, otherwise false.
|
|
1060
|
+
*/
|
|
1061
|
+
tableDoesNotExists(tableName) {
|
|
1062
|
+
return this.existingTables.indexOf(tableName) == -1;
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Recreates database tables that have been flagged to be recreated in migration data.
|
|
1066
|
+
* This method generated the necessary SQL code for backing up the current table data, dropping and recreating
|
|
1067
|
+
* the tables, and reinserting the preserved data into the recreated tables.
|
|
1068
|
+
*/
|
|
1069
|
+
async recreateTables() {
|
|
1070
|
+
const changes = {
|
|
1071
|
+
up: "\n\n-- Recreate tables\n",
|
|
1072
|
+
down: "\n\n-- Recreate tables\n"
|
|
1073
|
+
};
|
|
1074
|
+
const migrationData = this.migrations.getMigrationData();
|
|
1075
|
+
for (const tableName in migrationData) {
|
|
1076
|
+
if (!migrationData[tableName].recreate) continue;
|
|
1077
|
+
if (!this.dialect.canRecreateTable) throw new Error("SQL dialect does not support recreating tables!");
|
|
1078
|
+
this.migrations.compareWithAllowedMigration(tableName, "recreateTable");
|
|
1079
|
+
const oldColumnList = await this.dialect.getColumnInformation(this.migrations.getOldTableName(tableName));
|
|
1080
|
+
const newColumnList = this.newTables[tableName].columns;
|
|
1081
|
+
const moveableColumns = [];
|
|
1082
|
+
for (const key in newColumnList) if (oldColumnList.hasOwnProperty(key)) moveableColumns.push(newColumnList[key].name);
|
|
1083
|
+
const backupTableName = `${tableName}__backup`;
|
|
1084
|
+
const moveDataQuery = this.dialect.insert(backupTableName, this.dialect.insertValues(moveableColumns, this.dialect.select(tableName, moveableColumns))) + "\n" + this.dialect.dropTable(tableName) + "\n" + this.dialect.renameTable(backupTableName, tableName);
|
|
1085
|
+
const structure = this.newTables[tableName];
|
|
1086
|
+
changes.up += this.createTableSql(backupTableName, structure.columns, structure.foreignKeys) + "\n" + moveDataQuery + "\n" + this.createIndexesSql(tableName, structure.indexes) + "\n";
|
|
1087
|
+
const dbTableName = this.migrations.getOldTableName(tableName);
|
|
1088
|
+
changes.down += this.createTableSql(backupTableName, await this.dialect.getColumnInformation(dbTableName), await this.dialect.getForeignKeys(dbTableName)) + "\n" + moveDataQuery + "\n" + this.createIndexesSql(tableName, await this.dialect.getIndexes(dbTableName));
|
|
1089
|
+
}
|
|
1090
|
+
return changes;
|
|
1091
|
+
}
|
|
1092
|
+
/**
|
|
1093
|
+
* Migrates foreign key constraints for all defined tables.
|
|
1094
|
+
*/
|
|
1095
|
+
async migrateForeignKeys() {
|
|
1096
|
+
let changes = {
|
|
1097
|
+
up: "\n\n-- Foreign keys\n",
|
|
1098
|
+
down: "\n\n-- Foreign keys\n"
|
|
1099
|
+
};
|
|
1100
|
+
for (const tableName in this.newTables) {
|
|
1101
|
+
if (this.migrations.willBeRecreated(tableName) || this.tableDoesNotExists(tableName)) continue;
|
|
1102
|
+
const structure = this.newTables[tableName];
|
|
1103
|
+
const newForeignKeys = structure.foreignKeys ?? [];
|
|
1104
|
+
const oldForeignKeys = await this.dialect.getForeignKeys(this.migrations.getOldTableName(tableName));
|
|
1105
|
+
let checkForNewForeignKeys = true;
|
|
1106
|
+
for (const oldForeignKey of oldForeignKeys) {
|
|
1107
|
+
const newForeignKey = newForeignKeys.find((entry) => entry.fromColumn == oldForeignKey.fromColumn);
|
|
1108
|
+
if (!newForeignKey) {
|
|
1109
|
+
Logger.log(`Foreign key ${oldForeignKey.fromTable}.${oldForeignKey.fromColumn} to ${oldForeignKey.toTable}.${oldForeignKey.toColumn} will be removed!`);
|
|
1110
|
+
this.migrations.compareWithAllowedMigration(tableName, "removeForeignKey", oldForeignKey.fromColumn);
|
|
1111
|
+
if (this.dialect.canAlterForeignKeys) {
|
|
1112
|
+
changes.up += this.dialect.removeForeignKey(oldForeignKey.fromTable, oldForeignKey.fromColumn);
|
|
1113
|
+
changes.down += this.dialect.addForeignKey(oldForeignKey.fromTable, this.dialect.foreignKey(oldForeignKey.fromColumn, oldForeignKey.toTable, oldForeignKey.toColumn, oldForeignKey.onUpdate, oldForeignKey.onDelete));
|
|
1114
|
+
} else {
|
|
1115
|
+
this.migrations.internalRecreate(structure.table, "Dialect does not support altering foreign keys");
|
|
1116
|
+
checkForNewForeignKeys = false;
|
|
1117
|
+
}
|
|
1118
|
+
} else if (!newForeignKey || oldForeignKey.toColumn != newForeignKey.toColumn || (oldForeignKey.onUpdate ?? "NO ACTION") != (newForeignKey.onUpdate ?? "NO ACTION") || (oldForeignKey.onDelete ?? "NO ACTION") != (newForeignKey.onDelete ?? "NO ACTION")) {
|
|
1119
|
+
Logger.log(`Foreign key ${oldForeignKey.fromTable}.${oldForeignKey.fromColumn} to ${oldForeignKey.toTable}.${oldForeignKey.toColumn} will be changed!`);
|
|
1120
|
+
this.migrations.compareWithAllowedMigration(tableName, "alterForeignKey", oldForeignKey.fromColumn);
|
|
1121
|
+
if (this.dialect.canAlterForeignKeys) {
|
|
1122
|
+
changes.up += this.dialect.removeForeignKey(oldForeignKey.fromTable, oldForeignKey.fromColumn) + this.dialect.addForeignKey(newForeignKey.fromTable, this.dialect.foreignKey(newForeignKey.fromColumn, newForeignKey.toTable, newForeignKey.toColumn, newForeignKey.onUpdate, newForeignKey.onDelete));
|
|
1123
|
+
changes.down += this.dialect.addForeignKey(oldForeignKey.fromTable, this.dialect.foreignKey(oldForeignKey.fromColumn, oldForeignKey.toTable, oldForeignKey.toColumn, oldForeignKey.onUpdate, oldForeignKey.onDelete)) + this.dialect.removeForeignKey(newForeignKey.fromTable, newForeignKey.fromColumn);
|
|
1124
|
+
} else {
|
|
1125
|
+
this.migrations.internalRecreate(structure.table, "Dialect does not support altering foreign keys");
|
|
1126
|
+
checkForNewForeignKeys = false;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
if (checkForNewForeignKeys) for (const newForeignKey of newForeignKeys) {
|
|
1131
|
+
if (oldForeignKeys.find((entry) => entry.fromColumn == newForeignKey.fromColumn)) continue;
|
|
1132
|
+
Logger.log(`Foreign key ${newForeignKey.fromTable}.${newForeignKey.fromColumn} to ${newForeignKey.toTable}.${newForeignKey.toColumn} will be added!`);
|
|
1133
|
+
if (this.dialect.canAlterForeignKeys) {
|
|
1134
|
+
changes.up += this.dialect.addForeignKey(newForeignKey.toTable, this.dialect.foreignKey(newForeignKey.fromColumn, newForeignKey.toTable, newForeignKey.toColumn, newForeignKey.onUpdate, newForeignKey.onDelete));
|
|
1135
|
+
changes.down += this.dialect.removeForeignKey(newForeignKey.fromTable, newForeignKey.fromColumn);
|
|
1136
|
+
} else {
|
|
1137
|
+
this.migrations.internalRecreate(structure.table, "Dialect does not support altering foreign keys");
|
|
1138
|
+
break;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
return changes;
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Checks all columns of all tables, creates them if they do not exist in the database and modifies them if needed.
|
|
1146
|
+
* If types, default values or primary key change, the table is recreated
|
|
1147
|
+
*/
|
|
1148
|
+
async migrateColumns() {
|
|
1149
|
+
const changes = {
|
|
1150
|
+
up: "\n\n-- Migrate columns\n",
|
|
1151
|
+
down: "\n\n-- Migrate columns\n"
|
|
1152
|
+
};
|
|
1153
|
+
for (const tableName in this.newTables) {
|
|
1154
|
+
if (this.migrations.willBeRecreated(tableName) || this.tableDoesNotExists(tableName)) continue;
|
|
1155
|
+
const newTableDefinition = this.newTables[tableName];
|
|
1156
|
+
const oldColumnList = await this.dialect.getColumnInformation(this.migrations.getOldTableName(tableName));
|
|
1157
|
+
const oldPrimaryKey = this.getPrimaryKeyColumn(oldColumnList);
|
|
1158
|
+
const oldColumnNewNameIndex = {};
|
|
1159
|
+
for (const key in oldColumnList) oldColumnNewNameIndex[this.migrations.getNewestColumnName(tableName, key)] = oldColumnList[key];
|
|
1160
|
+
const newColumnList = newTableDefinition.columns;
|
|
1161
|
+
const newPrimaryKey = newTableDefinition.primaryKey;
|
|
1162
|
+
if (oldPrimaryKey != newPrimaryKey) {
|
|
1163
|
+
Logger.log(`Primary key in ${tableName} will be changed from ${oldPrimaryKey} to ${newPrimaryKey}!`);
|
|
1164
|
+
this.migrations.compareWithAllowedMigration(tableName, "alterPrimaryKey");
|
|
1165
|
+
if (this.dialect.canAlterPrimaryKey) {
|
|
1166
|
+
if (oldPrimaryKey) {
|
|
1167
|
+
changes.up += this.dialect.removePrimaryKey(tableName, oldPrimaryKey);
|
|
1168
|
+
changes.down += this.dialect.addPrimaryKey(tableName, oldPrimaryKey);
|
|
1169
|
+
}
|
|
1170
|
+
if (newPrimaryKey) {
|
|
1171
|
+
changes.up += this.dialect.addPrimaryKey(tableName, newPrimaryKey.toString());
|
|
1172
|
+
changes.down += this.dialect.removePrimaryKey(tableName, newPrimaryKey.toString());
|
|
1173
|
+
}
|
|
1174
|
+
} else this.migrations.internalRecreate(newTableDefinition.table, "Dialect does not support altering primary keys");
|
|
1175
|
+
continue;
|
|
1176
|
+
}
|
|
1177
|
+
const renamedColumns = this.migrations.getMigrationData()[tableName]?.renamedColumns;
|
|
1178
|
+
for (const key in newColumnList) {
|
|
1179
|
+
const newColumn = newColumnList[key];
|
|
1180
|
+
const oldColumn = oldColumnNewNameIndex[newColumn.name];
|
|
1181
|
+
if (renamedColumns?.find((entry) => entry.newName)) continue;
|
|
1182
|
+
if (oldColumn == void 0) {
|
|
1183
|
+
changes.up += this.dialect.createColumn(tableName, this.dialect.columnDefinition(newColumn.name, newColumn.sqlType, newColumn.isPrimaryKey, newColumn.defaultValue)) + "\n";
|
|
1184
|
+
changes.down += this.dialect.dropColumn(tableName, newColumn.name) + "\n";
|
|
1185
|
+
} else if (this.dialect.canAlterColumnStructure) {
|
|
1186
|
+
changes.up += this.dialect.alterColumnStructure(tableName, newColumn.name, newColumn.sqlType, newColumn.defaultValue);
|
|
1187
|
+
changes.down += this.dialect.alterColumnStructure(tableName, oldColumn.name, oldColumn.sqlType, oldColumn.defaultValue);
|
|
1188
|
+
} else if (newColumn.sqlType != oldColumn.sqlType || newColumn.defaultValue != oldColumn.defaultValue) this.migrations.internalRecreate(newTableDefinition.table, "Table structure was changed");
|
|
1189
|
+
}
|
|
1190
|
+
for (const key in oldColumnList) {
|
|
1191
|
+
const oldColumn = oldColumnList[key];
|
|
1192
|
+
if (newColumnList[this.migrations.getNewestColumnName(tableName, oldColumn.name)] == void 0) {
|
|
1193
|
+
this.migrations.compareWithAllowedMigration(tableName, "dropColumn", oldColumn.name);
|
|
1194
|
+
changes.up += this.dialect.dropColumn(tableName, oldColumn.name) + "\n";
|
|
1195
|
+
changes.down += this.dialect.createColumn(tableName, this.dialect.columnDefinition(oldColumn.name, oldColumn.sqlType, oldColumn.isPrimaryKey, oldColumn.defaultValue)) + "\n";
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
return changes;
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Compares the indexes of all existing tables with their new definitions.
|
|
1203
|
+
* Indexes that are removed or changed have to be allowed (using "dropIndex").
|
|
1204
|
+
* Indexes of tables that will be recreated are only checked, their SQL is generated in {@link recreateTables()}.
|
|
1205
|
+
*
|
|
1206
|
+
* @return SQL changes to drop indexes (needs to run before columns are migrated)
|
|
1207
|
+
* and to create indexes (needs to run after columns were migrated and renamed).
|
|
1208
|
+
*/
|
|
1209
|
+
async migrateIndexes() {
|
|
1210
|
+
const dropped = {
|
|
1211
|
+
up: "\n\n-- Drop indexes\n",
|
|
1212
|
+
down: "\n\n-- Drop indexes\n"
|
|
1213
|
+
};
|
|
1214
|
+
const created = {
|
|
1215
|
+
up: "\n\n-- Create indexes\n",
|
|
1216
|
+
down: "\n\n-- Create indexes\n"
|
|
1217
|
+
};
|
|
1218
|
+
for (const tableName in this.newTables) {
|
|
1219
|
+
if (this.tableDoesNotExists(tableName)) continue;
|
|
1220
|
+
const dbTableName = this.migrations.getOldTableName(tableName);
|
|
1221
|
+
const newIndexes = this.newTables[tableName].indexes ?? [];
|
|
1222
|
+
const oldIndexes = await this.dialect.getIndexes(dbTableName);
|
|
1223
|
+
const isSameIndex = (oldIndex, newIndex) => oldIndex.isUnique == newIndex.isUnique && oldIndex.columns.length == newIndex.columns.length && oldIndex.columns.every((column, i) => this.migrations.getNewestColumnName(tableName, column) == newIndex.columns[i]);
|
|
1224
|
+
const indexesToDrop = [];
|
|
1225
|
+
const indexesToCreate = [];
|
|
1226
|
+
const addedIndexes = newIndexes.filter((newIndex) => !oldIndexes.some((oldIndex) => oldIndex.name == newIndex.name));
|
|
1227
|
+
for (const oldIndex of oldIndexes) {
|
|
1228
|
+
const newIndex = newIndexes.find((entry) => entry.name == oldIndex.name);
|
|
1229
|
+
if (newIndex) {
|
|
1230
|
+
if (isSameIndex(oldIndex, newIndex)) continue;
|
|
1231
|
+
Logger.log(`Index ${oldIndex.name} in ${tableName} will be changed!`);
|
|
1232
|
+
this.migrations.compareWithAllowedMigration(tableName, "dropIndex", oldIndex.name);
|
|
1233
|
+
indexesToCreate.push(newIndex);
|
|
1234
|
+
} else {
|
|
1235
|
+
const renamedIndex = addedIndexes.find((entry) => isSameIndex(oldIndex, entry));
|
|
1236
|
+
if (renamedIndex) {
|
|
1237
|
+
Logger.log(`Index ${oldIndex.name} in ${tableName} will be renamed to ${renamedIndex.name}!`);
|
|
1238
|
+
addedIndexes.splice(addedIndexes.indexOf(renamedIndex), 1);
|
|
1239
|
+
indexesToCreate.push(renamedIndex);
|
|
1240
|
+
} else {
|
|
1241
|
+
Logger.log(`Index ${oldIndex.name} in ${tableName} will be removed!`);
|
|
1242
|
+
this.migrations.compareWithAllowedMigration(tableName, "dropIndex", oldIndex.name);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
indexesToDrop.push(oldIndex);
|
|
1246
|
+
}
|
|
1247
|
+
for (const newIndex of addedIndexes) {
|
|
1248
|
+
Logger.log(`Index ${newIndex.name} in ${tableName} will be added!`);
|
|
1249
|
+
indexesToCreate.push(newIndex);
|
|
1250
|
+
}
|
|
1251
|
+
if (this.migrations.willBeRecreated(tableName)) continue;
|
|
1252
|
+
for (const index of indexesToDrop) {
|
|
1253
|
+
dropped.up += `${this.dialect.dropIndex(tableName, index.name)}\n`;
|
|
1254
|
+
created.down += `${this.dialect.createIndex(dbTableName, index)}\n`;
|
|
1255
|
+
}
|
|
1256
|
+
for (const index of indexesToCreate) {
|
|
1257
|
+
created.up += `${this.dialect.createIndex(tableName, index)}\n`;
|
|
1258
|
+
dropped.down += `${this.dialect.dropIndex(dbTableName, index.name)}\n`;
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
return {
|
|
1262
|
+
dropped,
|
|
1263
|
+
created
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* Retrieves the name of the primary key column from a list of column information.
|
|
1268
|
+
*
|
|
1269
|
+
* @param columnInfoEntries - An array of ColumnInfo objects containing details about each column.
|
|
1270
|
+
* @return The name of the primary key column if found; otherwise, undefined.
|
|
1271
|
+
*/
|
|
1272
|
+
getPrimaryKeyColumn(columnInfoEntries) {
|
|
1273
|
+
for (const key in columnInfoEntries) {
|
|
1274
|
+
const columnInfo = columnInfoEntries[key];
|
|
1275
|
+
if (columnInfo.isPrimaryKey) return columnInfo.name;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Handles the renaming of columns in database tables by generating SQL changes for both applying and reverting the renames.
|
|
1280
|
+
* Skips tables that are marked for recreation.
|
|
1281
|
+
*/
|
|
1282
|
+
renameColumns() {
|
|
1283
|
+
const changes = {
|
|
1284
|
+
up: "\n\n-- Rename columns\n",
|
|
1285
|
+
down: "\n\n-- Rename columns\n"
|
|
1286
|
+
};
|
|
1287
|
+
const migrationData = this.migrations.getMigrationData();
|
|
1288
|
+
for (const tableName in migrationData) {
|
|
1289
|
+
if (migrationData[tableName].recreate) continue;
|
|
1290
|
+
this.migrations.loopRenamedColumns(tableName, (oldColumnName, newColumnName) => {
|
|
1291
|
+
Logger.log(`Column ${tableName}.${oldColumnName} will be renamed to ${tableName}.${newColumnName}!`);
|
|
1292
|
+
changes.up += this.dialect.renameColumn(tableName, oldColumnName, newColumnName);
|
|
1293
|
+
changes.down += this.dialect.renameColumn(tableName, newColumnName, oldColumnName);
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
return changes;
|
|
1297
|
+
}
|
|
1298
|
+
};
|
|
1299
|
+
//#endregion
|
|
1300
|
+
//#region src/lib/tableInfo/decorators/TableClass.ts
|
|
1301
|
+
/**
|
|
1302
|
+
* Decorator function to configure a database table with its name and primary key.
|
|
1303
|
+
*
|
|
1304
|
+
* @param tableName - The name of the database table used in SQL.
|
|
1305
|
+
* @param primaryKey - The property name representing the primary property of the table.
|
|
1306
|
+
*/
|
|
1307
|
+
function TableClass(tableName, primaryKey) {
|
|
1308
|
+
return (table, context) => {
|
|
1309
|
+
const tableStructure = context?.metadata ? getTableStructureFromMetadata(context.metadata) : getTableStructure(table);
|
|
1310
|
+
tableStructure.primaryKey = primaryKey?.toString();
|
|
1311
|
+
tableStructure.table = tableName;
|
|
1312
|
+
if (tableStructure.foreignKeys) for (const foreignKey of tableStructure.foreignKeys) {
|
|
1313
|
+
foreignKey.fromTable = tableName;
|
|
1314
|
+
if (foreignKey.toTable == table.name) foreignKey.toTable = tableName;
|
|
1315
|
+
}
|
|
1316
|
+
const obj = new table();
|
|
1317
|
+
for (const key in obj) {
|
|
1318
|
+
const value = obj[key];
|
|
1319
|
+
const existingEntry = tableStructure.columns[key];
|
|
1320
|
+
const defaultEntry = TableObjHelper.getColumnEntry(key, value);
|
|
1321
|
+
if (!defaultEntry) continue;
|
|
1322
|
+
if (key == primaryKey) defaultEntry.isPrimaryKey = true;
|
|
1323
|
+
tableStructure.columns[key] = {
|
|
1324
|
+
...defaultEntry,
|
|
1325
|
+
...existingEntry
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
Object.defineProperty(table, "name", {
|
|
1329
|
+
value: tableName,
|
|
1330
|
+
writable: false
|
|
1331
|
+
});
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
//#endregion
|
|
1335
|
+
//#region src/lib/tableInfo/TableObj.ts
|
|
1336
|
+
/**
|
|
1337
|
+
* Use this class to define tables for DatabaseInstructions
|
|
1338
|
+
* (as an alternative for Class decorators)
|
|
1339
|
+
*
|
|
1340
|
+
*/
|
|
1341
|
+
var TableObj = class TableObj {
|
|
1342
|
+
IS_TABLE_OBJ = true;
|
|
1343
|
+
tableName;
|
|
1344
|
+
tableStructure = {
|
|
1345
|
+
table: "",
|
|
1346
|
+
primaryKey: void 0,
|
|
1347
|
+
columns: {},
|
|
1348
|
+
foreignKeys: [],
|
|
1349
|
+
indexes: []
|
|
1350
|
+
};
|
|
1351
|
+
constructor(tableName, defaultValues) {
|
|
1352
|
+
const addColumnEntry = (key, value) => {
|
|
1353
|
+
const columnEntry = TableObjHelper.getColumnEntry(key, value);
|
|
1354
|
+
if (!columnEntry) return;
|
|
1355
|
+
this.tableStructure.columns[key] = columnEntry;
|
|
1356
|
+
return columnEntry;
|
|
1357
|
+
};
|
|
1358
|
+
this.tableName = tableName;
|
|
1359
|
+
this.tableStructure.table = tableName;
|
|
1360
|
+
for (const key in defaultValues) {
|
|
1361
|
+
const content = defaultValues[key];
|
|
1362
|
+
if (Array.isArray(content)) {
|
|
1363
|
+
const [value, options] = content;
|
|
1364
|
+
const columnEntry = addColumnEntry(key, value);
|
|
1365
|
+
if (columnEntry) this.applyOptions(columnEntry, options);
|
|
1366
|
+
} else addColumnEntry(key, content);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
applyOptions(entry, options) {
|
|
1370
|
+
for (const keyString in options) {
|
|
1371
|
+
const key = keyString;
|
|
1372
|
+
switch (key) {
|
|
1373
|
+
case "primaryKey":
|
|
1374
|
+
if (this.tableStructure.primaryKey) this.tableStructure.columns[this.tableStructure.primaryKey].isPrimaryKey = false;
|
|
1375
|
+
this.tableStructure.primaryKey = entry.name;
|
|
1376
|
+
entry.isPrimaryKey = true;
|
|
1377
|
+
break;
|
|
1378
|
+
case "dataType":
|
|
1379
|
+
entry.inputType = options[key];
|
|
1380
|
+
break;
|
|
1381
|
+
case "maxCharacterLength":
|
|
1382
|
+
entry.maxLength = options[key];
|
|
1383
|
+
break;
|
|
1384
|
+
default: throw new Error(`Unsupported option "${key}" for ${this.tableName}.${entry.name}`);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* Creates a foreign key relationship between the current table and a target table.
|
|
1390
|
+
*
|
|
1391
|
+
* @param fromColumn - The column in the current table that will serve as the foreign key.
|
|
1392
|
+
* @param toTable - The target table object that the foreign key will reference.
|
|
1393
|
+
* @param toColumn - The column in the target table that the foreign key will reference.
|
|
1394
|
+
* @param options - Optional configurations for the foreign key, specifying actions on update or delete.
|
|
1395
|
+
*/
|
|
1396
|
+
foreignKey(fromColumn, toTable, toColumn, options) {
|
|
1397
|
+
this.tableStructure.foreignKeys.push({
|
|
1398
|
+
fromTable: this.tableName,
|
|
1399
|
+
fromColumn: fromColumn.toString(),
|
|
1400
|
+
toTable: toTable.tableName,
|
|
1401
|
+
toColumn: toColumn.toString(),
|
|
1402
|
+
onUpdate: options?.onUpdate,
|
|
1403
|
+
onDelete: options?.onDelete
|
|
1404
|
+
});
|
|
1405
|
+
return this;
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* Creates an index on one or more columns of the current table.
|
|
1409
|
+
*
|
|
1410
|
+
* @param columns - The columns that will be part of the index (in order).
|
|
1411
|
+
* @param options - Optional configurations for the index.
|
|
1412
|
+
* If no name is provided, the name is generated from the table and column names.
|
|
1413
|
+
*/
|
|
1414
|
+
index(columns, options) {
|
|
1415
|
+
this.tableStructure.indexes.push({
|
|
1416
|
+
name: options?.name,
|
|
1417
|
+
columns: columns.map((column) => column.toString()),
|
|
1418
|
+
isUnique: !!options?.unique
|
|
1419
|
+
});
|
|
1420
|
+
return this;
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* An optional helper function to deal with `TS2589: Type instantiation is excessively deep and possibly infinite. when used as method parameter`
|
|
1424
|
+
* Does nothing in runtime
|
|
1425
|
+
*/
|
|
1426
|
+
sealType() {
|
|
1427
|
+
return this;
|
|
1428
|
+
}
|
|
1429
|
+
static create(tableName, columns) {
|
|
1430
|
+
return new TableObj(tableName, columns);
|
|
1431
|
+
}
|
|
1432
|
+
};
|
|
1433
|
+
//#endregion
|
|
1434
|
+
//#region src/lib/tableInfo/decorators/DataType.ts
|
|
1435
|
+
/**
|
|
1436
|
+
* Decorator function to assign a specific data type to a column.
|
|
1437
|
+
* Should be used if you want to use a data type that does not exist in JavaScript or
|
|
1438
|
+
* if the default value should be NULL
|
|
1439
|
+
*
|
|
1440
|
+
* @param type - The data type to be assigned.
|
|
1441
|
+
*/
|
|
1442
|
+
function DataType(type) {
|
|
1443
|
+
return (table, context) => {
|
|
1444
|
+
const entry = getInputColumnInfo(table, context);
|
|
1445
|
+
entry.inputType = type;
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
//#endregion
|
|
1449
|
+
//#region src/lib/tableInfo/decorators/ForeignKey.ts
|
|
1450
|
+
/**
|
|
1451
|
+
* Decorator function to define a foreign key relationship for a database table.
|
|
1452
|
+
*
|
|
1453
|
+
* @param toTable - The target table class to which the foreign key points.
|
|
1454
|
+
* @param toColumn - The column name in the target table to which the foreign key points.
|
|
1455
|
+
* @param options - Additional options.
|
|
1456
|
+
*/
|
|
1457
|
+
function ForeignKey(toTable, toColumn, options) {
|
|
1458
|
+
return (table, context) => {
|
|
1459
|
+
const metadata = context?.metadata ? getTableStructureFromMetadata(context.metadata) : getTableStructure(table);
|
|
1460
|
+
if (!metadata.foreignKeys) metadata.foreignKeys = [];
|
|
1461
|
+
metadata.foreignKeys.push({
|
|
1462
|
+
fromTable: "",
|
|
1463
|
+
fromColumn: context.name ?? context,
|
|
1464
|
+
toTable: toTable.name,
|
|
1465
|
+
toColumn: toColumn.toString(),
|
|
1466
|
+
onDelete: options?.onDelete,
|
|
1467
|
+
onUpdate: options?.onUpdate
|
|
1468
|
+
});
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
//#endregion
|
|
1472
|
+
//#region src/lib/tableInfo/decorators/Index.ts
|
|
1473
|
+
/**
|
|
1474
|
+
* Decorator function to create an index on one or more columns of a table.
|
|
1475
|
+
* This decorator must be used at the head of the class.
|
|
1476
|
+
*
|
|
1477
|
+
* @param columns - The columns that will be part of the index (in order).
|
|
1478
|
+
* @param options - Additional options. If no name is provided, the name is generated from the table and column names.
|
|
1479
|
+
*/
|
|
1480
|
+
function Index(columns, options) {
|
|
1481
|
+
return (table, context) => {
|
|
1482
|
+
const tableInfo = context?.metadata ? getTableStructureFromMetadata(context.metadata) : getTableStructure(table);
|
|
1483
|
+
if (!tableInfo.indexes) tableInfo.indexes = [];
|
|
1484
|
+
tableInfo.indexes.push({
|
|
1485
|
+
name: options?.name,
|
|
1486
|
+
columns: columns.map((column) => column.toString()),
|
|
1487
|
+
isUnique: !!options?.unique
|
|
1488
|
+
});
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
//#endregion
|
|
1492
|
+
//#region src/lib/dialects/SqliteDialect.ts
|
|
1493
|
+
/**
|
|
1494
|
+
* SQLite-specific syntax for SQL queries
|
|
1495
|
+
*/
|
|
1496
|
+
var SqliteDialect = class extends DefaultSql {
|
|
1497
|
+
types = {
|
|
1498
|
+
text: "TEXT",
|
|
1499
|
+
string: "TEXT",
|
|
1500
|
+
number: "INTEGER",
|
|
1501
|
+
bigint: "INTEGER",
|
|
1502
|
+
boolean: "INTEGER",
|
|
1503
|
+
date: "INTEGER",
|
|
1504
|
+
time: "INTEGER",
|
|
1505
|
+
dateTime: "INTEGER"
|
|
1506
|
+
};
|
|
1507
|
+
canRecreateTable = true;
|
|
1508
|
+
canAlterColumnStructure = false;
|
|
1509
|
+
canAlterForeignKeys = false;
|
|
1510
|
+
canAlterPrimaryKey = false;
|
|
1511
|
+
formatIdentifier(identifier) {
|
|
1512
|
+
return `"${identifier}"`;
|
|
1513
|
+
}
|
|
1514
|
+
async runTransactionWithoutForeignKeys(query) {
|
|
1515
|
+
await this.db.runWriteStatement(`PRAGMA foreign_keys = OFF;`);
|
|
1516
|
+
await this.db.runWriteStatement(`PRAGMA defer_foreign_keys = ON;`);
|
|
1517
|
+
await this.db.runTransaction(query);
|
|
1518
|
+
await this.db.runWriteStatement(`PRAGMA foreign_keys = ON;`);
|
|
1519
|
+
await this.db.runWriteStatement(`PRAGMA foreign_key_check;`);
|
|
1520
|
+
await this.db.runWriteStatement(`PRAGMA defer_foreign_keys = OFF;`);
|
|
1521
|
+
}
|
|
1522
|
+
async getTableNames() {
|
|
1523
|
+
return (await this.db.runReadStatement("SELECT name FROM sqlite_master WHERE type = 'table'")).map((obj) => obj.name);
|
|
1524
|
+
}
|
|
1525
|
+
async getColumnInformation(tableName) {
|
|
1526
|
+
const data = await this.db.runReadStatement(`PRAGMA table_info(${tableName})`);
|
|
1527
|
+
const output = {};
|
|
1528
|
+
for (const entry of data) output[entry["name"]] = {
|
|
1529
|
+
name: entry["name"],
|
|
1530
|
+
sqlType: entry["type"],
|
|
1531
|
+
defaultValue: entry["dflt_value"] ?? this.nullType,
|
|
1532
|
+
isPrimaryKey: entry["pk"] == "1"
|
|
1533
|
+
};
|
|
1534
|
+
return output;
|
|
1535
|
+
}
|
|
1536
|
+
formatValueToSql(value, type) {
|
|
1537
|
+
function toDate(value) {
|
|
1538
|
+
return value instanceof Date ? value : new Date(value);
|
|
1539
|
+
}
|
|
1540
|
+
switch (type) {
|
|
1541
|
+
case "boolean": return value ? "1" : "0";
|
|
1542
|
+
case "date":
|
|
1543
|
+
case "time":
|
|
1544
|
+
case "dateTime": return toDate(value).getTime().toString();
|
|
1545
|
+
default: return super.formatValueToSql(value, type);
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
async getForeignKeys(tableName) {
|
|
1549
|
+
return (await this.db.runReadStatement(`PRAGMA foreign_key_list(${tableName});`)).map((entry) => {
|
|
1550
|
+
return {
|
|
1551
|
+
fromTable: tableName,
|
|
1552
|
+
fromColumn: entry["from"],
|
|
1553
|
+
toTable: entry["table"],
|
|
1554
|
+
toColumn: entry["to"],
|
|
1555
|
+
onUpdate: entry["on_update"] ?? "NO ACTION",
|
|
1556
|
+
onDelete: entry["on_delete"] ?? "NO ACTION"
|
|
1557
|
+
};
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
async getIndexes(tableName) {
|
|
1561
|
+
const data = await this.db.runReadStatement(`SELECT il.name AS index_name, il."unique" AS is_unique, ii.name AS column_name
|
|
1562
|
+
FROM pragma_index_list('${tableName}') AS il JOIN pragma_index_info(il.name) AS ii
|
|
1563
|
+
WHERE il.origin = 'c'
|
|
1564
|
+
ORDER BY il.name, ii.seqno;`);
|
|
1565
|
+
return this.rowsToIndexInfo(data);
|
|
1566
|
+
}
|
|
1567
|
+
async setChanges(fromVersion, toVersion, changes) {
|
|
1568
|
+
await this.db.runTransaction(`PRAGMA user_version = ${toVersion};`);
|
|
1569
|
+
await super.setChanges(fromVersion, toVersion, changes);
|
|
1570
|
+
}
|
|
1571
|
+
async getVersion() {
|
|
1572
|
+
return (await this.db.runReadStatement(`PRAGMA user_version;`))[0].user_version;
|
|
1573
|
+
}
|
|
1574
|
+
async rollbackHistory(toVersion) {
|
|
1575
|
+
await this.db.runTransaction(`PRAGMA user_version = ${toVersion};`);
|
|
1576
|
+
await super.rollbackHistory(toVersion);
|
|
1577
|
+
}
|
|
1578
|
+
};
|
|
1579
|
+
//#endregion
|
|
1580
|
+
//#region src/lib/dialects/PostgresDialect.ts
|
|
1581
|
+
var PostgresDialect = class extends DefaultSql {
|
|
1582
|
+
canRecreateTable = false;
|
|
1583
|
+
canAlterColumnStructure = true;
|
|
1584
|
+
canAlterForeignKeys = true;
|
|
1585
|
+
canAlterPrimaryKey = true;
|
|
1586
|
+
types = {
|
|
1587
|
+
text: "TEXT",
|
|
1588
|
+
string: "VARCHAR",
|
|
1589
|
+
number: "NUMERIC",
|
|
1590
|
+
bigint: "BIGINT",
|
|
1591
|
+
boolean: "BOOLEAN",
|
|
1592
|
+
date: "DATE",
|
|
1593
|
+
time: "TIME",
|
|
1594
|
+
dateTime: "TIMESTAMP"
|
|
1595
|
+
};
|
|
1596
|
+
formatIdentifier(identifier) {
|
|
1597
|
+
return `"${identifier}"`;
|
|
1598
|
+
}
|
|
1599
|
+
alterColumnStructure(tableName, columnName, sqlType, defaultValue) {
|
|
1600
|
+
return `ALTER TABLE ${tableName} ALTER COLUMN ${columnName} TYPE ${sqlType}; ALTER TABLE ${tableName} ALTER COLUMN ${columnName} ${defaultValue ? `SET DEFAULT ${defaultValue}` : "DROP DEFAULT"};`;
|
|
1601
|
+
}
|
|
1602
|
+
async runTransactionWithoutForeignKeys(query) {
|
|
1603
|
+
await this.db.runTransaction(`SET session_replication_role = 'replica'; ${query}; SET session_replication_role = 'origin';`);
|
|
1604
|
+
}
|
|
1605
|
+
addForeignKey(fromTableName, foreignKey) {
|
|
1606
|
+
return `ALTER TABLE ${this.formatIdentifier(fromTableName)} ADD CONSTRAINT ${this.formatIdentifier(fromTableName)} ${foreignKey};`;
|
|
1607
|
+
}
|
|
1608
|
+
removeForeignKey(tableName, foreignKeyName) {
|
|
1609
|
+
return `ALTER TABLE ${this.formatIdentifier(tableName)} DROP CONSTRAINT ${foreignKeyName};`;
|
|
1610
|
+
}
|
|
1611
|
+
async getTableNames() {
|
|
1612
|
+
return (await this.db.runReadStatement("SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';")).map((row) => row.table_name);
|
|
1613
|
+
}
|
|
1614
|
+
async getColumnInformation(tableName) {
|
|
1615
|
+
const data = await this.db.runReadStatement(`SELECT c.column_name as column_name, data_type, column_default, constraint_type FROM information_schema.columns c LEFT JOIN information_schema.key_column_usage cu ON cu.table_name = c.table_name AND cu.column_name = c.column_name LEFT JOIN information_schema.table_constraints tc ON tc.constraint_name = cu.constraint_name WHERE c.table_schema = 'public' AND c.table_name = '${tableName}';`);
|
|
1616
|
+
const output = {};
|
|
1617
|
+
for (const entry of data) {
|
|
1618
|
+
const defaultValue = entry["column_default"]?.match(/^'(.+)'::.+$/);
|
|
1619
|
+
let dataType = entry["data_type"].toUpperCase();
|
|
1620
|
+
switch (dataType) {
|
|
1621
|
+
case "INTEGER":
|
|
1622
|
+
dataType = this.types.number;
|
|
1623
|
+
break;
|
|
1624
|
+
case "CHARACTER VARYING":
|
|
1625
|
+
dataType = this.types.string;
|
|
1626
|
+
break;
|
|
1627
|
+
case "TIMESTAMP WITHOUT TIME ZONE":
|
|
1628
|
+
case "TIMESTAMP WITH TIME ZONE":
|
|
1629
|
+
dataType = this.types.dateTime;
|
|
1630
|
+
break;
|
|
1631
|
+
case "TIME WITHOUT TIME ZONE":
|
|
1632
|
+
case "TIME WITH TIME ZONE":
|
|
1633
|
+
dataType = this.types.time;
|
|
1634
|
+
break;
|
|
1635
|
+
case "DATE WITHOUT TIME ZONE":
|
|
1636
|
+
case "DATE WITH TIME ZONE": dataType = this.types.date;
|
|
1637
|
+
}
|
|
1638
|
+
output[entry["column_name"]] = {
|
|
1639
|
+
name: entry["column_name"],
|
|
1640
|
+
sqlType: dataType,
|
|
1641
|
+
defaultValue: defaultValue ? `'${defaultValue[1]}'` : entry["column_default"] ?? this.nullType,
|
|
1642
|
+
isPrimaryKey: entry["constraint_type"] == "PRIMARY KEY"
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
return output;
|
|
1646
|
+
}
|
|
1647
|
+
addPrimaryKey(tableName, columnName) {
|
|
1648
|
+
return `ALTER TABLE ${tableName} ADD PRIMARY KEY (${columnName});\n`;
|
|
1649
|
+
}
|
|
1650
|
+
removePrimaryKey(tableName, columnName) {
|
|
1651
|
+
return `ALTER TABLE ${tableName} DROP CONSTRAINT ${columnName};\n`;
|
|
1652
|
+
}
|
|
1653
|
+
async getIndexes(tableName) {
|
|
1654
|
+
const data = await this.db.runReadStatement(`SELECT i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
1655
|
+
FROM pg_index AS ix
|
|
1656
|
+
JOIN pg_class AS t ON t.oid = ix.indrelid
|
|
1657
|
+
JOIN pg_class AS i ON i.oid = ix.indexrelid
|
|
1658
|
+
JOIN pg_namespace AS n ON n.oid = t.relnamespace
|
|
1659
|
+
JOIN pg_attribute AS a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
|
|
1660
|
+
WHERE n.nspname = 'public' AND t.relname = '${tableName}' AND NOT ix.indisprimary
|
|
1661
|
+
AND NOT EXISTS (SELECT 1 FROM pg_constraint AS c WHERE c.conindid = ix.indexrelid)
|
|
1662
|
+
ORDER BY i.relname, array_position(ix.indkey::int2[], a.attnum);`);
|
|
1663
|
+
return this.rowsToIndexInfo(data);
|
|
1664
|
+
}
|
|
1665
|
+
async getForeignKeys(tableName) {
|
|
1666
|
+
return (await this.db.runReadStatement(`SELECT
|
|
1667
|
+
tc.table_name AS child_table,
|
|
1668
|
+
kcu.column_name AS child_column,
|
|
1669
|
+
ccu.table_name AS parent_table,
|
|
1670
|
+
ccu.column_name AS parent_column,
|
|
1671
|
+
rc.update_rule AS update_rule,
|
|
1672
|
+
rc.delete_rule AS delete_rule
|
|
1673
|
+
FROM information_schema.table_constraints AS tc
|
|
1674
|
+
JOIN information_schema.key_column_usage AS kcu
|
|
1675
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
1676
|
+
JOIN information_schema.constraint_column_usage AS ccu
|
|
1677
|
+
ON tc.constraint_name = ccu.constraint_name
|
|
1678
|
+
JOIN information_schema.referential_constraints AS rc
|
|
1679
|
+
ON tc.constraint_name=rc.constraint_name
|
|
1680
|
+
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = '${tableName}';`)).map((entry) => {
|
|
1681
|
+
return {
|
|
1682
|
+
fromTable: tableName,
|
|
1683
|
+
fromColumn: entry["child_column"],
|
|
1684
|
+
toTable: entry["parent_table"],
|
|
1685
|
+
toColumn: entry["parent_column"],
|
|
1686
|
+
onUpdate: entry["update_rule"],
|
|
1687
|
+
onDelete: entry["delete_rule"]
|
|
1688
|
+
};
|
|
1689
|
+
});
|
|
1690
|
+
}
|
|
1691
|
+
};
|
|
1692
|
+
//#endregion
|
|
1693
|
+
//#region src/lib/dialects/MySqlDialect.ts
|
|
1694
|
+
var MySqlDialect = class extends DefaultSql {
|
|
1695
|
+
canRecreateTable = true;
|
|
1696
|
+
canAlterColumnStructure = true;
|
|
1697
|
+
canAlterForeignKeys = true;
|
|
1698
|
+
canAlterPrimaryKey = true;
|
|
1699
|
+
types = {
|
|
1700
|
+
text: "TEXT",
|
|
1701
|
+
string: "VARCHAR",
|
|
1702
|
+
number: "INT",
|
|
1703
|
+
bigint: "BIGINT",
|
|
1704
|
+
boolean: "TINYINT(1)",
|
|
1705
|
+
date: "DATE",
|
|
1706
|
+
time: "TIME",
|
|
1707
|
+
dateTime: "DATETIME"
|
|
1708
|
+
};
|
|
1709
|
+
formatValueToSql(value, type) {
|
|
1710
|
+
switch (type) {
|
|
1711
|
+
case "boolean": return value ? "1" : "0";
|
|
1712
|
+
default: return super.formatValueToSql(value, type);
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
getSqlType(dataType, columnInfo) {
|
|
1716
|
+
switch (dataType) {
|
|
1717
|
+
case "string": return this.types[dataType] + `(${columnInfo?.maxLength ?? 100})`;
|
|
1718
|
+
default: return super.getSqlType(dataType, columnInfo);
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
alterColumnStructure(tableName, columnName, sqlType, defaultValue) {
|
|
1722
|
+
const typeQuery = `ALTER TABLE ${tableName} MODIFY COLUMN ${columnName} ${sqlType}`;
|
|
1723
|
+
return defaultValue ? `${typeQuery} DEFAULT ${defaultValue}` : `${typeQuery}; ALTER TABLE ${tableName} ALTER ${columnName} DROP DEFAULT;`;
|
|
1724
|
+
}
|
|
1725
|
+
async runTransactionWithoutForeignKeys(query) {
|
|
1726
|
+
await this.db.runWriteStatement("SET FOREIGN_KEY_CHECKS = 0;");
|
|
1727
|
+
await this.db.runTransaction(query);
|
|
1728
|
+
await this.db.runWriteStatement("SET FOREIGN_KEY_CHECKS = 1;");
|
|
1729
|
+
}
|
|
1730
|
+
addForeignKey(fromTableName, foreignKey) {
|
|
1731
|
+
return `ALTER TABLE ${fromTableName} ADD ${foreignKey};`;
|
|
1732
|
+
}
|
|
1733
|
+
removeForeignKey(tableName, foreignKeyName) {
|
|
1734
|
+
return `ALTER TABLE ${tableName} DROP FOREIGN KEY ${foreignKeyName};`;
|
|
1735
|
+
}
|
|
1736
|
+
addPrimaryKey(tableName, columnName) {
|
|
1737
|
+
return `ALTER TABLE ${tableName} PRIMARY KEY (${columnName});`;
|
|
1738
|
+
}
|
|
1739
|
+
removePrimaryKey(tableName, _columnName) {
|
|
1740
|
+
return `ALTER TABLE ${tableName} PRIMARY KEY;`;
|
|
1741
|
+
}
|
|
1742
|
+
async getForeignKeys(tableName) {
|
|
1743
|
+
return (await this.db.runReadStatement(`SELECT
|
|
1744
|
+
info.TABLE_NAME, info.COLUMN_NAME, info.REFERENCED_TABLE_NAME, info.REFERENCED_COLUMN_NAME, constr.UPDATE_RULE, constr.DELETE_RULE
|
|
1745
|
+
FROM information_schema.KEY_COLUMN_USAGE AS info INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS AS constr ON info.CONSTRAINT_NAME = constr.CONSTRAINT_NAME
|
|
1746
|
+
WHERE info.REFERENCED_TABLE_SCHEMA = (SELECT DATABASE()) AND info.TABLE_NAME = '${tableName}';`)).map((entry) => {
|
|
1747
|
+
return {
|
|
1748
|
+
fromTable: tableName,
|
|
1749
|
+
fromColumn: entry["COLUMN_NAME"],
|
|
1750
|
+
toTable: entry["REFERENCED_TABLE_NAME"],
|
|
1751
|
+
toColumn: entry["REFERENCED_COLUMN_NAME"],
|
|
1752
|
+
onUpdate: entry["UPDATE_RULE"],
|
|
1753
|
+
onDelete: entry["DELETE_RULE"]
|
|
1754
|
+
};
|
|
1755
|
+
});
|
|
1756
|
+
}
|
|
1757
|
+
dropIndex(tableName, indexName) {
|
|
1758
|
+
return `DROP INDEX ${this.formatIdentifier(indexName)} ON ${this.formatIdentifier(tableName)};`;
|
|
1759
|
+
}
|
|
1760
|
+
async getIndexes(tableName) {
|
|
1761
|
+
const data = await this.db.runReadStatement(`SELECT s.INDEX_NAME AS index_name, s.NON_UNIQUE = 0 AS is_unique, s.COLUMN_NAME AS column_name
|
|
1762
|
+
FROM information_schema.STATISTICS AS s
|
|
1763
|
+
WHERE s.TABLE_SCHEMA = (SELECT DATABASE()) AND s.TABLE_NAME = '${tableName}' AND s.INDEX_NAME <> 'PRIMARY'
|
|
1764
|
+
AND NOT EXISTS (
|
|
1765
|
+
SELECT 1 FROM information_schema.KEY_COLUMN_USAGE AS k
|
|
1766
|
+
WHERE k.TABLE_SCHEMA = s.TABLE_SCHEMA AND k.TABLE_NAME = s.TABLE_NAME AND k.REFERENCED_TABLE_NAME IS NOT NULL
|
|
1767
|
+
AND (k.CONSTRAINT_NAME = s.INDEX_NAME OR k.COLUMN_NAME = s.INDEX_NAME)
|
|
1768
|
+
)
|
|
1769
|
+
ORDER BY s.INDEX_NAME, s.SEQ_IN_INDEX;`);
|
|
1770
|
+
return this.rowsToIndexInfo(data);
|
|
1771
|
+
}
|
|
1772
|
+
async getTableNames() {
|
|
1773
|
+
return (await this.db.runReadStatement("SHOW TABLES")).map((entry) => Object.values(entry)[0]);
|
|
1774
|
+
}
|
|
1775
|
+
async getColumnInformation(tableName) {
|
|
1776
|
+
const data = await this.db.runReadStatement(`SHOW COLUMNS FROM ${tableName};`);
|
|
1777
|
+
const output = {};
|
|
1778
|
+
for (const entry of data) {
|
|
1779
|
+
const sqlType = entry["Type"].toUpperCase();
|
|
1780
|
+
const info = {
|
|
1781
|
+
name: entry["Field"],
|
|
1782
|
+
sqlType,
|
|
1783
|
+
isPrimaryKey: entry["Key"] == "PRI"
|
|
1784
|
+
};
|
|
1785
|
+
switch (sqlType.substring(0, 4)) {
|
|
1786
|
+
case "TEXT":
|
|
1787
|
+
case "VARC":
|
|
1788
|
+
case "DATE":
|
|
1789
|
+
case "TIME":
|
|
1790
|
+
info.defaultValue = entry["Default"] ? `'${entry["Default"]}'` : this.nullType;
|
|
1791
|
+
break;
|
|
1792
|
+
default: info.defaultValue = entry["Default"] ?? this.nullType;
|
|
1793
|
+
}
|
|
1794
|
+
output[entry["Field"]] = info;
|
|
1795
|
+
}
|
|
1796
|
+
return output;
|
|
1797
|
+
}
|
|
1798
|
+
};
|
|
1799
|
+
//#endregion
|
|
1800
|
+
//#region src/lib/getDialect.ts
|
|
1801
|
+
function getDialect(db, dialect) {
|
|
1802
|
+
switch (dialect) {
|
|
1803
|
+
case "Sqlite": return new SqliteDialect(db);
|
|
1804
|
+
case "Postgres": return new PostgresDialect(db);
|
|
1805
|
+
case "MySql": return new MySqlDialect(db);
|
|
1806
|
+
default: throw new Error(`Unknown dialect ${dialect}`);
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
//#endregion
|
|
1810
|
+
//#region src/index.ts
|
|
1811
|
+
/**
|
|
1812
|
+
* Executes a database migration based on the provided database connection and migration instructions.
|
|
1813
|
+
*
|
|
1814
|
+
* @param db - The database access object used to interact with the database.
|
|
1815
|
+
* @param dbInstructions - The migration instructions, including target version, logger mode, and dialect.
|
|
1816
|
+
* @return A promise that resolves when the migration process is successfully completed.
|
|
1817
|
+
*/
|
|
1818
|
+
async function runMigration(db, dbInstructions) {
|
|
1819
|
+
Logger.setMode(dbInstructions.loggerMode);
|
|
1820
|
+
const dialect = getDialect(db, dbInstructions.dialect);
|
|
1821
|
+
const migration = await new MigrationManager(dialect).generateSqlChanges(dbInstructions);
|
|
1822
|
+
if (migration) {
|
|
1823
|
+
await db.createBackup?.(`from_${migration.fromVersion}_to_${dbInstructions.version}`);
|
|
1824
|
+
await dialect.runTransactionWithoutForeignKeys(migration.changes.up);
|
|
1825
|
+
await dialect.setChanges(migration.fromVersion, dbInstructions.version, migration.changes);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
1829
|
+
* Rolls back the database to the provided toVersion
|
|
1830
|
+
* @param dbAccess - Access to the database.
|
|
1831
|
+
* @param toVersion - the version to which the database should be upgraded to.
|
|
1832
|
+
* @param dialect - the dialect that should be used for the database. Usually is the value defined in DatabaseInstructions
|
|
1833
|
+
* @param loggerMode - defines how much should be logged to the console.
|
|
1834
|
+
*/
|
|
1835
|
+
async function rollback(dbAccess, toVersion, dialect, loggerMode) {
|
|
1836
|
+
Logger.setMode(loggerMode);
|
|
1837
|
+
const sql = getDialect(dbAccess, dialect);
|
|
1838
|
+
const fromVersion = await sql.getVersion();
|
|
1839
|
+
await dbAccess.createBackup?.(`from_${fromVersion}_to_${toVersion}`);
|
|
1840
|
+
Logger.log(`Rolling back from ${fromVersion} to ${toVersion}`);
|
|
1841
|
+
let version = fromVersion;
|
|
1842
|
+
while (version > toVersion) {
|
|
1843
|
+
const changes = await sql.getChanges(version);
|
|
1844
|
+
if (!changes) throw new Error(`Unexpected error! No changes were found from version ${version} (fromVersion: ${fromVersion}, toVersion: ${toVersion})`);
|
|
1845
|
+
else if (changes.fromVersion == version) throw new Error(`Saved changes do not change the database version (${version})`);
|
|
1846
|
+
Logger.debug(changes.down);
|
|
1847
|
+
await sql.runTransactionWithoutForeignKeys(changes.down);
|
|
1848
|
+
version = changes.fromVersion;
|
|
1849
|
+
}
|
|
1850
|
+
if (version < toVersion) Logger.warn(`There was no entry for version ${toVersion}. Rolled back to version ${version}`);
|
|
1851
|
+
await sql.rollbackHistory(version);
|
|
1852
|
+
return version;
|
|
1853
|
+
}
|
|
1854
|
+
//#endregion
|
|
1855
|
+
exports.DataType = DataType;
|
|
1856
|
+
exports.ForeignKey = ForeignKey;
|
|
1857
|
+
exports.Index = Index;
|
|
1858
|
+
exports.TableClass = TableClass;
|
|
1859
|
+
exports.TableObj = TableObj;
|
|
1860
|
+
exports.rollback = rollback;
|
|
1861
|
+
exports.runMigration = runMigration;
|