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