sqlmorpheus 0.1.8 → 0.1.10

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.js CHANGED
@@ -72,31 +72,36 @@ function getTableInfoFromMetadata(metadata) {
72
72
  // src/lib/TableStructureGenerator.ts
73
73
  var TableStructureGenerator = class {
74
74
  dialect;
75
- tables = {};
76
- constructor(dbContext, dialect) {
75
+ dbInstructions;
76
+ constructor(dbInstructions, dialect) {
77
77
  this.dialect = dialect;
78
- if (dbContext.tables.length) {
78
+ this.dbInstructions = dbInstructions;
79
+ }
80
+ generateTableStructure() {
81
+ if (this.dbInstructions.tables.length) {
79
82
  const tableObjects = {};
80
- for (const table of dbContext.tables) {
83
+ for (const table of this.dbInstructions.tables) {
81
84
  tableObjects[table.name] = { columns: new table(), tableInfo: getTableInfo(table) };
82
85
  }
83
- this.getExpectedStructure(tableObjects);
86
+ return this.getExpectedStructure(tableObjects);
84
87
  } else {
85
- const tableObjects = dbContext.tables;
86
- this.getExpectedStructure(tableObjects);
88
+ const tableObjects = this.dbInstructions.tables;
89
+ return this.getExpectedStructure(tableObjects);
87
90
  }
88
91
  }
89
92
  getExpectedStructure(tableObjects) {
93
+ const tables = {};
90
94
  for (const tableName in tableObjects) {
91
95
  const obj = tableObjects[tableName];
92
96
  const tableInfo = obj.tableInfo;
93
- this.tables[tableName] = {
97
+ tables[tableName] = {
94
98
  table: tableName,
95
99
  primaryKey: tableInfo?.primaryKey,
96
100
  columns: this.getColumns(obj.columns, tableInfo?.primaryKey),
97
101
  foreignKeys: tableInfo?.foreignKeys
98
102
  };
99
103
  }
104
+ return tables;
100
105
  }
101
106
  getColumns(obj, primaryKey) {
102
107
  const columns = [];
@@ -140,38 +145,32 @@ var TableStructureGenerator = class {
140
145
 
141
146
  // src/lib/exceptions/NotAllowedException.ts
142
147
  var NotAllowedException = class extends Error {
143
- constructor(version, tableName, type) {
144
- const information = `You have to enable "${type}" for version "${version}" and table "${tableName}"`;
145
- switch (type) {
146
- case "continueWithoutRollback":
147
- super(`Some changes can not be rolled back automatically. ${information}`);
148
- break;
149
- case "dropColumn":
150
- super(`Not allowed to drop column. ${information}`);
151
- break;
152
- case "dropTable":
153
- super(`Not allowed to drop table. ${information}`);
154
- break;
155
- case "recreateTable":
156
- super(`Not allowed to recreate table. ${information}`);
157
- break;
158
- case "alterForeignKey":
159
- super(`Not allowed to alter existing foreign key. ${information}`);
160
- break;
161
- case "alterPrimaryKey":
162
- super(`Not allowed to alter primary key. ${information}`);
163
- break;
164
- case "removeForeignKey":
165
- super(`Not allowed to remove existing foreign key. ${information}`);
166
- break;
148
+ constructor(entries) {
149
+ let message = "Some destructive changes need to be confirmed. In preMigrations() run:";
150
+ for (const entry of entries) {
151
+ message += `
152
+ migrations.allowMigration(${entry.version}, "${entry.tableName}", "${entry.type}");`;
167
153
  }
154
+ super(`${message}
155
+
156
+ `);
168
157
  }
169
158
  };
170
159
 
171
160
  // src/lib/typings/Migrations.ts
172
161
  var Migrations = class {
173
- migrationData = {};
162
+ toVersion = 0;
174
163
  alwaysAllowed = {};
164
+ fromVersion = 0;
165
+ migrationData = {};
166
+ notAllowedChanges = [];
167
+ reset(dbInstructions, fromVersion) {
168
+ this.fromVersion = fromVersion;
169
+ this.migrationData = {};
170
+ this.toVersion = dbInstructions.version;
171
+ this.alwaysAllowed = dbInstructions.alwaysAllowedMigrations ?? {};
172
+ this.notAllowedChanges = [];
173
+ }
175
174
  getEntry(table) {
176
175
  const tableName = this.getTableName(table);
177
176
  if (!this.migrationData.hasOwnProperty(tableName)) {
@@ -186,30 +185,40 @@ var Migrations = class {
186
185
  getTableName(table) {
187
186
  return typeof table == "string" ? table : table.name;
188
187
  }
189
- alwaysAllow(...allowedMigrations) {
190
- for (const key of allowedMigrations) {
191
- this.alwaysAllowed[key] = true;
188
+ verifyMigration(tableName, type) {
189
+ if (!this.migrationData[tableName]?.allowedMigrations[type] && !this.alwaysAllowed[type])
190
+ this.notAllowedChanges.push({ version: this.toVersion, tableName, type });
191
+ }
192
+ checkIfAllowed(throwIfNotAllowed) {
193
+ if (!this.notAllowedChanges.length)
194
+ return true;
195
+ const exception = new NotAllowedException(this.notAllowedChanges);
196
+ if (throwIfNotAllowed)
197
+ throw exception;
198
+ else {
199
+ console.error(exception.message);
200
+ return false;
192
201
  }
193
202
  }
194
203
  allowMigration(version, table, ...allowedMigrations) {
204
+ if (version < this.fromVersion || version > this.toVersion)
205
+ return;
195
206
  const entry = this.getEntry(table);
196
- if (!entry.allowedMigrations.hasOwnProperty(version))
197
- entry.allowedMigrations[version] = {};
198
207
  for (const key of allowedMigrations) {
199
- this.alwaysAllowed[key] = true;
208
+ entry.allowedMigrations[key] = true;
200
209
  }
201
210
  }
202
- throwIfNotAllowed(version, tableName, type) {
203
- if (!(this.migrationData[tableName]?.allowedMigrations[version] ?? this.alwaysAllowed)[type])
204
- throw new NotAllowedException(version, tableName, type);
205
- }
206
- renameTable(oldTableName, newTable) {
211
+ renameTable(version, oldTableName, newTable) {
212
+ if (version < this.fromVersion || version > this.toVersion)
213
+ return;
207
214
  const entry = this.getEntry(newTable);
208
215
  entry.recreate = true;
209
216
  if (!entry.oldTableName)
210
217
  entry.oldTableName = oldTableName;
211
218
  }
212
- renameColumn(table, oldColumn, newColumn) {
219
+ renameColumn(version, table, oldColumn, newColumn) {
220
+ if (version < this.fromVersion || version > this.toVersion)
221
+ return;
213
222
  const entry = this.getEntry(table);
214
223
  const existingColumnEntry = entry.renamedColumns.find((entry2) => entry2[entry2.length - 1] == oldColumn);
215
224
  if (existingColumnEntry)
@@ -217,10 +226,15 @@ var Migrations = class {
217
226
  else
218
227
  entry.renamedColumns.push([oldColumn, newColumn]);
219
228
  }
220
- recreateTable(table) {
229
+ recreateTableImp(table) {
221
230
  const entry = this.getEntry(table);
222
231
  entry.recreate = true;
223
232
  }
233
+ recreateTable(version, table) {
234
+ if (version < this.fromVersion || version > this.toVersion)
235
+ return;
236
+ this.recreateTableImp(table);
237
+ }
224
238
  getMigrationData() {
225
239
  return this.migrationData;
226
240
  }
@@ -235,7 +249,7 @@ var Migrations = class {
235
249
  }
236
250
  }
237
251
  getUpdatedColumnName(tableName, oldColumnName) {
238
- const columnNames = this.migrationData[tableName].renamedColumns.find((columns) => columns[0] == oldColumnName);
252
+ const columnNames = this.migrationData[tableName]?.renamedColumns.find((columns) => columns[0] == oldColumnName);
239
253
  return columnNames ? columnNames[columnNames.length - 1] : oldColumnName;
240
254
  }
241
255
  willBeRecreated(tableName) {
@@ -243,827 +257,836 @@ var Migrations = class {
243
257
  }
244
258
  };
245
259
 
246
- // src/lib/MigrationHistoryManager.ts
247
- var import_node_fs = require("fs");
248
- var import_fs = require("fs");
249
- var FILENAME_UP_PREFIX = "up_to_";
250
- var FILENAME_DOWN_PREFIX = "down_to_";
251
- var MigrationHistoryManager = class {
252
- configPath;
253
- migrationsPath;
254
- constructor(configPath) {
255
- this.configPath = configPath;
256
- this.migrationsPath = `${configPath}/migrations`;
257
- (0, import_node_fs.mkdirSync)(this.configPath, { recursive: true });
258
- (0, import_node_fs.mkdirSync)(this.migrationsPath, { recursive: true });
260
+ // src/lib/MigrationManager.ts
261
+ var MigrationManager = class {
262
+ migrations = new Migrations();
263
+ newTables = {};
264
+ existingTables = [];
265
+ dialect;
266
+ constructor(dialect) {
267
+ this.dialect = dialect;
259
268
  }
260
269
  /**
261
- * Creates migration history files for upgrading and downgrading database schemas.
270
+ * Generates the SQL changes required to migrate a database from its current version
271
+ * to the target version defined in the database instructions. Handles the creation
272
+ * and deletion of tables, migration of foreign keys and columns, renaming of columns,
273
+ * and recreating tables, along with executing any pre- and post-migration custom logic.
262
274
  *
263
- * @param fromVersion - The current version number of the database.
264
- * @param toVersion - The target version number for the migration.
265
- * @param changes - An object containing the SQL changes for upgrading (`changes.up`) and downgrading (`changes.down`).
266
- * @param overwriteExisting - A flag that determines if existing migration files should be overwritten. Defaults to `false`.
275
+ * @return A promise that resolves to an object containing the SQL
276
+ * changes for the migration (`up` and `down` changes) or null if no migration is required.
277
+ * Throws an error in scenarios such as attempting to migrate to a lower version
278
+ * or an invalid starting version.
267
279
  */
268
- createMigrationHistory(fromVersion, toVersion, changes, overwriteExisting) {
269
- const upPath = `${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`;
270
- const downPath = `${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${fromVersion}.sql`;
271
- if ((0, import_node_fs.existsSync)(upPath) && !overwriteExisting)
272
- throw new Error(`Migration ${upPath} already exists!`);
273
- else if ((0, import_node_fs.existsSync)(downPath) && !overwriteExisting)
274
- throw new Error(`Migration ${downPath} already exists!`);
275
- Logger.log(`Save migrations to ${this.migrationsPath}`);
276
- (0, import_node_fs.writeFileSync)(`${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`, `-- From: Version ${fromVersion}
277
- -- To: Version ${toVersion}
278
- ${changes.up}`, { encoding: "utf-8" });
279
- (0, import_node_fs.writeFileSync)(`${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${fromVersion}.sql`, `-- From: Version ${toVersion}
280
- -- To: Version ${fromVersion}
281
- ${changes.down}`, { encoding: "utf-8" });
280
+ async generateSqlChanges(dbInstructions) {
281
+ const fromVersion = await this.dialect.getVersion();
282
+ const toVersion = dbInstructions.version;
283
+ if (toVersion <= 0)
284
+ throw new Error("Cannot migrate to version 0 or lower");
285
+ if (fromVersion == toVersion) {
286
+ Logger.log("Version has not changed. No migrations needed.");
287
+ return null;
288
+ }
289
+ if (fromVersion > toVersion)
290
+ throw new Error(`You cannot create new migrations with a lower version (from ${fromVersion} to ${toVersion})`);
291
+ const foreignKeyOffQuery = this.dialect.changeForeignKeysState(false);
292
+ const changes = {
293
+ up: foreignKeyOffQuery,
294
+ down: foreignKeyOffQuery
295
+ };
296
+ this.migrations.reset(dbInstructions, fromVersion);
297
+ const preSQL = dbInstructions.preMigration?.(
298
+ this.migrations,
299
+ fromVersion,
300
+ toVersion
301
+ );
302
+ if (preSQL) {
303
+ changes.up += `
304
+
305
+ -- Custom SQL from preMigration()
306
+ ${preSQL.up}`;
307
+ changes.down += `
308
+
309
+ -- Custom SQL from preMigration()
310
+ ${preSQL.down}`;
311
+ }
312
+ const tableStructureGenerator = new TableStructureGenerator(dbInstructions, this.dialect);
313
+ this.newTables = tableStructureGenerator.generateTableStructure();
314
+ if (fromVersion == 0) {
315
+ Logger.log(`Creating initial migration to version ${dbInstructions.version}`);
316
+ const initialChanges = await this.createAndDropTables();
317
+ changes.up += initialChanges.up;
318
+ changes.down += initialChanges.down;
319
+ } else {
320
+ Logger.log(`Creating migration SQL from version ${fromVersion} to ${toVersion}`);
321
+ this.existingTables = await this.dialect.getTableNames();
322
+ [
323
+ await this.createAndDropTables(),
324
+ await this.migrateForeignKeys(),
325
+ await this.migrateColumns(),
326
+ this.renameColumns(),
327
+ await this.recreateTables()
328
+ ].forEach((entry) => {
329
+ changes.up += entry.up;
330
+ changes.down += entry.down;
331
+ });
332
+ }
333
+ const postSql = dbInstructions.postMigration?.(fromVersion, toVersion);
334
+ if (postSql) {
335
+ changes.up += `
336
+
337
+ -- Custom SQL from postMigration()
338
+ ${postSql.up}`;
339
+ changes.down += `
340
+
341
+ -- Custom SQL from postMigration()
342
+ ${postSql.down}`;
343
+ }
344
+ const foreignKeyOnQuery = this.dialect.changeForeignKeysState(true);
345
+ changes.up += `
346
+
347
+ ${foreignKeyOnQuery}`;
348
+ changes.down += `
349
+
350
+ ${foreignKeyOnQuery}`;
351
+ if (!this.migrations.checkIfAllowed(dbInstructions.throwIfNotAllowed)) {
352
+ return null;
353
+ }
354
+ return {
355
+ fromVersion,
356
+ toVersion,
357
+ changes
358
+ };
282
359
  }
283
360
  /**
284
- * Retrieves the SQL migration script for upgrading to the specified version.
285
- * If no version is provided, it retrieves the migration script for the latest version in the history.
361
+ * Generates SQL change statements for creating and dropping tables based on the current table structure
362
+ * and existing table configurations in the database. The `up` changes include SQL statements for creating
363
+ * new tables, while the `down` changes include SQL statements for dropping the corresponding tables or
364
+ * recreating them if necessary.
286
365
  *
287
- * @param toVersion - The version of the migration script to retrieve. If not specified, the latest version is used.
288
- * @return The content of the SQL migration script as a string.
366
+ * @return {Promise<SqlChanges>} A promise that resolves to an object containing `up` and `down` SQL
367
+ * change statements for migrating the database schema.
289
368
  */
290
- getUpMigration(toVersion) {
291
- return (0, import_fs.readFileSync)(`${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`, { encoding: "utf-8" });
369
+ async createAndDropTables() {
370
+ let changes = {
371
+ up: "\n\n-- Create tables\n",
372
+ down: "\n\n-- Create tables\n"
373
+ };
374
+ for (const tableName in this.newTables) {
375
+ if (this.tableDoesNotExists(tableName)) {
376
+ const structure = this.newTables[tableName];
377
+ changes.up += `${this.createTableSql(tableName, structure.columns, structure.foreignKeys)}
378
+ `;
379
+ changes.down += `${this.dialect.dropTable(tableName)}
380
+ `;
381
+ }
382
+ }
383
+ for (const tableName of this.existingTables) {
384
+ if (!this.newTables[tableName]) {
385
+ this.migrations.verifyMigration(tableName, "dropTable");
386
+ if (!this.dialect.canInspectForeignKeys || !this.dialect.canInspectPrimaryKey)
387
+ this.migrations.verifyMigration(tableName, "continueWithoutRollback");
388
+ changes.up += `${this.dialect.dropTable(tableName)}
389
+ `;
390
+ changes.down += this.dialect.canInspectForeignKeys && this.dialect.canInspectPrimaryKey ? this.createTableSql(tableName, await this.dialect.getColumnInformation(tableName), await this.dialect.getForeignKeys(tableName)) : "\n\n-- Cannot recreate foreign keys or load primary keys with this database! Table will not be recreated!\n";
391
+ }
392
+ }
393
+ return changes;
292
394
  }
293
395
  /**
294
- * Retrieves the SQL migration script for downgrading to the specified version.
396
+ * Generates an SQL string to create a table with the specified schema.
295
397
  *
296
- * @param version - The version number of the migration to retrieve.
297
- * @return The SQL script for the down migration.
398
+ * @param tableName - The name of the table to be created.
399
+ * @param columns - An array of objects defining the columns of the table, including their names, types
400
+ * default values, and whether they are primary keys.
401
+ * @param foreignKeys - An optional array of objects defining the foreign key constraints for the table,
402
+ * including the source column, target table, target column, action on update, and action on delete.
403
+ * @return The complete SQL string to create the table with the specified structure and constraints.
298
404
  */
299
- getDownMigration(version) {
300
- return (0, import_fs.readFileSync)(`${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${version}.sql`, { encoding: "utf-8" });
301
- }
302
- };
303
-
304
- // src/lib/dialects/DefaultSql.ts
305
- var MIGRATION_DATA_TABLE_NAME = "__sqlmorpheus_migrations";
306
- var DefaultSql = class {
307
- canAlterForeignKeys = false;
308
- canAlterPrimaryKey = false;
309
- canInspectForeignKeys = false;
310
- canInspectPrimaryKey = false;
311
- typeString = "TEXT";
312
- typeInt = "INTEGER";
313
- typeBigInt = "BIGINT";
314
- typeBoolean = "BOOLEAN";
315
- typeNull = "NULL";
316
- formatValueToSql(value) {
317
- return value.toString();
318
- }
319
- changeForeignKeysState(enabled) {
320
- return "";
321
- }
322
- async getForeignKeys(tableName, db) {
323
- throw new Error("Inspecting foreign keys is not supported!");
324
- }
325
- addForeignKey(fromTableName, foreignKey) {
326
- throw new Error("Adding foreign keys is not supported!");
327
- }
328
- removeForeignKey(tableName, foreignKeyName) {
329
- throw new Error("Foreign key removal is not supported!");
330
- }
331
- addPrimaryKey(tableName, columnName) {
332
- throw new Error("Adding foreign keys is not supported!");
333
- }
334
- removePrimaryKey(tableName, columnName) {
335
- throw new Error("Foreign key removal is not supported!");
336
- }
337
- foreignKey(column, foreignTable, foreignColumn, onUpdate, onDelete) {
338
- let query = `FOREIGN KEY (${column}) REFERENCES ${foreignTable} (${foreignColumn})`;
339
- if (onUpdate)
340
- query += ` ON UPDATE ${onUpdate}`;
341
- if (onDelete)
342
- query += ` ON DELETE ${onDelete}`;
343
- return query;
344
- }
345
- createTable(tableName, entries) {
346
- return `CREATE TABLE IF NOT EXISTS ${tableName} (
347
- ${entries.join(",\n ")}
348
- );`;
349
- }
350
- renameTable(tableName, newTableName) {
351
- return `ALTER TABLE ${tableName} RENAME TO ${newTableName};`;
352
- }
353
- dropTable(tableName) {
354
- return `DROP TABLE IF EXISTS ${tableName};`;
355
- }
356
- columnDefinition(columnName, type, defaultValue, isPrimaryKey) {
357
- const query = `${columnName} ${type} DEFAULT ${defaultValue}`;
358
- return isPrimaryKey ? `${query} PRIMARY KEY` : query;
405
+ createTableSql(tableName, columns, foreignKeys) {
406
+ const queryLines = [];
407
+ for (const columnInfo of columns) {
408
+ queryLines.push(this.dialect.columnDefinition(columnInfo.name, columnInfo.type, columnInfo.defaultValue, columnInfo.isPrimaryKey));
409
+ }
410
+ if (foreignKeys) {
411
+ for (const foreignKeyInfo of foreignKeys) {
412
+ queryLines.push(this.dialect.foreignKey(foreignKeyInfo.fromColumn, foreignKeyInfo.toTable, foreignKeyInfo.toColumn.toString(), foreignKeyInfo.onUpdate, foreignKeyInfo.onDelete));
413
+ }
414
+ }
415
+ return this.dialect.createTable(tableName, queryLines);
359
416
  }
360
- createColumn(columnTable, entry) {
361
- return `ALTER TABLE ${columnTable} ADD ${entry};`;
417
+ /**
418
+ * Checks if the specified table does not exist in the list of existing tables.
419
+ *
420
+ * @param tableName - The name of the table to check.
421
+ * @return Returns true if the table does not exist, otherwise false.
422
+ */
423
+ tableDoesNotExists(tableName) {
424
+ return this.existingTables.indexOf(tableName) == -1;
362
425
  }
363
- renameColumn(tableName, oldColumnName, newColumnName) {
364
- return `ALTER TABLE ${tableName} RENAME COLUMN ${newColumnName} TO ${oldColumnName};`;
426
+ /**
427
+ * Recreates database tables that have been flagged to be recreated in migration data.
428
+ * This method generated the necessary SQL code for backing up the current table data, dropping and recreating
429
+ * the tables, and reinserting the preserved data into the recreated tables.
430
+ */
431
+ async recreateTables() {
432
+ const changes = {
433
+ up: "\n\n-- Recreate tables\n",
434
+ down: "\n\n-- Recreate tables\n"
435
+ };
436
+ const migrationData = this.migrations.getMigrationData();
437
+ for (const tableName in migrationData) {
438
+ const migrationEntry = migrationData[tableName];
439
+ if (!migrationEntry.recreate)
440
+ continue;
441
+ this.migrations.verifyMigration(tableName, "recreateTable");
442
+ if (!this.dialect.canInspectForeignKeys || !this.dialect.canInspectPrimaryKey)
443
+ this.migrations.verifyMigration(tableName, "continueWithoutRollback");
444
+ const oldColumnList = await this.dialect.getColumnInformation(tableName);
445
+ const newColumnList = this.newTables[tableName].columns;
446
+ const moveableColumns = newColumnList.filter((entry) => oldColumnList.find((oldEntry) => oldEntry.name == entry.name) != void 0).map((entry) => entry.name);
447
+ const backupTableName = `${tableName}__backup`;
448
+ const insertQuery = this.dialect.insert(
449
+ backupTableName,
450
+ this.dialect.insertValues(moveableColumns, this.dialect.select(tableName, moveableColumns))
451
+ );
452
+ const moveDataQuery = insertQuery + "\n" + this.dialect.dropTable(tableName) + "\n" + this.dialect.renameTable(backupTableName, tableName);
453
+ const structure = this.newTables[tableName];
454
+ changes.up += this.createTableSql(backupTableName, structure.columns, structure.foreignKeys) + "\n" + moveDataQuery;
455
+ changes.down += this.dialect.canInspectForeignKeys && this.dialect.canInspectPrimaryKey ? this.createTableSql(backupTableName, await this.dialect.getColumnInformation(tableName), await this.dialect.getForeignKeys(tableName)) + "\n" + moveDataQuery : "\n\n-- Cannot recreate foreign keys or load primary keys with this database! Table will not be recreated!\n";
456
+ }
457
+ return changes;
365
458
  }
366
- copyColumn(tableName, oldColumnName, newColumnName) {
367
- return `UPDATE ${tableName} SET ${newColumnName} = ${oldColumnName};`;
368
- }
369
- dropColumn(tableName, columnName) {
370
- return `ALTER TABLE ${tableName} DROP COLUMN ${columnName};`;
371
- }
372
- select(tableName, select, where) {
373
- let query = `SELECT ${select.join(",")} FROM ${tableName}`;
374
- if (where)
375
- query += ` WHERE ${where}`;
376
- return `${query};`;
377
- }
378
- insert(tableName, content) {
379
- return `INSERT INTO ${tableName} ${content};`;
380
- }
381
- insertValues(keys, valueString) {
382
- return `(${keys}) ${valueString ?? `VALUES (${keys.map(() => "?").join(",")})`}`;
383
- }
384
- migrationTableQuery() {
385
- return this.createTable(MIGRATION_DATA_TABLE_NAME, [
386
- this.columnDefinition("version", this.typeInt, "0", false)
387
- ]);
388
- }
389
- async createMigrationTableIfNeeded(db) {
390
- await db.runMultipleWriteStatements(this.migrationTableQuery());
391
- }
392
- //TODO: untested
393
- async getVersion(db) {
394
- await this.createMigrationTableIfNeeded(db);
395
- const query = this.select(MIGRATION_DATA_TABLE_NAME, ["version"]);
396
- const data = await db.runGetStatement(query);
397
- return data.length ? data[0].version : 0;
398
- }
399
- //TODO: untested
400
- async setVersion(db, newVersion) {
401
- const query = `${this.migrationTableQuery()};
402
- INSERT INTO ${MIGRATION_DATA_TABLE_NAME} (version) VALUES ${newVersion} WHERE NOT EXISTS (SELECT 1 FROM ${MIGRATION_DATA_TABLE_NAME})
403
- UNION ALL
404
- UPDATE ${MIGRATION_DATA_TABLE_NAME} SET version = ${newVersion} WHERE EXISTS (SELECT 1 FROM ${MIGRATION_DATA_TABLE_NAME});
405
- `;
406
- await db.runMultipleWriteStatements(query);
407
- }
408
- };
409
-
410
- // src/lib/dialects/SqliteDialect.ts
411
- var SqliteDialect = class extends DefaultSql {
412
- typeBoolean = "INTEGER";
413
- typeBigInt = "INTEGER";
414
- canAlterForeignKeys = false;
415
- canAlterPrimaryKey = false;
416
- canInspectForeignKeys = true;
417
- canInspectPrimaryKey = true;
418
- changeForeignKeysState(enabled) {
419
- return `PRAGMA foreign_keys = ${enabled ? "ON" : "OFF"};`;
420
- }
421
- async getForeignKeys(tableName, db) {
422
- const data = await db.runGetStatement(`PRAGMA foreign_key_list(${tableName});`);
423
- return data.map((entry) => {
424
- return {
425
- fromTable: tableName,
426
- fromColumn: entry["from"],
427
- toTable: entry["table"],
428
- toColumn: entry["to"],
429
- on_update: entry["on_update"],
430
- on_delete: entry["on_delete"]
431
- };
432
- });
433
- }
434
- async getTableNames(db) {
435
- return (await db.runGetStatement("SELECT name FROM sqlite_master WHERE type = 'table'")).map((obj) => obj.name);
436
- }
437
- async getColumnInformation(tableName, db) {
438
- const data = await db.runGetStatement(`PRAGMA table_info(${tableName})`);
439
- return data.map((entry) => {
440
- return {
441
- name: entry["name"],
442
- type: entry["type"],
443
- defaultValue: entry["dflt_value"],
444
- isPrimaryKey: entry["pk"] == "1"
445
- };
446
- });
447
- }
448
- formatValueToSql(value) {
449
- switch (typeof value) {
450
- case "boolean":
451
- return value ? "1" : "0";
452
- default:
453
- return value.toString();
459
+ /**
460
+ * Migrates foreign key constraints for all defined tables.
461
+ */
462
+ async migrateForeignKeys() {
463
+ if (!this.dialect.canAlterForeignKeys)
464
+ return { up: "", down: "" };
465
+ let changes = {
466
+ up: "\n\n-- Foreign keys\n",
467
+ down: "\n\n-- Foreign keys\n"
468
+ };
469
+ for (const tableName in this.newTables) {
470
+ if (this.migrations.willBeRecreated(tableName) || this.tableDoesNotExists(tableName))
471
+ continue;
472
+ const structure = this.newTables[tableName];
473
+ const newForeignKeys = structure.foreignKeys ?? [];
474
+ const oldForeignKeys = await this.dialect.getForeignKeys(tableName);
475
+ let checkForNewForeignKeys = true;
476
+ for (const oldForeignKey of oldForeignKeys) {
477
+ const newForeignKey = newForeignKeys.find((entry) => entry.fromColumn == oldForeignKey.fromColumn);
478
+ if (!newForeignKey) {
479
+ Logger.log(`Foreign key ${oldForeignKey.toTable}.${oldForeignKey.toColumn} to ${oldForeignKey.toTable}.${oldForeignKey.toColumn} was removed!`);
480
+ this.migrations.verifyMigration(tableName, "removeForeignKey");
481
+ if (this.dialect.canAlterForeignKeys) {
482
+ changes.up += this.dialect.removeForeignKey(oldForeignKey.fromTable, oldForeignKey.fromColumn);
483
+ changes.down += this.dialect.addForeignKey(
484
+ oldForeignKey.fromTable,
485
+ this.dialect.foreignKey(oldForeignKey.fromColumn, oldForeignKey.toTable, oldForeignKey.toColumn, oldForeignKey.onUpdate, oldForeignKey.onDelete)
486
+ );
487
+ } else {
488
+ this.migrations.recreateTableImp(structure.table);
489
+ checkForNewForeignKeys = false;
490
+ }
491
+ } else {
492
+ if (!newForeignKey || oldForeignKey.toColumn != newForeignKey.toColumn || (oldForeignKey.onUpdate ?? "NO ACTION") != (newForeignKey.onUpdate ?? "NO ACTION") || (oldForeignKey.onDelete ?? "NO ACTION") != (newForeignKey.onDelete ?? "NO ACTION")) {
493
+ Logger.log(`Foreign key ${oldForeignKey.toTable}.${oldForeignKey.toColumn} to ${oldForeignKey.toTable}.${oldForeignKey.toColumn} was changed!`);
494
+ this.migrations.verifyMigration(tableName, "alterForeignKey");
495
+ if (this.dialect.canAlterForeignKeys) {
496
+ changes.up += this.dialect.removeForeignKey(oldForeignKey.fromTable, oldForeignKey.fromColumn) + this.dialect.addForeignKey(
497
+ newForeignKey.fromTable,
498
+ this.dialect.foreignKey(newForeignKey.fromColumn, newForeignKey.toTable, newForeignKey.toColumn, newForeignKey.onUpdate, newForeignKey.onDelete)
499
+ );
500
+ changes.down += this.dialect.addForeignKey(
501
+ oldForeignKey.fromTable,
502
+ this.dialect.foreignKey(oldForeignKey.fromColumn, oldForeignKey.toTable, oldForeignKey.toColumn, oldForeignKey.onUpdate, oldForeignKey.onDelete)
503
+ ) + this.dialect.removeForeignKey(newForeignKey.fromTable, newForeignKey.fromColumn);
504
+ } else {
505
+ this.migrations.recreateTableImp(structure.table);
506
+ checkForNewForeignKeys = false;
507
+ }
508
+ }
509
+ }
510
+ }
511
+ if (checkForNewForeignKeys) {
512
+ for (const newForeignKey of newForeignKeys) {
513
+ const oldForeignKey = oldForeignKeys.find((entry) => entry.fromColumn == newForeignKey.fromColumn);
514
+ if (oldForeignKey)
515
+ continue;
516
+ Logger.log(`Foreign key ${newForeignKey.toTable}.${newForeignKey.toColumn} to ${newForeignKey.toTable}.${newForeignKey.toColumn} is new!`);
517
+ if (this.dialect.canAlterForeignKeys) {
518
+ changes.up += this.dialect.addForeignKey(
519
+ newForeignKey.toTable,
520
+ this.dialect.foreignKey(newForeignKey.fromColumn, newForeignKey.toTable, newForeignKey.toColumn, newForeignKey.onUpdate, newForeignKey.onDelete)
521
+ );
522
+ changes.down += this.dialect.removeForeignKey(newForeignKey.fromTable, newForeignKey.fromColumn);
523
+ } else {
524
+ this.migrations.recreateTableImp(structure.table);
525
+ break;
526
+ }
527
+ }
528
+ }
454
529
  }
455
- }
456
- async getVersion(db) {
457
- const output = await db.runGetStatement(`PRAGMA user_version;`);
458
- return output[0].user_version;
459
- }
460
- async setVersion(db, newVersion) {
461
- await db.runMultipleWriteStatements(`PRAGMA user_version = ${newVersion};`);
462
- }
463
- };
464
-
465
- // src/lib/dialects/PostgresDialect.ts
466
- var PostgresDialect = class extends DefaultSql {
467
- canAlterForeignKeys = true;
468
- canAlterPrimaryKey = true;
469
- canInspectForeignKeys = false;
470
- canInspectPrimaryKey = false;
471
- changeForeignKeysState(enabled) {
472
- return `SET session_replication_role = '${enabled ? "replica" : "origin"}';`;
473
- }
474
- addForeignKey(fromTableName, foreignKey) {
475
- return `ALTER TABLE ${fromTableName} ADD CONSTRAINT ${fromTableName} ${foreignKey};`;
476
- }
477
- removeForeignKey(tableName, foreignKeyName) {
478
- return `ALTER TABLE ${tableName} DROP CONSTRAINT ${foreignKeyName};`;
479
- }
480
- async getTableNames(db) {
481
- return await db.runGetStatement("SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';");
482
- }
483
- async getColumnInformation(tableName, db) {
484
- const data = await db.runGetStatement(`SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '${tableName}';`);
485
- return data.map((entry) => {
486
- return {
487
- name: entry["column_name"],
488
- type: entry["data_type"],
489
- defaultValue: entry["column_default"],
490
- isPrimaryKey: false
491
- };
492
- });
493
- }
494
- addPrimaryKey(tableName, columnName) {
495
- return `ALTER TABLE ${tableName} ADD PRIMARY KEY (${columnName});
496
- `;
497
- }
498
- removePrimaryKey(tableName, columnName) {
499
- return `ALTER TABLE ${tableName} DROP CONSTRAINT ${columnName};
500
- `;
501
- }
502
- };
503
-
504
- // src/lib/dialects/MsSqlDialect.ts
505
- var MsSqlDialect = class extends DefaultSql {
506
- canAlterForeignKeys = true;
507
- canAlterPrimaryKey = true;
508
- canInspectForeignKeys = true;
509
- canInspectPrimaryKey = false;
510
- changeForeignKeysState(enabled) {
511
- return `EXEC sp_MSforeachtable "${enabled ? "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" : "ALTER TABLE ? NOCHECK CONSTRAINT all"}"`;
512
- }
513
- async getForeignKeys(tableName, db) {
514
- const data = await db.runGetStatement(`EXEC sp_fkeys @fktable_name = ${tableName};`);
515
- return data.map((entry) => {
516
- return {
517
- fromTable: entry[tableName],
518
- fromColumn: entry["FKCOLUMN_NAME"],
519
- toTable: entry["PKTABLE_NAME"],
520
- toColumn: entry["PKCOLUMN_NAME"]
521
- };
522
- });
523
- }
524
- addForeignKey(fromTableName, foreignKey) {
525
- return `ALTER TABLE ${fromTableName} ADD ${foreignKey};`;
526
- }
527
- removeForeignKey(tableName, foreignKeyName) {
528
- return `ALTER TABLE ${tableName} DROP CONSTRAINT ${foreignKeyName};`;
529
- }
530
- addPrimaryKey(tableName, columnName) {
531
- return `ALTER TABLE ${tableName} ADD CONSTRAINT ${tableName}_primary PRIMARY KEY (${columnName});`;
532
- }
533
- removePrimaryKey(tableName, columnName) {
534
- return `ALTER TABLE ${tableName} DROP CONSTRAINT ${columnName}_primary;`;
535
- }
536
- async getTableNames(db) {
537
- return await db.runGetStatement("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");
538
- }
539
- async getColumnInformation(tableName, db) {
540
- const data = await db.runGetStatement(`SELECT COLUMN_NAME, DATA_TYPE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'${tableName};'`);
541
- return data.map((entry) => {
542
- return {
543
- name: entry["COLUMN_NAME"],
544
- type: entry["DATA_TYPE"],
545
- defaultValue: entry["COLUMN_DEFAULT"],
546
- isPrimaryKey: false
547
- };
548
- });
549
- }
550
- };
551
-
552
- // src/lib/dialects/MySqlDialect.ts
553
- var MySqlDialect = class extends DefaultSql {
554
- canAlterForeignKeys = true;
555
- canAlterPrimaryKey = true;
556
- canInspectForeignKeys = true;
557
- canInspectPrimaryKey = true;
558
- changeForeignKeysState(enabled) {
559
- return `SET FOREIGN_KEY_CHECKS ${enabled ? "1" : "0"}
560
- ;`;
561
- }
562
- async getForeignKeys(tableName, db) {
563
- const data = await db.runGetStatement(`SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = (SELECT DATABASE()) AND REFERENCED_TABLE_NAME = '${tableName}';`);
564
- return data.map((entry) => {
565
- return {
566
- fromTable: tableName,
567
- fromColumn: entry["COLUMN_NAME"],
568
- toTable: entry["REFERENCED_TABLE_NAME"],
569
- toColumn: entry["REFERENCED_COLUMN_NAME"]
570
- };
571
- });
572
- }
573
- addForeignKey(fromTableName, foreignKey) {
574
- return `ALTER TABLE ${fromTableName} ADD ${foreignKey};`;
575
- }
576
- removeForeignKey(tableName, foreignKeyName) {
577
- return `ALTER TABLE ${tableName} DROP FOREIGN KEY ${foreignKeyName};`;
578
- }
579
- addPrimaryKey(tableName, columnName) {
580
- return `ALTER TABLE ${tableName} PRIMARY KEY (${columnName});`;
581
- }
582
- removePrimaryKey(tableName, _columnName) {
583
- return `ALTER TABLE ${tableName} PRIMARY KEY;`;
584
- }
585
- async getTableNames(db) {
586
- return await db.runGetStatement("SHOW TABLES;");
587
- }
588
- async getColumnInformation(tableName, db) {
589
- const data = await db.runGetStatement(`SHOW COLUMNS FROM ${tableName};`);
590
- return data.map((entry) => {
591
- return {
592
- name: entry["Field"],
593
- type: entry["Type"],
594
- defaultValue: entry["Default"],
595
- isPrimaryKey: entry["Key"] == "PRI"
596
- };
597
- });
598
- }
599
- };
600
-
601
- // src/lib/getDialect.ts
602
- function getDialect(dbInstructions) {
603
- switch (dbInstructions.dialect) {
604
- case "Sqlite":
605
- return new SqliteDialect();
606
- case "Postgres":
607
- return new PostgresDialect();
608
- case "MsSql":
609
- return new MsSqlDialect();
610
- case "MySql":
611
- return new MySqlDialect();
612
- default:
613
- throw new Error(`Unknown dialect ${dbInstructions.dialect}`);
614
- }
615
- }
616
-
617
- // src/lib/MigrationManager.ts
618
- var MigrationManager = class {
619
- migrations = new Migrations();
620
- tableStructureGenerator;
621
- existingTables = [];
622
- db;
623
- dbInstructions;
624
- migrationHistoryManager;
625
- dialect;
626
- constructor(db, dbInstructions) {
627
- this.dialect = getDialect(dbInstructions);
628
- this.db = db;
629
- this.dbInstructions = dbInstructions;
630
- this.tableStructureGenerator = new TableStructureGenerator(dbInstructions, this.dialect);
631
- this.migrationHistoryManager = new MigrationHistoryManager(this.dbInstructions.configPath);
530
+ return changes;
632
531
  }
633
532
  /**
634
- * Generates the SQL changes required to migrate a database from its current version
635
- * to the target version defined in the database instructions. Handles the creation
636
- * and deletion of tables, migration of foreign keys and columns, renaming of columns,
637
- * and recreating tables, along with executing any pre- and post-migration custom logic.
638
- *
639
- * @return A promise that resolves to an object containing the SQL
640
- * changes for the migration (`up` and `down` changes) or null if no migration is required.
641
- * Throws an error in scenarios such as attempting to migrate to a lower version
642
- * or an invalid starting version.
533
+ * Checks all columns of all tables, creates them if they do not exist in the database and modifies them if needed.
534
+ * If types, default values or primary key change, the table is recreated
643
535
  */
644
- async getMigrateSql() {
645
- if (this.dbInstructions.version <= 0)
646
- throw new Error("Cannot migrate to version 0 or lower");
647
- const fromVersion = await this.dialect.getVersion(this.db);
648
- if (fromVersion == 0) {
649
- Logger.log(`Creating initial migration to version ${this.dbInstructions.version}`);
650
- return this.createAndDropTables();
651
- }
652
- if (fromVersion == this.dbInstructions.version) {
653
- Logger.log("Version has not changed. No migrations needed.");
654
- return null;
655
- }
656
- if (fromVersion > this.dbInstructions.version)
657
- throw new Error(`You cannot create new migrations with a lower version (from ${fromVersion} to ${this.dbInstructions.version})`);
658
- Logger.log(`Creating migration SQL from version ${fromVersion} to ${this.dbInstructions.version}`);
659
- const db = this.db;
660
- await db.createBackup?.(`from_${fromVersion}_to_${this.dbInstructions.version}`);
661
- this.existingTables = await this.dialect.getTableNames(this.db);
662
- const foreignKeyOffQuery = this.dialect.changeForeignKeysState(false);
536
+ async migrateColumns() {
663
537
  const changes = {
664
- up: foreignKeyOffQuery,
665
- down: foreignKeyOffQuery
538
+ up: "\n\n-- Migrate columns\n",
539
+ down: "\n\n-- Migrate columns\n"
666
540
  };
667
- const preSQL = this.dbInstructions.preMigration?.(
668
- this.migrations,
669
- fromVersion,
670
- this.dbInstructions.version
671
- );
672
- if (preSQL) {
673
- changes.up += `
674
-
675
- -- Custom SQL from preMigration()
676
- ${preSQL.up}`;
677
- changes.down += `
678
-
679
- -- Custom SQL from preMigration()
680
- ${preSQL.down}`;
681
- }
682
- [
683
- await this.createAndDropTables(),
684
- await this.migrateForeignKeys(),
685
- await this.migrateColumns(),
686
- this.renameColumns(),
687
- await this.recreateTables()
688
- ].forEach((entry) => {
689
- changes.up += entry.up;
690
- changes.down += entry.down;
691
- });
692
- const postSql = this.dbInstructions.postMigration?.(fromVersion, this.dbInstructions.version);
693
- if (postSql) {
694
- changes.up += `
695
-
696
- -- Custom SQL from postMigration()
697
- ${postSql.up}`;
698
- changes.down += `
699
-
700
- -- Custom SQL from postMigration()
701
- ${postSql.down}`;
541
+ for (const tableName in this.newTables) {
542
+ if (this.migrations.willBeRecreated(tableName) || this.tableDoesNotExists(tableName))
543
+ continue;
544
+ const newTableDefinition = this.newTables[tableName];
545
+ const oldColumnList = await this.dialect.getColumnInformation(tableName);
546
+ const oldPrimaryKey = this.dialect.canInspectPrimaryKey ? this.getPrimaryKeyColumn(oldColumnList) : false;
547
+ const newColumnList = newTableDefinition.columns;
548
+ const newPrimaryKey = newTableDefinition.primaryKey;
549
+ if (this.dialect.canInspectPrimaryKey && oldPrimaryKey != newPrimaryKey) {
550
+ Logger.log(`Primary key in ${tableName} was changed from ${oldPrimaryKey} to ${newPrimaryKey}!`);
551
+ this.migrations.verifyMigration(tableName, "alterPrimaryKey");
552
+ if (this.dialect.canAlterPrimaryKey) {
553
+ if (oldPrimaryKey) {
554
+ changes.up += this.dialect.removePrimaryKey(tableName, oldPrimaryKey);
555
+ changes.down += this.dialect.addPrimaryKey(tableName, oldPrimaryKey);
556
+ }
557
+ if (newPrimaryKey) {
558
+ changes.up += this.dialect.addPrimaryKey(tableName, newPrimaryKey.toString());
559
+ changes.down += this.dialect.removePrimaryKey(tableName, newPrimaryKey.toString());
560
+ }
561
+ } else
562
+ this.migrations.recreateTableImp(newTableDefinition.table);
563
+ continue;
564
+ }
565
+ for (const newColumn of newColumnList) {
566
+ const oldColumn = oldColumnList.find(
567
+ (entry) => this.migrations.getUpdatedColumnName(tableName, entry.name) == newColumn.name
568
+ );
569
+ if (oldColumn == void 0) {
570
+ changes.up += this.dialect.createColumn(tableName, this.dialect.columnDefinition(newColumn.name, newColumn.type, newColumn.defaultValue, newColumn.isPrimaryKey)) + "\n";
571
+ changes.down += this.dialect.dropColumn(tableName, newColumn.name) + "\n";
572
+ } else if (newColumn.type != oldColumn.type || newColumn.defaultValue != oldColumn.defaultValue) {
573
+ this.migrations.recreateTableImp(newTableDefinition.table);
574
+ }
575
+ }
576
+ for (const oldColumn of oldColumnList) {
577
+ const newColumn = newColumnList.find(
578
+ (entry) => entry.name == this.migrations.getUpdatedColumnName(tableName, oldColumn.name)
579
+ );
580
+ if (newColumn == void 0) {
581
+ this.migrations.verifyMigration(tableName, "dropColumn");
582
+ changes.up += this.dialect.dropColumn(tableName, oldColumn.name) + "\n";
583
+ changes.down += this.dialect.createColumn(tableName, this.dialect.columnDefinition(oldColumn.name, oldColumn.type, oldColumn.defaultValue, oldColumn.isPrimaryKey)) + "\n";
584
+ }
585
+ }
702
586
  }
703
- const foreignKeyOnQuery = this.dialect.changeForeignKeysState(true);
704
- changes.up += `
705
-
706
- ${foreignKeyOnQuery}`;
707
- changes.down += `
708
-
709
- ${foreignKeyOnQuery}`;
710
587
  return changes;
711
588
  }
712
589
  /**
713
- * Prepares the migration by generating the SQL changes and creating a migration history entry.
714
- * If no changes are needed, the method exits early.
590
+ * Retrieves the name of the primary key column from a list of column information.
715
591
  *
716
- * @param overwriteExisting - Optional flag indicating if overwriting existing changes is allowed.
717
- * @return - A promise that resolves once the migration preparation is complete.
592
+ * @param columnInfoList - An array of ColumnInfo objects containing details about each column.
593
+ * @return The name of the primary key column if found; otherwise, undefined.
718
594
  */
719
- async prepareMigration(overwriteExisting) {
720
- const changes = await this.getMigrateSql();
721
- if (!changes)
722
- return;
723
- const fromVersion = await this.dialect.getVersion(this.db);
724
- this.migrationHistoryManager.createMigrationHistory(fromVersion, this.dbInstructions.version, changes, overwriteExisting);
595
+ getPrimaryKeyColumn(columnInfoList) {
596
+ for (const columnInfo of columnInfoList) {
597
+ if (columnInfo.isPrimaryKey)
598
+ return columnInfo.name;
599
+ }
725
600
  }
726
601
  /**
727
- * Generates SQL change statements for creating and dropping tables based on the current table structure
728
- * and existing table configurations in the database. The `up` changes include SQL statements for creating
729
- * new tables, while the `down` changes include SQL statements for dropping the corresponding tables or
730
- * recreating them if necessary.
731
- *
732
- * @return {Promise<SqlChanges>} A promise that resolves to an object containing `up` and `down` SQL
733
- * change statements for migrating the database schema.
602
+ * Handles the renaming of columns in database tables by generating SQL changes for both applying and reverting the renames.
603
+ * Skips tables that are marked for recreation.
734
604
  */
735
- async createAndDropTables() {
736
- let changes = {
737
- up: "\n\n-- Create tables\n",
738
- down: "\n\n-- Create tables\n"
605
+ renameColumns() {
606
+ const changes = {
607
+ up: "\n\n-- Rename columns\n",
608
+ down: "\n\n-- Rename columns\n"
739
609
  };
740
- for (const tableName in this.tableStructureGenerator.tables) {
741
- if (this.tableDoesNotExists(tableName)) {
742
- const structure = this.tableStructureGenerator.tables[tableName];
743
- changes.up += `${this.createTableSql(tableName, structure.columns, structure.foreignKeys)}
744
- `;
745
- changes.down += `${this.dialect.dropTable(tableName)}
746
- `;
747
- }
748
- }
749
- for (const tableName of this.existingTables) {
750
- if (!this.tableStructureGenerator.tables[tableName]) {
751
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "dropTable");
752
- if (!this.dialect.canInspectForeignKeys || !this.dialect.canInspectPrimaryKey)
753
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "continueWithoutRollback");
754
- changes.up += `${this.dialect.dropTable(tableName)}
755
- `;
756
- changes.down += this.dialect.canInspectForeignKeys && this.dialect.canInspectPrimaryKey ? this.createTableSql(tableName, await this.dialect.getColumnInformation(tableName, this.db), await this.dialect.getForeignKeys(tableName, this.db)) : "\n\n-- Cannot recreate foreign keys or load primary keys with this database! Table will not be recreated!\n";
757
- }
610
+ const migrationData = this.migrations.getMigrationData();
611
+ for (const tableName in migrationData) {
612
+ if (migrationData[tableName].recreate)
613
+ continue;
614
+ this.migrations.loopRenamedColumns(tableName, (oldColumnName, newColumnName) => {
615
+ changes.up += this.dialect.renameColumn(tableName, oldColumnName, newColumnName);
616
+ changes.down += this.dialect.renameColumn(tableName, newColumnName, oldColumnName);
617
+ });
758
618
  }
759
619
  return changes;
760
620
  }
621
+ };
622
+
623
+ // src/lib/MigrationHistoryManager.ts
624
+ var import_node_fs = require("fs");
625
+ var import_fs = require("fs");
626
+ var FILENAME_UP_PREFIX = "up_to_";
627
+ var FILENAME_DOWN_PREFIX = "down_to_";
628
+ var MigrationHistoryManager = class {
629
+ configPath;
630
+ migrationsPath;
631
+ constructor(configPath) {
632
+ this.configPath = configPath;
633
+ this.migrationsPath = `${configPath}/migrations`;
634
+ (0, import_node_fs.mkdirSync)(this.configPath, { recursive: true });
635
+ (0, import_node_fs.mkdirSync)(this.migrationsPath, { recursive: true });
636
+ }
761
637
  /**
762
- * Generates an SQL string to create a table with the specified schema.
638
+ * Creates migration history files for upgrading and downgrading database schemas.
763
639
  *
764
- * @param tableName - The name of the table to be created.
765
- * @param columns - An array of objects defining the columns of the table, including their names, types
766
- * default values, and whether they are primary keys.
767
- * @param foreignKeys - An optional array of objects defining the foreign key constraints for the table,
768
- * including the source column, target table, target column, action on update, and action on delete.
769
- * @return The complete SQL string to create the table with the specified structure and constraints.
640
+ * @param fromVersion - The current version number of the database.
641
+ * @param toVersion - The target version number for the migration.
642
+ * @param changes - An object containing the SQL changes for upgrading (`changes.up`) and downgrading (`changes.down`).
643
+ * @param overwriteExisting - A flag that determines if existing migration files should be overwritten. Defaults to `false`.
770
644
  */
771
- createTableSql(tableName, columns, foreignKeys) {
772
- const queryLines = [];
773
- for (const columnInfo of columns) {
774
- queryLines.push(this.dialect.columnDefinition(columnInfo.name, columnInfo.type, columnInfo.defaultValue, columnInfo.isPrimaryKey));
775
- }
776
- if (foreignKeys) {
777
- for (const foreignKeyInfo of foreignKeys) {
778
- queryLines.push(this.dialect.foreignKey(foreignKeyInfo.fromColumn, foreignKeyInfo.toTable, foreignKeyInfo.toColumn.toString(), foreignKeyInfo.onUpdate, foreignKeyInfo.onDelete));
779
- }
780
- }
781
- return this.dialect.createTable(tableName, queryLines);
645
+ createMigrationHistory(fromVersion, toVersion, changes, overwriteExisting) {
646
+ const upPath = `${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`;
647
+ const downPath = `${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${fromVersion}.sql`;
648
+ if ((0, import_node_fs.existsSync)(upPath) && !overwriteExisting)
649
+ throw new Error(`Migration ${upPath} already exists!`);
650
+ else if ((0, import_node_fs.existsSync)(downPath) && !overwriteExisting)
651
+ throw new Error(`Migration ${downPath} already exists!`);
652
+ Logger.log(`Save migrations to ${this.migrationsPath}`);
653
+ (0, import_node_fs.writeFileSync)(`${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`, `-- From: Version ${fromVersion}
654
+ -- To: Version ${toVersion}
655
+ ${changes.up}`, { encoding: "utf-8" });
656
+ (0, import_node_fs.writeFileSync)(`${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${fromVersion}.sql`, `-- From: Version ${toVersion}
657
+ -- To: Version ${fromVersion}
658
+ ${changes.down}`, { encoding: "utf-8" });
782
659
  }
783
660
  /**
784
- * Checks if the specified table does not exist in the list of existing tables.
661
+ * Retrieves the SQL migration script for upgrading to the specified version.
662
+ * If no version is provided, it retrieves the migration script for the latest version in the history.
785
663
  *
786
- * @param tableName - The name of the table to check.
787
- * @return Returns true if the table does not exist, otherwise false.
664
+ * @param toVersion - The version of the migration script to retrieve. If not specified, the latest version is used.
665
+ * @return The content of the SQL migration script as a string.
788
666
  */
789
- tableDoesNotExists(tableName) {
790
- return this.existingTables.indexOf(tableName) == -1;
667
+ getUpMigration(toVersion) {
668
+ return (0, import_fs.readFileSync)(`${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`, { encoding: "utf-8" });
791
669
  }
792
670
  /**
793
- * Recreates database tables that have been flagged to be recreated in migration data.
794
- * This method generated the necessary SQL code for backing up the current table data, dropping and recreating
795
- * the tables, and reinserting the preserved data into the recreated tables.
671
+ * Retrieves the SQL migration script for downgrading to the specified version.
672
+ *
673
+ * @param version - The version number of the migration to retrieve.
674
+ * @return The SQL script for the down migration.
796
675
  */
797
- async recreateTables() {
798
- const changes = {
799
- up: "\n\n-- Recreate tables\n",
800
- down: "\n\n-- Recreate tables\n"
801
- };
802
- const migrationData = this.migrations.getMigrationData();
803
- for (const tableName in migrationData) {
804
- const migrationEntry = migrationData[tableName];
805
- if (!migrationEntry.recreate)
806
- continue;
807
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "recreateTable");
808
- if (!this.dialect.canInspectForeignKeys || !this.dialect.canInspectPrimaryKey)
809
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "continueWithoutRollback");
810
- const oldColumnList = await this.dialect.getColumnInformation(tableName, this.db);
811
- const newColumnList = this.tableStructureGenerator.tables[tableName].columns;
812
- const moveableColumns = newColumnList.filter((entry) => oldColumnList.find((oldEntry) => oldEntry.name == entry.name) != void 0).map((entry) => entry.name);
813
- const backupTableName = `${tableName}__backup`;
814
- const insertQuery = this.dialect.insert(
815
- backupTableName,
816
- this.dialect.insertValues(moveableColumns, this.dialect.select(tableName, moveableColumns))
817
- );
818
- const moveDataQuery = insertQuery + "\n" + this.dialect.dropTable(tableName) + "\n" + this.dialect.renameTable(backupTableName, tableName);
819
- const structure = this.tableStructureGenerator.tables[tableName];
820
- changes.up += this.createTableSql(backupTableName, structure.columns, structure.foreignKeys) + "\n" + moveDataQuery;
821
- changes.down += this.dialect.canInspectForeignKeys && this.dialect.canInspectPrimaryKey ? this.createTableSql(backupTableName, await this.dialect.getColumnInformation(tableName, this.db), await this.dialect.getForeignKeys(tableName, this.db)) + "\n" + moveDataQuery : "\n\n-- Cannot recreate foreign keys or load primary keys with this database! Table will not be recreated!\n";
822
- }
823
- return changes;
676
+ getDownMigration(version) {
677
+ return (0, import_fs.readFileSync)(`${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${version}.sql`, { encoding: "utf-8" });
824
678
  }
825
- /**
826
- * Migrates foreign key constraints for all defined tables.
827
- */
828
- async migrateForeignKeys() {
829
- if (!this.dialect.canAlterForeignKeys)
830
- return { up: "", down: "" };
831
- let changes = {
832
- up: "\n\n-- Foreign keys\n",
833
- down: "\n\n-- Foreign keys\n"
834
- };
835
- for (const tableName in this.tableStructureGenerator.tables) {
836
- if (this.migrations.willBeRecreated(tableName) || this.tableDoesNotExists(tableName))
837
- continue;
838
- const structure = this.tableStructureGenerator.tables[tableName];
839
- const newForeignKeys = structure.foreignKeys ?? [];
840
- const oldForeignKeys = await this.dialect.getForeignKeys(tableName, this.db);
841
- let checkForNewForeignKeys = true;
842
- for (const oldForeignKey of oldForeignKeys) {
843
- const newForeignKey = newForeignKeys.find((entry) => entry.fromColumn == oldForeignKey.fromColumn);
844
- if (!newForeignKey) {
845
- Logger.log(`Foreign key ${oldForeignKey.toTable}.${oldForeignKey.toColumn} to ${oldForeignKey.toTable}.${oldForeignKey.toColumn} was removed!`);
846
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "removeForeignKey");
847
- if (this.dialect.canAlterForeignKeys) {
848
- changes.up += this.dialect.removeForeignKey(oldForeignKey.fromTable, oldForeignKey.fromColumn);
849
- changes.down += this.dialect.addForeignKey(
850
- oldForeignKey.fromTable,
851
- this.dialect.foreignKey(oldForeignKey.fromColumn, oldForeignKey.toTable, oldForeignKey.toColumn, oldForeignKey.onUpdate, oldForeignKey.onDelete)
852
- );
853
- } else {
854
- this.migrations.recreateTable(structure.table);
855
- checkForNewForeignKeys = false;
856
- }
857
- } else {
858
- if (!newForeignKey || oldForeignKey.toColumn != newForeignKey.toColumn || (oldForeignKey.onUpdate ?? "NO ACTION") != (newForeignKey.onUpdate ?? "NO ACTION") || (oldForeignKey.onDelete ?? "NO ACTION") != (newForeignKey.onDelete ?? "NO ACTION")) {
859
- Logger.log(`Foreign key ${oldForeignKey.toTable}.${oldForeignKey.toColumn} to ${oldForeignKey.toTable}.${oldForeignKey.toColumn} was changed!`);
860
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "alterForeignKey");
861
- if (this.dialect.canAlterForeignKeys) {
862
- changes.up += this.dialect.removeForeignKey(oldForeignKey.fromTable, oldForeignKey.fromColumn) + this.dialect.addForeignKey(
863
- newForeignKey.fromTable,
864
- this.dialect.foreignKey(newForeignKey.fromColumn, newForeignKey.toTable, newForeignKey.toColumn, newForeignKey.onUpdate, newForeignKey.onDelete)
865
- );
866
- changes.down += this.dialect.addForeignKey(
867
- oldForeignKey.fromTable,
868
- this.dialect.foreignKey(oldForeignKey.fromColumn, oldForeignKey.toTable, oldForeignKey.toColumn, oldForeignKey.onUpdate, oldForeignKey.onDelete)
869
- ) + this.dialect.removeForeignKey(newForeignKey.fromTable, newForeignKey.fromColumn);
870
- } else {
871
- this.migrations.recreateTable(structure.table);
872
- checkForNewForeignKeys = false;
873
- }
874
- }
875
- }
876
- }
877
- if (checkForNewForeignKeys) {
878
- for (const newForeignKey of newForeignKeys) {
879
- const oldForeignKey = oldForeignKeys.find((entry) => entry.fromColumn == newForeignKey.fromColumn);
880
- if (oldForeignKey)
881
- continue;
882
- Logger.log(`Foreign key ${newForeignKey.toTable}.${newForeignKey.toColumn} to ${newForeignKey.toTable}.${newForeignKey.toColumn} is new!`);
883
- if (this.dialect.canAlterForeignKeys) {
884
- changes.up += this.dialect.addForeignKey(
885
- newForeignKey.toTable,
886
- this.dialect.foreignKey(newForeignKey.fromColumn, newForeignKey.toTable, newForeignKey.toColumn, newForeignKey.onUpdate, newForeignKey.onDelete)
887
- );
888
- changes.down += this.dialect.removeForeignKey(newForeignKey.fromTable, newForeignKey.fromColumn);
889
- } else {
890
- this.migrations.recreateTable(structure.table);
891
- break;
892
- }
893
- }
679
+ };
680
+
681
+ // src/lib/tableInfo/decorators/DbTable.ts
682
+ var import_polyfill_symbol_metadata = require("polyfill-symbol-metadata");
683
+ function DbTable(tableName, primaryKey) {
684
+ return (table, context) => {
685
+ Object.defineProperty(table, "name", { value: tableName, writable: false });
686
+ const tableInfo = context?.metadata ? getTableInfoFromMetadata(context.metadata) : getTableInfo(table);
687
+ tableInfo.primaryKey = primaryKey?.toString();
688
+ if (tableInfo.foreignKeys) {
689
+ for (const foreignKey of tableInfo.foreignKeys) {
690
+ foreignKey.fromTable = tableName;
894
691
  }
895
692
  }
896
- return changes;
693
+ };
694
+ }
695
+
696
+ // src/lib/tableInfo/decorators/ForeignKey.ts
697
+ var import_polyfill_symbol_metadata2 = require("polyfill-symbol-metadata");
698
+ function ForeignKey(toTable, toColumn, onDelete, onUpdate) {
699
+ return (table, context) => {
700
+ const metadata = context?.metadata ? getTableInfoFromMetadata(context.metadata) : getTableInfo(table);
701
+ if (!metadata.foreignKeys)
702
+ metadata.foreignKeys = [];
703
+ metadata.foreignKeys.push({
704
+ fromTable: "",
705
+ fromColumn: context.name ?? context,
706
+ //to stay compatible with old decorator structure (see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#decorator-metadata)
707
+ toTable: toTable.name,
708
+ toColumn: toColumn.toString(),
709
+ onDelete,
710
+ onUpdate
711
+ });
712
+ };
713
+ }
714
+
715
+ // src/lib/dialects/DefaultSql.ts
716
+ var MIGRATION_DATA_TABLE_NAME = "__sqlmorpheus_migrations";
717
+ var DefaultSql = class {
718
+ db;
719
+ canAlterForeignKeys = false;
720
+ canAlterPrimaryKey = false;
721
+ canInspectForeignKeys = false;
722
+ canInspectPrimaryKey = false;
723
+ typeString = "TEXT";
724
+ typeInt = "INTEGER";
725
+ typeBigInt = "BIGINT";
726
+ typeBoolean = "BOOLEAN";
727
+ typeNull = "NULL";
728
+ constructor(db) {
729
+ this.db = db;
730
+ }
731
+ formatValueToSql(value) {
732
+ return value.toString();
733
+ }
734
+ changeForeignKeysState(enabled) {
735
+ return "";
736
+ }
737
+ addForeignKey(fromTableName, foreignKey) {
738
+ throw new Error("Adding foreign keys is not supported!");
739
+ }
740
+ removeForeignKey(tableName, foreignKeyName) {
741
+ throw new Error("Foreign key removal is not supported!");
742
+ }
743
+ addPrimaryKey(tableName, columnName) {
744
+ throw new Error("Adding foreign keys is not supported!");
745
+ }
746
+ removePrimaryKey(tableName, columnName) {
747
+ throw new Error("Foreign key removal is not supported!");
748
+ }
749
+ foreignKey(column, foreignTable, foreignColumn, onUpdate, onDelete) {
750
+ let query = `FOREIGN KEY (${column}) REFERENCES ${foreignTable} (${foreignColumn})`;
751
+ if (onUpdate)
752
+ query += ` ON UPDATE ${onUpdate}`;
753
+ if (onDelete)
754
+ query += ` ON DELETE ${onDelete}`;
755
+ return query;
756
+ }
757
+ createTable(tableName, entries) {
758
+ return `CREATE TABLE IF NOT EXISTS ${tableName} (
759
+ ${entries.join(",\n ")}
760
+ );`;
761
+ }
762
+ renameTable(tableName, newTableName) {
763
+ return `ALTER TABLE ${tableName} RENAME TO ${newTableName};`;
764
+ }
765
+ dropTable(tableName) {
766
+ return `DROP TABLE IF EXISTS ${tableName};`;
767
+ }
768
+ columnDefinition(columnName, type, defaultValue, isPrimaryKey) {
769
+ const query = `${columnName} ${type} DEFAULT ${defaultValue}`;
770
+ return isPrimaryKey ? `${query} PRIMARY KEY` : query;
771
+ }
772
+ createColumn(columnTable, entry) {
773
+ return `ALTER TABLE ${columnTable} ADD ${entry};`;
774
+ }
775
+ renameColumn(tableName, oldColumnName, newColumnName) {
776
+ return `ALTER TABLE ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};`;
777
+ }
778
+ copyColumn(tableName, oldColumnName, newColumnName) {
779
+ return `UPDATE ${tableName} SET ${newColumnName} = ${oldColumnName};`;
780
+ }
781
+ dropColumn(tableName, columnName) {
782
+ return `ALTER TABLE ${tableName} DROP COLUMN ${columnName};`;
783
+ }
784
+ select(tableName, select, where) {
785
+ let query = `SELECT ${select.join(",")} FROM ${tableName}`;
786
+ if (where)
787
+ query += ` WHERE ${where}`;
788
+ return `${query};`;
789
+ }
790
+ insert(tableName, content) {
791
+ return `INSERT INTO ${tableName} ${content};`;
792
+ }
793
+ insertValues(keys, valueString) {
794
+ return `(${keys}) ${valueString ?? `VALUES (${keys.map(() => "?").join(",")})`}`;
795
+ }
796
+ migrationTableQuery() {
797
+ return this.createTable(MIGRATION_DATA_TABLE_NAME, [
798
+ this.columnDefinition("version", this.typeInt, "0", false)
799
+ ]);
800
+ }
801
+ async getForeignKeys(tableName) {
802
+ throw new Error("Inspecting foreign keys is not supported!");
803
+ }
804
+ async createMigrationTableIfNeeded() {
805
+ await this.db.runMultipleWriteStatements(this.migrationTableQuery());
806
+ }
807
+ //TODO: untested
808
+ async getVersion() {
809
+ await this.createMigrationTableIfNeeded();
810
+ const query = this.select(MIGRATION_DATA_TABLE_NAME, ["version"]);
811
+ const data = await this.db.runGetStatement(query);
812
+ return data.length ? data[0].version : 0;
813
+ }
814
+ //TODO: untested
815
+ async setVersion(newVersion) {
816
+ const query = `${this.migrationTableQuery()};
817
+ INSERT INTO ${MIGRATION_DATA_TABLE_NAME} (version) VALUES ${newVersion} WHERE NOT EXISTS (SELECT 1 FROM ${MIGRATION_DATA_TABLE_NAME})
818
+ UNION ALL
819
+ UPDATE ${MIGRATION_DATA_TABLE_NAME} SET version = ${newVersion} WHERE EXISTS (SELECT 1 FROM ${MIGRATION_DATA_TABLE_NAME});
820
+ `;
821
+ await this.db.runMultipleWriteStatements(query);
822
+ }
823
+ };
824
+
825
+ // src/lib/dialects/SqliteDialect.ts
826
+ var SqliteDialect = class extends DefaultSql {
827
+ typeBoolean = "INTEGER";
828
+ typeBigInt = "INTEGER";
829
+ canAlterForeignKeys = false;
830
+ canAlterPrimaryKey = false;
831
+ canInspectForeignKeys = true;
832
+ canInspectPrimaryKey = true;
833
+ changeForeignKeysState(enabled) {
834
+ return `PRAGMA foreign_keys = ${enabled ? "ON" : "OFF"};`;
835
+ }
836
+ async getTableNames() {
837
+ return (await this.db.runGetStatement("SELECT name FROM sqlite_master WHERE type = 'table'")).map((obj) => obj.name);
838
+ }
839
+ async getColumnInformation(tableName) {
840
+ const data = await this.db.runGetStatement(`PRAGMA table_info(${tableName})`);
841
+ return data.map((entry) => {
842
+ return {
843
+ name: entry["name"],
844
+ type: entry["type"],
845
+ defaultValue: entry["dflt_value"],
846
+ isPrimaryKey: entry["pk"] == "1"
847
+ };
848
+ });
897
849
  }
898
- /**
899
- * Checks all columns of all tables, creates them if they do not exist in the database and modifies them if needed.
900
- * If types, default values or primary key change, the table is recreated
901
- */
902
- async migrateColumns() {
903
- const changes = {
904
- up: "\n\n-- Migrate columns\n",
905
- down: "\n\n-- Migrate columns\n"
906
- };
907
- for (const tableName in this.tableStructureGenerator.tables) {
908
- if (this.migrations.willBeRecreated(tableName) || this.tableDoesNotExists(tableName))
909
- continue;
910
- const newTableDefinition = this.tableStructureGenerator.tables[tableName];
911
- const oldColumnList = await this.dialect.getColumnInformation(tableName, this.db);
912
- const oldPrimaryKey = this.dialect.canInspectPrimaryKey ? this.getPrimaryKeyColumn(oldColumnList) : false;
913
- const newColumnList = newTableDefinition.columns;
914
- const newPrimaryKey = newTableDefinition.primaryKey;
915
- if (this.dialect.canInspectPrimaryKey && oldPrimaryKey != newPrimaryKey) {
916
- Logger.log(`Primary key in ${tableName} was changed from ${oldPrimaryKey} to ${newPrimaryKey}!`);
917
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "alterPrimaryKey");
918
- if (this.dialect.canAlterPrimaryKey) {
919
- if (oldPrimaryKey) {
920
- changes.up += this.dialect.removePrimaryKey(tableName, oldPrimaryKey);
921
- changes.down += this.dialect.addPrimaryKey(tableName, oldPrimaryKey);
922
- }
923
- if (newPrimaryKey) {
924
- changes.up += this.dialect.addPrimaryKey(tableName, newPrimaryKey.toString());
925
- changes.down += this.dialect.removePrimaryKey(tableName, newPrimaryKey.toString());
926
- }
927
- } else
928
- this.migrations.recreateTable(newTableDefinition.table);
929
- continue;
930
- }
931
- for (const newColumn of newColumnList) {
932
- const oldColumn = oldColumnList.find((entry) => entry.name == newColumn.name);
933
- if (oldColumn == void 0) {
934
- changes.up += this.dialect.createColumn(tableName, this.dialect.columnDefinition(newColumn.name, newColumn.type, newColumn.defaultValue, newColumn.isPrimaryKey)) + "\n";
935
- changes.down += this.dialect.dropColumn(tableName, newColumn.name) + "\n";
936
- } else if (newColumn.type != oldColumn.type || newColumn.defaultValue != oldColumn.defaultValue) {
937
- this.migrations.recreateTable(newTableDefinition.table);
938
- }
939
- }
940
- for (const oldColumn of oldColumnList) {
941
- const newColumn = newColumnList.find((entry) => entry.name == oldColumn.name);
942
- if (newColumn == void 0) {
943
- this.migrations.throwIfNotAllowed(this.dbInstructions.version, tableName, "dropColumn");
944
- changes.up += this.dialect.dropColumn(tableName, oldColumn.name) + "\n";
945
- changes.down += this.dialect.createColumn(tableName, this.dialect.columnDefinition(oldColumn.name, oldColumn.type, oldColumn.defaultValue, oldColumn.isPrimaryKey)) + "\n";
946
- }
947
- }
850
+ formatValueToSql(value) {
851
+ switch (typeof value) {
852
+ case "boolean":
853
+ return value ? "1" : "0";
854
+ default:
855
+ return value.toString();
948
856
  }
949
- return changes;
950
857
  }
951
- /**
952
- * Retrieves the name of the primary key column from a list of column information.
953
- *
954
- * @param columnInfoList - An array of ColumnInfo objects containing details about each column.
955
- * @return The name of the primary key column if found; otherwise, undefined.
956
- */
957
- getPrimaryKeyColumn(columnInfoList) {
958
- for (const columnInfo of columnInfoList) {
959
- if (columnInfo.isPrimaryKey)
960
- return columnInfo.name;
961
- }
858
+ async getForeignKeys(tableName) {
859
+ const data = await this.db.runGetStatement(`PRAGMA foreign_key_list(${tableName});`);
860
+ return data.map((entry) => {
861
+ return {
862
+ fromTable: tableName,
863
+ fromColumn: entry["from"],
864
+ toTable: entry["table"],
865
+ toColumn: entry["to"],
866
+ on_update: entry["on_update"],
867
+ on_delete: entry["on_delete"]
868
+ };
869
+ });
962
870
  }
963
- /**
964
- * Handles the renaming of columns in database tables by generating SQL changes for both applying and reverting the renames.
965
- * Skips tables that are marked for recreation.
966
- */
967
- renameColumns() {
968
- const changes = {
969
- up: "\n\n-- Rename columns\n",
970
- down: "\n\n-- Rename columns\n"
971
- };
972
- const migrationData = this.migrations.getMigrationData();
973
- for (const tableName in migrationData) {
974
- if (migrationData[tableName].recreate)
975
- continue;
976
- this.migrations.loopRenamedColumns(tableName, (oldColumnName, newColumnName) => {
977
- changes.up += this.dialect.renameColumn(tableName, oldColumnName, newColumnName);
978
- changes.down += this.dialect.renameColumn(tableName, newColumnName, oldColumnName);
979
- });
980
- }
981
- return changes;
871
+ async getVersion() {
872
+ const output = await this.db.runGetStatement(`PRAGMA user_version;`);
873
+ return output[0].user_version;
874
+ }
875
+ async setVersion(newVersion) {
876
+ await this.db.runMultipleWriteStatements(`PRAGMA user_version = ${newVersion};`);
982
877
  }
983
878
  };
984
879
 
985
- // src/lib/tableInfo/decorators/DbTable.ts
986
- var import_polyfill_symbol_metadata = require("polyfill-symbol-metadata");
987
- function DbTable(tableName, primaryKey) {
988
- return (table, context) => {
989
- Object.defineProperty(table, "name", { value: tableName, writable: false });
990
- const tableInfo = context?.metadata ? getTableInfoFromMetadata(context.metadata) : getTableInfo(table);
991
- tableInfo.primaryKey = primaryKey?.toString();
992
- if (tableInfo.foreignKeys) {
993
- for (const foreignKey of tableInfo.foreignKeys) {
994
- foreignKey.fromTable = tableName;
995
- }
996
- }
997
- };
998
- }
880
+ // src/lib/dialects/PostgresDialect.ts
881
+ var PostgresDialect = class extends DefaultSql {
882
+ canAlterForeignKeys = true;
883
+ canAlterPrimaryKey = true;
884
+ canInspectForeignKeys = false;
885
+ canInspectPrimaryKey = false;
886
+ changeForeignKeysState(enabled) {
887
+ return `SET session_replication_role = '${enabled ? "replica" : "origin"}';`;
888
+ }
889
+ addForeignKey(fromTableName, foreignKey) {
890
+ return `ALTER TABLE ${fromTableName} ADD CONSTRAINT ${fromTableName} ${foreignKey};`;
891
+ }
892
+ removeForeignKey(tableName, foreignKeyName) {
893
+ return `ALTER TABLE ${tableName} DROP CONSTRAINT ${foreignKeyName};`;
894
+ }
895
+ async getTableNames() {
896
+ return await this.db.runGetStatement("SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';");
897
+ }
898
+ async getColumnInformation(tableName) {
899
+ const data = await this.db.runGetStatement(`SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '${tableName}';`);
900
+ return data.map((entry) => {
901
+ return {
902
+ name: entry["column_name"],
903
+ type: entry["data_type"],
904
+ defaultValue: entry["column_default"],
905
+ isPrimaryKey: false
906
+ };
907
+ });
908
+ }
909
+ addPrimaryKey(tableName, columnName) {
910
+ return `ALTER TABLE ${tableName} ADD PRIMARY KEY (${columnName});
911
+ `;
912
+ }
913
+ removePrimaryKey(tableName, columnName) {
914
+ return `ALTER TABLE ${tableName} DROP CONSTRAINT ${columnName};
915
+ `;
916
+ }
917
+ };
999
918
 
1000
- // src/lib/tableInfo/decorators/ForeignKey.ts
1001
- var import_polyfill_symbol_metadata2 = require("polyfill-symbol-metadata");
1002
- function ForeignKey(toTable, toColumn, onDelete, onUpdate) {
1003
- return (table, context) => {
1004
- const metadata = context?.metadata ? getTableInfoFromMetadata(context.metadata) : getTableInfo(table);
1005
- if (!metadata.foreignKeys)
1006
- metadata.foreignKeys = [];
1007
- metadata.foreignKeys.push({
1008
- fromTable: "",
1009
- fromColumn: context.name ?? context,
1010
- //to stay compatible with old decorator structure (see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#decorator-metadata)
1011
- toTable: toTable.name,
1012
- toColumn: toColumn.toString(),
1013
- onDelete,
1014
- onUpdate
919
+ // src/lib/dialects/MsSqlDialect.ts
920
+ var MsSqlDialect = class extends DefaultSql {
921
+ canAlterForeignKeys = true;
922
+ canAlterPrimaryKey = true;
923
+ canInspectForeignKeys = true;
924
+ canInspectPrimaryKey = false;
925
+ changeForeignKeysState(enabled) {
926
+ return `EXEC sp_MSforeachtable "${enabled ? "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" : "ALTER TABLE ? NOCHECK CONSTRAINT all"}"`;
927
+ }
928
+ addForeignKey(fromTableName, foreignKey) {
929
+ return `ALTER TABLE ${fromTableName} ADD ${foreignKey};`;
930
+ }
931
+ removeForeignKey(tableName, foreignKeyName) {
932
+ return `ALTER TABLE ${tableName} DROP CONSTRAINT ${foreignKeyName};`;
933
+ }
934
+ addPrimaryKey(tableName, columnName) {
935
+ return `ALTER TABLE ${tableName} ADD CONSTRAINT ${tableName}_primary PRIMARY KEY (${columnName});`;
936
+ }
937
+ removePrimaryKey(tableName, columnName) {
938
+ return `ALTER TABLE ${tableName} DROP CONSTRAINT ${columnName}_primary;`;
939
+ }
940
+ async getForeignKeys(tableName) {
941
+ const data = await this.db.runGetStatement(`EXEC sp_fkeys @fktable_name = ${tableName};`);
942
+ return data.map((entry) => {
943
+ return {
944
+ fromTable: entry[tableName],
945
+ fromColumn: entry["FKCOLUMN_NAME"],
946
+ toTable: entry["PKTABLE_NAME"],
947
+ toColumn: entry["PKCOLUMN_NAME"]
948
+ };
1015
949
  });
1016
- };
950
+ }
951
+ async getTableNames() {
952
+ return await this.db.runGetStatement("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");
953
+ }
954
+ async getColumnInformation(tableName) {
955
+ const data = await this.db.runGetStatement(`SELECT COLUMN_NAME, DATA_TYPE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'${tableName};'`);
956
+ return data.map((entry) => {
957
+ return {
958
+ name: entry["COLUMN_NAME"],
959
+ type: entry["DATA_TYPE"],
960
+ defaultValue: entry["COLUMN_DEFAULT"],
961
+ isPrimaryKey: false
962
+ };
963
+ });
964
+ }
965
+ };
966
+
967
+ // src/lib/dialects/MySqlDialect.ts
968
+ var MySqlDialect = class extends DefaultSql {
969
+ canAlterForeignKeys = true;
970
+ canAlterPrimaryKey = true;
971
+ canInspectForeignKeys = true;
972
+ canInspectPrimaryKey = true;
973
+ changeForeignKeysState(enabled) {
974
+ return `SET FOREIGN_KEY_CHECKS ${enabled ? "1" : "0"}
975
+ ;`;
976
+ }
977
+ addForeignKey(fromTableName, foreignKey) {
978
+ return `ALTER TABLE ${fromTableName} ADD ${foreignKey};`;
979
+ }
980
+ removeForeignKey(tableName, foreignKeyName) {
981
+ return `ALTER TABLE ${tableName} DROP FOREIGN KEY ${foreignKeyName};`;
982
+ }
983
+ addPrimaryKey(tableName, columnName) {
984
+ return `ALTER TABLE ${tableName} PRIMARY KEY (${columnName});`;
985
+ }
986
+ removePrimaryKey(tableName, _columnName) {
987
+ return `ALTER TABLE ${tableName} PRIMARY KEY;`;
988
+ }
989
+ async getForeignKeys(tableName) {
990
+ const data = await this.db.runGetStatement(`SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = (SELECT DATABASE()) AND REFERENCED_TABLE_NAME = '${tableName}';`);
991
+ return data.map((entry) => {
992
+ return {
993
+ fromTable: tableName,
994
+ fromColumn: entry["COLUMN_NAME"],
995
+ toTable: entry["REFERENCED_TABLE_NAME"],
996
+ toColumn: entry["REFERENCED_COLUMN_NAME"]
997
+ };
998
+ });
999
+ }
1000
+ async getTableNames() {
1001
+ return await this.db.runGetStatement("SHOW TABLES;");
1002
+ }
1003
+ async getColumnInformation(tableName) {
1004
+ const data = await this.db.runGetStatement(`SHOW COLUMNS FROM ${tableName};`);
1005
+ return data.map((entry) => {
1006
+ return {
1007
+ name: entry["Field"],
1008
+ type: entry["Type"],
1009
+ defaultValue: entry["Default"],
1010
+ isPrimaryKey: entry["Key"] == "PRI"
1011
+ };
1012
+ });
1013
+ }
1014
+ };
1015
+
1016
+ // src/lib/getDialect.ts
1017
+ function getDialect(db, dbInstructions) {
1018
+ switch (dbInstructions.dialect) {
1019
+ case "Sqlite":
1020
+ return new SqliteDialect(db);
1021
+ case "Postgres":
1022
+ return new PostgresDialect(db);
1023
+ case "MsSql":
1024
+ return new MsSqlDialect(db);
1025
+ case "MySql":
1026
+ return new MySqlDialect(db);
1027
+ default:
1028
+ throw new Error(`Unknown dialect ${dbInstructions.dialect}`);
1029
+ }
1017
1030
  }
1018
1031
 
1019
1032
  // src/index.ts
1020
- async function prepareMigration(db, instructions, overwriteExisting) {
1021
- Logger.setMode(instructions.loggerMode);
1022
- const mm = new MigrationManager(db, instructions);
1023
- await mm.prepareMigration(overwriteExisting);
1033
+ async function prepareMigration(db, dbInstructions, overwriteExisting) {
1034
+ Logger.setMode(dbInstructions.loggerMode);
1035
+ const dialect = getDialect(db, dbInstructions);
1036
+ const mm = new MigrationManager(dialect);
1037
+ const migration = await mm.generateSqlChanges(dbInstructions);
1038
+ if (!migration)
1039
+ return;
1040
+ const migrationHistoryManager = new MigrationHistoryManager(dbInstructions.configPath);
1041
+ migrationHistoryManager.createMigrationHistory(migration.fromVersion, dbInstructions.version, migration.changes, overwriteExisting);
1024
1042
  }
1025
- async function runPreparedMigrations(db, instructions) {
1026
- Logger.setMode(instructions.loggerMode);
1027
- const migrationHistoryManager = new MigrationHistoryManager(instructions.configPath);
1028
- const dialect = getDialect(instructions);
1029
- const fromVersion = await dialect.getVersion(db);
1030
- const toVersion = instructions.version;
1043
+ async function runPreparedMigrations(db, dbInstructions) {
1044
+ Logger.setMode(dbInstructions.loggerMode);
1045
+ const historyManager = new MigrationHistoryManager(dbInstructions.configPath);
1046
+ const dialect = getDialect(db, dbInstructions);
1047
+ const fromVersion = await dialect.getVersion();
1048
+ const toVersion = dbInstructions.version;
1031
1049
  if (fromVersion == toVersion)
1032
1050
  return;
1051
+ await db.createBackup?.(`from_${fromVersion}_to_${dbInstructions.version}`);
1033
1052
  Logger.log(`Running migrations from ${fromVersion} to ${toVersion}`);
1034
1053
  for (let i = fromVersion ? fromVersion + 1 : toVersion; i <= toVersion; ++i) {
1035
- const upChanges = migrationHistoryManager.getUpMigration(i);
1054
+ const upChanges = historyManager.getUpMigration(i);
1036
1055
  Logger.debug(upChanges);
1037
1056
  await db.runMultipleWriteStatements(upChanges);
1038
- instructions.version = i;
1057
+ dbInstructions.version = i;
1039
1058
  }
1040
- await dialect.setVersion(db, toVersion);
1059
+ await dialect.setVersion(toVersion);
1041
1060
  }
1042
1061
  async function prepareAndRunMigration(db, instructions, overwriteExisting) {
1043
1062
  Logger.setMode(instructions.loggerMode);
1044
1063
  await prepareMigration(db, instructions, overwriteExisting);
1045
1064
  await runPreparedMigrations(db, instructions);
1046
1065
  }
1047
- async function runMigrationWithoutHistory(db, instructions) {
1048
- Logger.setMode(instructions.loggerMode);
1049
- const mm = new MigrationManager(db, instructions);
1050
- const changes = await mm.getMigrateSql();
1051
- if (changes)
1052
- await db.runMultipleWriteStatements(changes.up);
1066
+ async function runMigrationWithoutHistory(db, dbInstructions) {
1067
+ Logger.setMode(dbInstructions.loggerMode);
1068
+ const dialect = getDialect(db, dbInstructions);
1069
+ const mm = new MigrationManager(dialect);
1070
+ const migration = await mm.generateSqlChanges(dbInstructions);
1071
+ if (migration) {
1072
+ await db.createBackup?.(`from_${migration.fromVersion}_to_${dbInstructions.version}`);
1073
+ await db.runMultipleWriteStatements(migration.changes.up);
1074
+ }
1053
1075
  }
1054
- async function rollback(db, instructions, toVersion) {
1055
- Logger.setMode(instructions.loggerMode);
1056
- const migrationHistoryManager = new MigrationHistoryManager(instructions.configPath);
1057
- const dialect = getDialect(instructions);
1058
- const fromVersion = await dialect.getVersion(db);
1076
+ async function rollback(db, dbInstructions, toVersion) {
1077
+ Logger.setMode(dbInstructions.loggerMode);
1078
+ const dialect = getDialect(db, dbInstructions);
1079
+ const fromVersion = await dialect.getVersion();
1080
+ const historyManager = new MigrationHistoryManager(dbInstructions.configPath);
1081
+ await db.createBackup?.(`from_${fromVersion}_to_${dbInstructions.version}`);
1059
1082
  Logger.log(`Rolling back from ${fromVersion} to ${toVersion}`);
1060
1083
  for (let i = fromVersion - 1; i >= toVersion; --i) {
1061
- const upChanges = migrationHistoryManager.getDownMigration(i);
1084
+ const upChanges = historyManager.getDownMigration(i);
1062
1085
  Logger.debug(upChanges);
1063
1086
  await db.runMultipleWriteStatements(upChanges);
1064
- instructions.version = i;
1087
+ dbInstructions.version = i;
1065
1088
  }
1066
- await dialect.setVersion(db, toVersion);
1089
+ await dialect.setVersion(toVersion);
1067
1090
  }
1068
1091
  // Annotate the CommonJS export names for ESM import in node:
1069
1092
  0 && (module.exports = {