gina-sequelize 0.0.16 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runner.js ADDED
@@ -0,0 +1,602 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ChainError = void 0;
7
+ exports.stripExtension = stripExtension;
8
+ exports.resolveOrder = resolveOrder;
9
+ exports.readVersion = readVersion;
10
+ exports.runMigrations = runMigrations;
11
+ exports.revertMigrations = revertMigrations;
12
+ exports.repairMigration = repairMigration;
13
+ exports.dryRunMigrations = dryRunMigrations;
14
+ exports.createSnapshot = createSnapshot;
15
+ exports.upgradeFromSnapshot = upgradeFromSnapshot;
16
+ /**
17
+ * Applies and reverts migrations: the migration chain, the version stored in the database,
18
+ * failures halfway through a migration (`repair`) and dry runs.
19
+ */
20
+ const promises_1 = __importDefault(require("fs/promises"));
21
+ const sequelize_1 = require("sequelize");
22
+ const FAILURE_TABLE = 'gina_failure';
23
+ /** Operations `repair` checks before running, and that are listed when a migration fails. */
24
+ const OPERATIONS = [
25
+ 'createTable', 'dropTable', 'renameTable',
26
+ 'addColumn', 'removeColumn', 'changeColumn', 'renameColumn',
27
+ 'addIndex', 'removeIndex', 'addConstraint', 'removeConstraint',
28
+ 'bulkInsert', 'bulkUpdate', 'bulkDelete',
29
+ ];
30
+ /**
31
+ * Versions used to be saved with the file extension when migrations ran from compiled .js files
32
+ * (e.g. `20240101000000-foo.js`), so they're compared without it.
33
+ */
34
+ function stripExtension(version) {
35
+ return version.replace(/\.[cm]?[jt]s$/, '');
36
+ }
37
+ function normalize(migrationFiles) {
38
+ const entries = new Map();
39
+ for (const [name, entry] of Object.entries(migrationFiles)) {
40
+ entries.set(stripExtension(name), entry);
41
+ }
42
+ return entries;
43
+ }
44
+ class ChainError extends Error {
45
+ }
46
+ exports.ChainError = ChainError;
47
+ /**
48
+ * The order migrations run in. Each migration runs after its `previous`; migrations without one
49
+ * run first, by name. Fails when two migrations come after the same one (usually two branches that
50
+ * each added a migration), when a `previous` doesn't exist, or when there's a cycle.
51
+ */
52
+ function resolveOrder(migrationFiles) {
53
+ const entries = normalize(migrationFiles);
54
+ const names = [...entries.keys()].sort();
55
+ const previousOf = new Map();
56
+ const roots = names.filter(name => !entries.get(name)?.previous);
57
+ roots.forEach((name, index) => previousOf.set(name, roots[index - 1]));
58
+ for (const name of names) {
59
+ const previous = entries.get(name)?.previous;
60
+ if (!previous) {
61
+ continue;
62
+ }
63
+ if (!entries.has(stripExtension(previous))) {
64
+ throw new ChainError(`${name} runs after ${previous}, but there's no migration with that name.`);
65
+ }
66
+ previousOf.set(name, stripExtension(previous));
67
+ }
68
+ const next = new Map();
69
+ for (const [name, previous] of previousOf) {
70
+ next.set(previous, [...next.get(previous) ?? [], name]);
71
+ }
72
+ for (const [previous, children] of next) {
73
+ if (previous !== undefined && children.length > 1) {
74
+ throw new ChainError(`${children.join(' and ')} all run right after ${previous}. This usually happens when `
75
+ + 'two branches add a migration at the same time. Make them run one after the other: '
76
+ + 'set `export const previous` on the newer one to the last migration of the other, and update the HEAD file.');
77
+ }
78
+ }
79
+ const order = [];
80
+ let current = next.get(undefined)?.[0];
81
+ while (current !== undefined && !order.includes(current)) {
82
+ order.push(current);
83
+ current = next.get(current)?.[0];
84
+ }
85
+ if (order.length !== names.length) {
86
+ const unreachable = names.filter(name => !order.includes(name));
87
+ throw new ChainError(`The migration chain has a cycle: ${unreachable.join(', ')}.`);
88
+ }
89
+ return { order, entries };
90
+ }
91
+ function tableName(table) {
92
+ return typeof table === 'string' ? table : table.tableName;
93
+ }
94
+ async function tableExists(queryInterface, table) {
95
+ const tables = await queryInterface.showAllTables();
96
+ return tables.map(tableName).includes(tableName(table));
97
+ }
98
+ async function readVersion(sequelize) {
99
+ if (!await tableExists(sequelize.getQueryInterface(), 'gina_version')) {
100
+ return '';
101
+ }
102
+ const versions = await sequelize.query('SELECT version FROM gina_version;', {
103
+ type: sequelize_1.QueryTypes.SELECT,
104
+ });
105
+ if (versions.length > 1) {
106
+ throw new Error('There must be only one version on `gina_version` table.');
107
+ }
108
+ return versions.length == 1 ? stripExtension(versions[0].version) : '';
109
+ }
110
+ async function saveVersion(sequelize, version, updateAtFieldName) {
111
+ const [rows] = await sequelize.query('SELECT version FROM gina_version;');
112
+ if (rows.length) {
113
+ await sequelize.query(`UPDATE gina_version SET version = ?, ${updateAtFieldName} = NOW();`, { replacements: [version] });
114
+ }
115
+ else {
116
+ await sequelize.query(`INSERT INTO gina_version (${updateAtFieldName}, version) VALUES (NOW(), ?);`, { replacements: [version] });
117
+ }
118
+ }
119
+ /**
120
+ * Index (in `order`) of the version the database is at, -1 when it has none.
121
+ */
122
+ function versionIndex(order, entries, version) {
123
+ if (!version) {
124
+ return -1;
125
+ }
126
+ const index = order.indexOf(version);
127
+ if (index !== -1) {
128
+ return index;
129
+ }
130
+ // before the chain, versions were only compared by name, so a database can be at a migration
131
+ // whose file was removed since
132
+ if ([...entries.values()].every(entry => !entry.previous)) {
133
+ return order.filter(name => name <= version).length - 1;
134
+ }
135
+ throw new Error(`The database is at ${version}, which doesn't match any migration file.`);
136
+ }
137
+ async function readFailure(sequelize) {
138
+ if (!await tableExists(sequelize.getQueryInterface(), FAILURE_TABLE)) {
139
+ return undefined;
140
+ }
141
+ const failures = await sequelize.query(`SELECT migration, direction, error, failedAt FROM ${FAILURE_TABLE};`, {
142
+ type: sequelize_1.QueryTypes.SELECT,
143
+ });
144
+ return failures[0];
145
+ }
146
+ async function recordFailure(sequelize, failure) {
147
+ try {
148
+ await sequelize.getQueryInterface().createTable(FAILURE_TABLE, {
149
+ migration: { type: sequelize_1.DataTypes.STRING, allowNull: false },
150
+ direction: { type: sequelize_1.DataTypes.STRING(4), allowNull: false },
151
+ error: { type: sequelize_1.DataTypes.TEXT, allowNull: true },
152
+ failedAt: { type: sequelize_1.DataTypes.DATE, allowNull: false },
153
+ });
154
+ await sequelize.query(`DELETE FROM ${FAILURE_TABLE};`);
155
+ await sequelize.query(`INSERT INTO ${FAILURE_TABLE} (migration, direction, error, failedAt) VALUES (?, ?, ?, NOW());`, {
156
+ replacements: [failure.migration, failure.direction, failure.error],
157
+ });
158
+ }
159
+ catch (err) {
160
+ console.error(`could not record the failure on the ${FAILURE_TABLE} table:`, err.message);
161
+ }
162
+ }
163
+ function failureHelp(failure) {
164
+ return `Migration ${failure.migration} failed halfway (${failure.direction}), so part of it may have been applied. `
165
+ + 'Fix the cause, then run `gina-cli repair --continue` to finish it, '
166
+ + 'or `gina-cli repair --rollback` to undo what was applied.';
167
+ }
168
+ async function assertNoFailure(sequelize) {
169
+ const failure = await readFailure(sequelize);
170
+ if (failure) {
171
+ throw new Error(`${failureHelp(failure)}\nThe error was: ${failure.error}`);
172
+ }
173
+ }
174
+ function describeOperation(method, args) {
175
+ const table = args.length ? tableName(args[0]) : '';
176
+ const options = (value) => (value && typeof value === 'object' ? value : {});
177
+ switch (method) {
178
+ case 'addColumn':
179
+ case 'removeColumn':
180
+ case 'changeColumn':
181
+ return `${method} ${table}.${args[1]}`;
182
+ case 'renameColumn':
183
+ return `${method} ${table}.${args[1]} -> ${args[2]}`;
184
+ case 'renameTable':
185
+ return `${method} ${table} -> ${tableName(args[1])}`;
186
+ case 'addIndex':
187
+ return `${method} ${table} ${options(args[2]).name ?? options(args[1]).name ?? JSON.stringify(args[1])}`;
188
+ case 'removeIndex':
189
+ case 'removeConstraint':
190
+ return `${method} ${table} ${typeof args[1] === 'string' ? args[1] : JSON.stringify(args[1])}`;
191
+ case 'addConstraint':
192
+ return `${method} ${table} ${options(args[1]).name ?? options(args[1]).type}`;
193
+ }
194
+ return `${method} ${table}`;
195
+ }
196
+ /**
197
+ * Why an operation can be skipped on `repair` because the database is already the way it would leave it,
198
+ * or `undefined` when it has to run. Only checks by name; anything else still runs and may fail.
199
+ */
200
+ async function alreadyApplied(queryInterface, method, args) {
201
+ const table = tableName(args[0]);
202
+ const columns = async () => (await tableExists(queryInterface, table) ? queryInterface.describeTable(table) : undefined);
203
+ const indexes = async () => (await tableExists(queryInterface, table)
204
+ ? (await queryInterface.showIndex(table)).map(index => index.name)
205
+ : []);
206
+ const constraintExists = async (name) => {
207
+ if (!['mysql', 'mariadb'].includes(queryInterface.sequelize.getDialect())) {
208
+ return undefined;
209
+ }
210
+ const rows = await queryInterface.sequelize.query(`
211
+ SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
212
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND CONSTRAINT_NAME = ?`, {
213
+ type: sequelize_1.QueryTypes.SELECT,
214
+ replacements: [table, name],
215
+ });
216
+ return rows.length > 0;
217
+ };
218
+ switch (method) {
219
+ case 'createTable':
220
+ return await tableExists(queryInterface, table) ? `table ${table} already exists` : undefined;
221
+ case 'dropTable':
222
+ return await tableExists(queryInterface, table) ? undefined : `table ${table} doesn't exist`;
223
+ case 'renameTable':
224
+ return !await tableExists(queryInterface, table) && await tableExists(queryInterface, args[1])
225
+ ? `table ${table} was already renamed to ${tableName(args[1])}`
226
+ : undefined;
227
+ case 'addColumn':
228
+ return (await columns())?.[args[1]] ? `column ${table}.${args[1]} already exists` : undefined;
229
+ case 'removeColumn':
230
+ return (await columns())?.[args[1]] ? undefined : `column ${table}.${args[1]} doesn't exist`;
231
+ case 'renameColumn': {
232
+ const description = await columns();
233
+ return description && !description[args[1]] && description[args[2]]
234
+ ? `column ${table}.${args[1]} was already renamed to ${args[2]}`
235
+ : undefined;
236
+ }
237
+ case 'addIndex': {
238
+ const name = args[2]?.name ?? args[1].name;
239
+ return name && (await indexes()).includes(name) ? `index ${name} already exists` : undefined;
240
+ }
241
+ case 'removeIndex':
242
+ return typeof args[1] === 'string' && !(await indexes()).includes(args[1]) ? `index ${args[1]} doesn't exist` : undefined;
243
+ case 'addConstraint': {
244
+ const name = args[1].name;
245
+ return name && await constraintExists(name) ? `constraint ${name} already exists` : undefined;
246
+ }
247
+ case 'removeConstraint':
248
+ return typeof args[1] === 'string' && await constraintExists(args[1]) === false
249
+ ? `constraint ${args[1]} doesn't exist`
250
+ : undefined;
251
+ }
252
+ return undefined;
253
+ }
254
+ /**
255
+ * The QueryInterface handed to a migration: it records each operation that completes, so a failure
256
+ * can tell what was applied, and on `repair` skips the operations that were already applied.
257
+ */
258
+ function instrument(queryInterface, applied, repairing) {
259
+ const sequelize = new Proxy(queryInterface.sequelize, {
260
+ get(target, prop) {
261
+ const value = Reflect.get(target, prop);
262
+ if (prop === 'query') {
263
+ return async (...args) => {
264
+ const description = `query ${String(args[0]).replace(/\s+/g, ' ').trim().slice(0, 80)}`;
265
+ if (repairing) {
266
+ console.warn(`running again: ${description}`);
267
+ }
268
+ const result = await target.query(...args);
269
+ applied.push(description);
270
+ return result;
271
+ };
272
+ }
273
+ return typeof value === 'function' ? value.bind(target) : value;
274
+ },
275
+ });
276
+ return new Proxy(queryInterface, {
277
+ get(target, prop) {
278
+ if (prop === 'sequelize') {
279
+ return sequelize;
280
+ }
281
+ const value = Reflect.get(target, prop);
282
+ if (typeof value !== 'function') {
283
+ return value;
284
+ }
285
+ if (typeof prop !== 'string' || !OPERATIONS.includes(prop)) {
286
+ return value.bind(target);
287
+ }
288
+ return async (...args) => {
289
+ const description = describeOperation(prop, args);
290
+ if (repairing) {
291
+ const reason = await alreadyApplied(target, prop, args);
292
+ if (reason) {
293
+ console.info(`skipped: ${description} (${reason})`);
294
+ return undefined;
295
+ }
296
+ }
297
+ const result = await value.apply(target, args);
298
+ applied.push(description);
299
+ return result;
300
+ };
301
+ },
302
+ });
303
+ }
304
+ async function runMigration(sequelize, name, entry, direction, options) {
305
+ const run = entry.migration[direction];
306
+ if (typeof run !== 'function') {
307
+ throw new Error(`${name} doesn't have a ${direction} function.`);
308
+ }
309
+ const applied = [];
310
+ try {
311
+ await run.call(entry.migration, instrument(sequelize.getQueryInterface(), applied, Boolean(options.repairing)));
312
+ }
313
+ catch (err) {
314
+ if (!applied.length) {
315
+ console.error(`${name} failed (${direction}) before changing anything.`);
316
+ throw err;
317
+ }
318
+ console.error(`${name} failed (${direction}). Applied before the error:\n${applied.map(step => ` - ${step}`).join('\n')}`);
319
+ if (options.recordFailures !== false) {
320
+ await recordFailure(sequelize, { migration: name, direction, error: err.message });
321
+ console.error(failureHelp({ migration: name, direction }));
322
+ }
323
+ throw err;
324
+ }
325
+ }
326
+ async function runMigrations(sequelize, migrationFiles, updateAtFieldName, options = {}) {
327
+ const updatedAt = updateAtFieldName || 'updatedAt';
328
+ await assertNoFailure(sequelize);
329
+ const { order, entries } = resolveOrder(migrationFiles);
330
+ const version = await readVersion(sequelize);
331
+ const log = options.quiet ? () => undefined : console.info;
332
+ log('current version:', version);
333
+ for (const name of order.slice(versionIndex(order, entries, version) + 1)) {
334
+ log('applying migration:', name);
335
+ await runMigration(sequelize, name, entries.get(name), 'up', options);
336
+ await saveVersion(sequelize, name, updatedAt);
337
+ log('applied version:', name);
338
+ }
339
+ }
340
+ /**
341
+ * Reverts applied migrations, newest first, running their `down` functions.
342
+ * The first migration is never reverted: it creates the `gina_version` table that holds the version.
343
+ */
344
+ async function revertMigrations(sequelize, migrationFiles, target, updateAtFieldName = 'updatedAt') {
345
+ await assertNoFailure(sequelize);
346
+ const { order, entries } = resolveOrder(migrationFiles);
347
+ const version = await readVersion(sequelize);
348
+ console.info('current version:', version);
349
+ if (!version) {
350
+ throw new Error('There are no applied migrations to downgrade.');
351
+ }
352
+ const current = order.indexOf(version);
353
+ if (current === -1) {
354
+ throw new Error(`The current version ${version} doesn't match any migration file.`);
355
+ }
356
+ let targetIndex;
357
+ if (target.to !== undefined) {
358
+ const to = stripExtension(target.to);
359
+ const matches = order.filter(name => name.startsWith(to));
360
+ const exact = order.indexOf(to);
361
+ if (exact === -1 && matches.length !== 1) {
362
+ throw new Error(matches.length
363
+ ? `"${target.to}" matches more than one migration: ${matches.join(', ')}.`
364
+ : `There's no migration named "${target.to}".`);
365
+ }
366
+ targetIndex = exact !== -1 ? exact : order.indexOf(matches[0]);
367
+ if (targetIndex > current) {
368
+ throw new Error(`${order[targetIndex]} isn't applied yet (current version is ${version}). Use upgrade instead.`);
369
+ }
370
+ }
371
+ else {
372
+ const steps = target.steps ?? 1;
373
+ if (!Number.isInteger(steps) || steps < 1) {
374
+ throw new Error('The number of migrations to downgrade must be a positive integer.');
375
+ }
376
+ targetIndex = current - steps;
377
+ }
378
+ if (targetIndex < 0) {
379
+ throw new Error(`Can't downgrade ${current - targetIndex} migration(s): only ${current} can be reverted, `
380
+ + `the first one (${order[0]}) creates the gina_version table.`);
381
+ }
382
+ const toRevert = order.slice(targetIndex + 1, current + 1).reverse();
383
+ if (!toRevert.length) {
384
+ console.info('Nothing to downgrade.');
385
+ return;
386
+ }
387
+ const withoutDown = toRevert.filter(name => typeof entries.get(name)?.migration.down !== 'function');
388
+ if (withoutDown.length) {
389
+ throw new Error(`These migrations don't have a down function: ${withoutDown.join(', ')}.`);
390
+ }
391
+ for (const name of toRevert) {
392
+ const previous = order[order.indexOf(name) - 1];
393
+ console.info('reverting migration:', name);
394
+ await runMigration(sequelize, name, entries.get(name), 'down', {});
395
+ await saveVersion(sequelize, previous, updateAtFieldName);
396
+ console.info('current version:', previous);
397
+ }
398
+ }
399
+ /**
400
+ * Finishes (`continue`) or undoes (`rollback`) a migration that failed halfway, running it again
401
+ * while skipping the operations that are already applied.
402
+ */
403
+ async function repairMigration(sequelize, migrationFiles, mode, options = {}, updateAtFieldName = 'updatedAt') {
404
+ const failure = await readFailure(sequelize);
405
+ if (!failure) {
406
+ console.info('Nothing to repair: no migration failed halfway.');
407
+ return;
408
+ }
409
+ const { order, entries } = resolveOrder(migrationFiles);
410
+ const entry = entries.get(failure.migration);
411
+ if (!entry) {
412
+ throw new Error(`${failure.migration} failed halfway, but there's no migration file with that name.`);
413
+ }
414
+ console.info(`${failure.migration} failed halfway (${failure.direction}) on ${new Date(failure.failedAt).toISOString()}: ${failure.error}`);
415
+ if (entry.filePath && !options.yes) {
416
+ const source = await promises_1.default.readFile(entry.filePath, 'utf8');
417
+ if (/\.(query|bulkInsert|bulkUpdate|bulkDelete)\s*\(/.test(source)) {
418
+ throw new Error(`${failure.migration} runs raw queries or bulk operations. repair can't tell whether they were `
419
+ + 'already applied, so it would run them again. Review the migration and run repair again with --yes.');
420
+ }
421
+ }
422
+ const direction = mode === 'continue'
423
+ ? failure.direction
424
+ : failure.direction === 'up' ? 'down' : 'up';
425
+ const previous = order[order.indexOf(failure.migration) - 1];
426
+ console.info(`${mode === 'continue' ? 'finishing' : 'undoing'} ${failure.migration} (${direction})...`);
427
+ await runMigration(sequelize, failure.migration, entry, direction, { recordFailures: false, repairing: true });
428
+ const version = direction === 'up' ? failure.migration : previous;
429
+ if (version) {
430
+ await saveVersion(sequelize, version, updateAtFieldName);
431
+ }
432
+ await sequelize.getQueryInterface().dropTable(FAILURE_TABLE);
433
+ console.info('repaired. current version:', version);
434
+ }
435
+ function assertMySQL(sequelize, feature) {
436
+ if (!['mysql', 'mariadb'].includes(sequelize.getDialect())) {
437
+ throw new Error(`${feature} is only supported on MySQL and MariaDB.`);
438
+ }
439
+ }
440
+ /**
441
+ * A Sequelize instance for another database on the same server, with a single connection
442
+ * so session settings like FOREIGN_KEY_CHECKS apply to every statement.
443
+ */
444
+ function connect(sequelize, database) {
445
+ const SequelizeClass = sequelize.constructor;
446
+ return new SequelizeClass(database, sequelize.config.username, sequelize.config.password ?? undefined, {
447
+ ...sequelize.options,
448
+ logging: false,
449
+ pool: { max: 1, min: 0 },
450
+ });
451
+ }
452
+ /** Runs `callback` on a new, temporary database, which is dropped at the end. */
453
+ async function withTemporaryDatabase(sequelize, feature, callback) {
454
+ const name = `gina_tmp_${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
455
+ try {
456
+ await sequelize.query(`CREATE DATABASE \`${name}\`;`);
457
+ }
458
+ catch (err) {
459
+ throw new Error(`${feature} needs permission to create and drop databases: ${err.message}`);
460
+ }
461
+ const temporary = connect(sequelize, name);
462
+ try {
463
+ return await callback(temporary, name);
464
+ }
465
+ finally {
466
+ await temporary.close();
467
+ await sequelize.query(`DROP DATABASE IF EXISTS \`${name}\`;`);
468
+ }
469
+ }
470
+ /** `CREATE TABLE` statements of every table, without AUTO_INCREMENT counters. */
471
+ async function showCreateTables(sequelize) {
472
+ const tables = await sequelize.query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\';', {
473
+ type: sequelize_1.QueryTypes.SELECT,
474
+ });
475
+ const statements = [];
476
+ for (const table of tables.map(row => Object.values(row)[0]).sort()) {
477
+ const [definition] = await sequelize.query(`SHOW CREATE TABLE \`${table}\`;`, {
478
+ type: sequelize_1.QueryTypes.SELECT,
479
+ });
480
+ statements.push({ table, sql: definition['Create Table'].replace(/ AUTO_INCREMENT=\d+/, '') });
481
+ }
482
+ return statements;
483
+ }
484
+ async function createTables(sequelize, statements) {
485
+ await sequelize.query('SET FOREIGN_KEY_CHECKS = 0;');
486
+ for (const statement of statements) {
487
+ await sequelize.query(statement);
488
+ }
489
+ await sequelize.query('SET FOREIGN_KEY_CHECKS = 1;');
490
+ }
491
+ /**
492
+ * Applies the pending migrations to a copy of the database's schema (no data) in a temporary
493
+ * database, which is dropped at the end. MySQL/MariaDB only.
494
+ */
495
+ async function dryRunMigrations(sequelize, migrationFiles, updateAtFieldName) {
496
+ assertMySQL(sequelize, '--dry-run');
497
+ await assertNoFailure(sequelize);
498
+ const { order, entries } = resolveOrder(migrationFiles);
499
+ const version = await readVersion(sequelize);
500
+ const pending = order.slice(versionIndex(order, entries, version) + 1);
501
+ if (!pending.length) {
502
+ console.info('dry run: there are no pending migrations.');
503
+ return;
504
+ }
505
+ const database = sequelize.config.database;
506
+ await withTemporaryDatabase(sequelize, '--dry-run', async (copy, copyName) => {
507
+ console.info(`dry run: copying the schema of ${database} (without data) to ${copyName}...`);
508
+ const tables = await showCreateTables(sequelize);
509
+ await createTables(copy, tables.map(table => table.sql));
510
+ if (tables.some(table => table.table === 'gina_version')) {
511
+ await copy.query(`INSERT INTO gina_version SELECT * FROM \`${database}\`.gina_version;`);
512
+ }
513
+ console.info(`dry run: applying ${pending.length} migration(s)...`);
514
+ try {
515
+ await runMigrations(copy, migrationFiles, updateAtFieldName, { recordFailures: false });
516
+ }
517
+ catch (err) {
518
+ console.error(`dry run failed. Nothing was changed on ${database}.`);
519
+ throw err;
520
+ }
521
+ });
522
+ console.info(`dry run passed: ${pending.length} migration(s) applied cleanly to a copy of the schema. Nothing was changed on ${database}.`);
523
+ console.info('Errors that depend on the data can still happen, like duplicates on a new unique index or NULLs on a column that becomes NOT NULL.');
524
+ }
525
+ const SNAPSHOT_HEADER = `-- Generated by \`gina-cli snapshot\`: the schema after every migration up to the version below.
526
+ -- \`gina-cli upgrade --from-snapshot\` creates it on an empty database and then runs only the migrations after it.
527
+ -- Meant for development databases; the migrations are still the source of truth. Don't edit by hand.
528
+ `;
529
+ /**
530
+ * Runs every migration on a temporary database and writes the resulting schema to `snapshotFile`.
531
+ * Data inserted by migrations isn't part of it.
532
+ */
533
+ async function createSnapshot(sequelize, migrationFiles, snapshotFile, updateAtFieldName) {
534
+ assertMySQL(sequelize, 'snapshot');
535
+ const { order, entries } = resolveOrder(migrationFiles);
536
+ if (!order.length) {
537
+ throw new Error('There are no migrations to snapshot.');
538
+ }
539
+ const withData = [];
540
+ for (const name of order) {
541
+ const filePath = entries.get(name)?.filePath;
542
+ if (filePath && /\.(query|bulkInsert|bulkUpdate|bulkDelete)\s*\(/.test(await promises_1.default.readFile(filePath, 'utf8'))) {
543
+ withData.push(name);
544
+ }
545
+ }
546
+ const statements = await withTemporaryDatabase(sequelize, 'snapshot', async (temporary) => {
547
+ console.info(`snapshot: running ${order.length} migration(s) on a temporary database...`);
548
+ await runMigrations(temporary, migrationFiles, updateAtFieldName, { recordFailures: false, quiet: true });
549
+ return showCreateTables(temporary);
550
+ });
551
+ const version = order[order.length - 1];
552
+ await promises_1.default.writeFile(snapshotFile, `${SNAPSHOT_HEADER}-- version: ${version}\n\n${statements.map(statement => `${statement.sql};`).join('\n\n')}\n`);
553
+ console.info(`snapshot written: ${snapshotFile} (version ${version}, ${statements.length} tables)`);
554
+ if (withData.length) {
555
+ console.warn('These migrations run raw queries or bulk operations. If they insert or change data, '
556
+ + `that data isn't in the snapshot:\n${withData.map(name => ` - ${name}`).join('\n')}`);
557
+ }
558
+ }
559
+ /**
560
+ * Creates the schema from a snapshot on an empty database, then applies the migrations after it.
561
+ */
562
+ async function upgradeFromSnapshot(sequelize, migrationFiles, snapshotFile, updateAtFieldName = 'updatedAt') {
563
+ assertMySQL(sequelize, '--from-snapshot');
564
+ let content;
565
+ try {
566
+ content = await promises_1.default.readFile(snapshotFile, 'utf8');
567
+ }
568
+ catch {
569
+ throw new Error(`Snapshot not found: ${snapshotFile}. Create it with \`gina-cli snapshot\`.`);
570
+ }
571
+ const version = /^-- version: (.+)$/m.exec(content)?.[1]?.trim();
572
+ if (!version) {
573
+ throw new Error(`${snapshotFile} doesn't say which version it's at. Create it again with \`gina-cli snapshot\`.`);
574
+ }
575
+ const tables = await sequelize.getQueryInterface().showAllTables();
576
+ if (tables.length) {
577
+ throw new Error(`--from-snapshot only works on an empty database, and ${sequelize.config.database} has ${tables.length} table(s). `
578
+ + 'Use upgrade without it, or start from an empty database.');
579
+ }
580
+ const { order } = resolveOrder(migrationFiles);
581
+ if (!order.includes(version)) {
582
+ throw new Error(`The snapshot is at ${version}, which doesn't match any migration file. Create it again with \`gina-cli snapshot\`.`);
583
+ }
584
+ const statements = content
585
+ .split('\n')
586
+ .filter(line => !line.startsWith('--'))
587
+ .join('\n')
588
+ .split(/;\n\n/)
589
+ .map(statement => statement.trim().replace(/;$/, ''))
590
+ .filter(Boolean);
591
+ console.info(`creating ${statements.length} tables from ${snapshotFile} (version ${version})...`);
592
+ const connection = connect(sequelize, sequelize.config.database);
593
+ try {
594
+ await createTables(connection, statements);
595
+ }
596
+ finally {
597
+ await connection.close();
598
+ }
599
+ await saveVersion(sequelize, version, updateAtFieldName);
600
+ await runMigrations(sequelize, migrationFiles, updateAtFieldName);
601
+ }
602
+ //# sourceMappingURL=runner.js.map