sqlmorpheus 0.2.7 → 1.0.1

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