masterrecord 1.23.0 → 1.27.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.
@@ -0,0 +1,361 @@
1
+ // Ported from Entity Framework Core (dotnet/efcore, MIT) —
2
+ // Migrations/Internal/Migrator.cs. See THIRD-PARTY-NOTICES.md.
3
+
4
+ import MigrationsAssembly from './MigrationsAssembly.js';
5
+ import { createHistoryRepository } from './HistoryRepository.js';
6
+ import HistoryRow from './HistoryRow.js';
7
+
8
+ /**
9
+ * Decides which migrations to apply and which to revert (EF `Migrator`).
10
+ *
11
+ * This is the planning half of EF's Migrator, ported faithfully. Applying a
12
+ * migration is still done by the `masterrecord update-database` CLI, which owns
13
+ * the snapshot handling and the per-migration transaction; this class is what
14
+ * answers "what is pending?" and "what would `--target X` do?".
15
+ */
16
+ class Migrator {
17
+ /** EF's sentinel target meaning "revert everything" (Migration.InitialDatabase). */
18
+ static InitialDatabase = '0';
19
+
20
+ /**
21
+ * @param {{historyRepository?: object, migrationsAssembly?: MigrationsAssembly, migrationsPath?: string}} dependencies
22
+ */
23
+ constructor(dependencies = {}) {
24
+ this.dependencies = dependencies;
25
+ this._assembly = dependencies.migrationsAssembly
26
+ || new MigrationsAssembly({ migrationsPath: dependencies.migrationsPath, files: dependencies.files });
27
+ }
28
+
29
+ get migrationsAssembly() { return this._assembly; }
30
+ get historyRepository() { return this.dependencies.historyRepository; }
31
+
32
+ /** Every migration on disk, oldest first (EF: GetMigrations). */
33
+ getMigrations() { return this.migrationsAssembly.migrationIds; }
34
+
35
+ /** Migration ids recorded as applied (EF: GetAppliedMigrations). */
36
+ async getAppliedMigrations() {
37
+ if (!this.historyRepository) throw new Error('masterrecord: Migrator needs a historyRepository to read applied migrations.');
38
+ const rows = await this.historyRepository.getAppliedMigrations();
39
+ return rows.map(r => r.migrationId);
40
+ }
41
+
42
+ /** On disk but not recorded as applied (EF: GetPendingMigrations = GetMigrations except applied). */
43
+ async getPendingMigrations() {
44
+ const applied = new Set((await this.getAppliedMigrations()).map(id => id.toLowerCase()));
45
+ return this.getMigrations().filter(id => !applied.has(id.toLowerCase()));
46
+ }
47
+
48
+ /**
49
+ * EF's PopulateMigrations: split the known migrations into those to apply and
50
+ * those to revert for a given target.
51
+ *
52
+ * - no target -> apply every unapplied migration, revert nothing
53
+ * - target === '0' -> revert every applied migration, apply nothing
54
+ * - target === some id -> apply unapplied migrations up to and including it,
55
+ * revert applied migrations after it (newest first)
56
+ *
57
+ * @param {Iterable<string>} appliedMigrationEntries - ids currently in the history table
58
+ * @param {string|null} targetMigration
59
+ * @returns {{migrationsToApply: string[], migrationsToRevert: string[], targetMigration: string|null}}
60
+ */
61
+ populateMigrations(appliedMigrationEntries, targetMigration) {
62
+ const appliedSet = new Set([...(appliedMigrationEntries || [])].map(id => String(id).toLowerCase()));
63
+ const all = this.getMigrations();
64
+ const applied = all.filter(id => appliedSet.has(id.toLowerCase()));
65
+ const unapplied = all.filter(id => !appliedSet.has(id.toLowerCase()));
66
+
67
+ const cmp = MigrationsAssembly.compareIds;
68
+
69
+ if (targetMigration === null || targetMigration === undefined || targetMigration === '') {
70
+ return { migrationsToApply: [...unapplied], migrationsToRevert: [], targetMigration: null };
71
+ }
72
+
73
+ if (String(targetMigration) === Migrator.InitialDatabase) {
74
+ return {
75
+ migrationsToApply: [],
76
+ migrationsToRevert: [...applied].reverse(),
77
+ targetMigration: null,
78
+ };
79
+ }
80
+
81
+ const target = this.migrationsAssembly.getMigrationId(targetMigration);
82
+ return {
83
+ migrationsToApply: unapplied.filter(id => cmp(id, target) <= 0),
84
+ migrationsToRevert: applied.filter(id => cmp(id, target) > 0).reverse(),
85
+ targetMigration: applied.find(id => cmp(id, target) === 0) || null,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * The plan for a target, read against the live history table
91
+ * (EF: what Migrate(targetMigration) would do).
92
+ */
93
+ async plan(targetMigration = null) {
94
+ return this.populateMigrations(await this.getAppliedMigrations(), targetMigration);
95
+ }
96
+
97
+ // ---- applying (EF: Migrator.Migrate) ---------------------------------
98
+
99
+ get context() { return this.dependencies.context; }
100
+ get databaseCreator() { return this.dependencies.databaseCreator; }
101
+
102
+ _log(event, ...args) {
103
+ const logger = this.dependencies.logger;
104
+ if (logger && typeof logger[event] === 'function') logger[event](...args);
105
+ }
106
+
107
+ /**
108
+ * The `table` object every migration's up()/down() receives: the diff between
109
+ * the snapshot's schema and the context's current entities. EF hands the
110
+ * migration its model; masterrecord hands it this.
111
+ */
112
+ async _tableObject() {
113
+ if (this._tableObj) return this._tableObj;
114
+ if (this.dependencies.tableObj) { this._tableObj = this.dependencies.tableObj; return this._tableObj; }
115
+ const snapshot = this.dependencies.snapshot;
116
+ if (!snapshot) throw new Error('masterrecord: Migrator.migrate() needs the context snapshot (or an explicit tableObj).');
117
+ // dynamic: migrations.js -> schema.js -> context.js would close an import cycle
118
+ const { default: Migration } = await import('./migrations.js');
119
+ const helper = new Migration();
120
+ const cleanEntities = helper.cleanEntities(this.context.__entities);
121
+ this._tableObj = helper.buildUpObject(snapshot.schema, cleanEntities);
122
+ return this._tableObj;
123
+ }
124
+
125
+ async _loadMigration(file) {
126
+ const loader = this.dependencies.loadMigration;
127
+ if (loader) return loader(file);
128
+ const { pathToFileURL } = await import('node:url');
129
+ const mod = await import(pathToFileURL(file).href);
130
+ return (mod && mod.default !== undefined) ? mod.default : mod;
131
+ }
132
+
133
+ /**
134
+ * Run one migration and record it, atomically where the engine allows it
135
+ * (EF applies each migration in its own transaction; MySQL autocommits DDL).
136
+ */
137
+ async _executeMigration(id, direction) {
138
+ const file = this.migrationsAssembly.getMigrationFile(id);
139
+ if (!file) throw new Error(`masterrecord: migration '${id}' was recorded or planned but its file is missing.`);
140
+ const MigrationCtor = await this._loadMigration(file);
141
+ const instance = new MigrationCtor(this.dependencies.contextCtor);
142
+ const ctx = (instance && instance.context) ? instance.context : this.context;
143
+ const tableObj = await this._tableObject();
144
+
145
+ this._log(direction === 'down' ? 'migrationReverting' : 'migrationApplying', id);
146
+
147
+ // The migration runs on ITS OWN context (schema's constructor builds one), and
148
+ // the history row must be written on that same connection — otherwise the DDL
149
+ // and the row land in different transactions, and on SQLite the second
150
+ // connection blocks on the first one's write lock.
151
+ const history = (ctx === this.context)
152
+ ? this.historyRepository
153
+ : createHistoryRepository(ctx, { productVersion: this.historyRepository.productVersion });
154
+
155
+ const run = async () => {
156
+ if (direction === 'down') await instance.down(tableObj);
157
+ else await instance.up(tableObj);
158
+ if (typeof instance.finalize === 'function') await instance.finalize();
159
+ if (direction === 'down') await history.recordReverted(id);
160
+ else await history.recordApplied(id);
161
+ };
162
+
163
+ let mode = 'autocommit';
164
+ if (ctx.isMySQL || typeof ctx.transaction !== 'function') {
165
+ await run();
166
+ } else {
167
+ // SQLite: a table rebuild inside the migration drops and recreates
168
+ // tables, which foreign keys would veto mid-flight.
169
+ let fkWasOn = false;
170
+ if (ctx.isSQLite) {
171
+ await ctx._ensureReady();
172
+ try { fkWasOn = ctx._SQLEngine.db.pragma('foreign_keys', { simple: true }) === 1; } catch (_) { /* older driver */ }
173
+ if (fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = OFF'); } catch (_) { /* ignore */ } }
174
+ }
175
+ try {
176
+ await ctx.transaction(run);
177
+ mode = 'transaction';
178
+ } finally {
179
+ if (ctx.isSQLite && fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = ON'); } catch (_) { /* ignore */ } }
180
+ }
181
+ }
182
+
183
+ // Each migration's schema constructor opens its OWN context; release it so
184
+ // connections do not accumulate across a batch of migrations or contexts.
185
+ if (ctx !== this.context && typeof ctx.close === 'function') {
186
+ try { await ctx.close(); } catch (_) { /* best-effort teardown */ }
187
+ }
188
+
189
+ this._log(direction === 'down' ? 'migrationReverted' : 'migrationApplied', id, mode);
190
+ return mode;
191
+ }
192
+
193
+ /**
194
+ * The SQL a migration would run, captured instead of executed.
195
+ *
196
+ * schema.js issues all DDL/DML through `context._execute`, so swapping that out
197
+ * records the statements while engine-level introspection (tableExists /
198
+ * getTableInfo) still reads the real database — the script therefore reflects
199
+ * what update-database would actually do. This is masterrecord's stand-in for
200
+ * EF's MigrationsSqlGenerator, which can generate SQL without a connection.
201
+ */
202
+ async _captureSql(id, direction) {
203
+ const file = this.migrationsAssembly.getMigrationFile(id);
204
+ if (!file) throw new Error(`masterrecord: migration '${id}' has no file on disk.`);
205
+ const MigrationCtor = await this._loadMigration(file);
206
+ const instance = new MigrationCtor(this.dependencies.contextCtor);
207
+ const mctx = (instance && instance.context) ? instance.context : this.context;
208
+ const tableObj = await this._tableObject();
209
+
210
+ const captured = [];
211
+ const fmt = (q, p) => {
212
+ const text = String(q).replace(/\s+/g, ' ').trim().replace(/;$/, '');
213
+ return (p && p.length) ? `${text}; -- params: ${JSON.stringify(p)}` : `${text};`;
214
+ };
215
+ const patch = (c) => {
216
+ const orig = c._execute;
217
+ c._execute = (q, p) => { captured.push(fmt(q, p)); return Promise.resolve({ changes: 0, rowCount: 0, affectedRows: 0 }); };
218
+ return () => { c._execute = orig; };
219
+ };
220
+ const restores = [patch(mctx)];
221
+ if (mctx !== this.context) restores.push(patch(this.context));
222
+ try {
223
+ if (direction === 'down') await instance.down(tableObj);
224
+ else await instance.up(tableObj);
225
+ if (typeof instance.finalize === 'function') await instance.finalize();
226
+ } finally {
227
+ for (const r of restores) r();
228
+ }
229
+ if (mctx !== this.context && typeof mctx.close === 'function') {
230
+ try { await mctx.close(); } catch (_) { /* best-effort teardown */ }
231
+ }
232
+ return captured;
233
+ }
234
+
235
+ /**
236
+ * Generate the SQL for a migration range without applying it
237
+ * (EF: Migrator.GenerateScript).
238
+ *
239
+ * `fromMigration` is the state the script assumes the database is already in:
240
+ * omitted or '0' means an empty database, so everything is scripted. Pass
241
+ * `options.appliedMigrations` to script against what a live database has
242
+ * actually applied (what `masterrecord script` does — "the pending ones").
243
+ * `options.idempotent` wraps each migration in a "only if not already applied"
244
+ * guard; providers that cannot express that (SQLite, MySQL) refuse, as EF's
245
+ * SQLite provider does.
246
+ */
247
+ async generateScript(fromMigration = null, toMigration = null, options = {}) {
248
+ const { idempotent = false, appliedMigrations = null } = options;
249
+ const all = this.getMigrations();
250
+
251
+ let applied;
252
+ if (appliedMigrations) {
253
+ applied = [...appliedMigrations];
254
+ } else if (!fromMigration || String(fromMigration) === Migrator.InitialDatabase) {
255
+ applied = [];
256
+ } else {
257
+ const fromId = this.migrationsAssembly.getMigrationId(fromMigration);
258
+ applied = all.filter(id => MigrationsAssembly.compareIds(id, fromId) <= 0);
259
+ }
260
+
261
+ const plan = this.populateMigrations(applied, toMigration);
262
+ const lines = [];
263
+
264
+ // EF emits the history-table bootstrap when scripting from an empty database.
265
+ if (!appliedMigrations && (!fromMigration || String(fromMigration) === Migrator.InitialDatabase)) {
266
+ lines.push(this.historyRepository.getCreateIfNotExistsScript().replace(/;?$/, ';'));
267
+ lines.push('');
268
+ }
269
+
270
+ const endIf = idempotent ? this.historyRepository.getEndIfScript() : null;
271
+
272
+ for (const id of plan.migrationsToRevert) {
273
+ lines.push(`-- Migration: ${id} (down)`);
274
+ if (idempotent) lines.push(this.historyRepository.getBeginIfExistsScript(id));
275
+ lines.push(...await this._captureSql(id, 'down'));
276
+ lines.push(this.historyRepository.getDeleteScript(id).replace(/;?$/, ';'));
277
+ if (idempotent) lines.push(endIf);
278
+ lines.push('');
279
+ }
280
+ for (const id of plan.migrationsToApply) {
281
+ lines.push(`-- Migration: ${id}`);
282
+ if (idempotent) lines.push(this.historyRepository.getBeginIfNotExistsScript(id));
283
+ lines.push(...await this._captureSql(id, 'up'));
284
+ // A literal INSERT, not a parameterized one: a script has to be runnable
285
+ // as-is by a DBA, and '?' placeholders are not.
286
+ lines.push(this.historyRepository.getInsertScript(
287
+ new HistoryRow(id, this.historyRepository.productVersion, new Date().toISOString())).replace(/;?$/, ';'));
288
+ if (idempotent) lines.push(endIf);
289
+ lines.push('');
290
+ }
291
+
292
+ return { sql: lines.join('\n'), migrationsToApply: plan.migrationsToApply, migrationsToRevert: plan.migrationsToRevert };
293
+ }
294
+
295
+ /**
296
+ * Does the model have changes that no migration captures yet?
297
+ * (EF: Migrator.HasPendingModelChanges)
298
+ */
299
+ async hasPendingModelChanges() {
300
+ const snapshot = this.dependencies.snapshot;
301
+ if (!snapshot) throw new Error('masterrecord: hasPendingModelChanges() needs the context snapshot.');
302
+ const { default: Migration } = await import('./migrations.js');
303
+ const helper = new Migration();
304
+ const cleanEntities = helper.cleanEntities(this.context.__entities);
305
+ return helper.hasChanges(snapshot.schema, cleanEntities, this.context.__contextSeedData || {});
306
+ }
307
+
308
+ /**
309
+ * Apply one migration and record it. EF has no single-migration entry point
310
+ * (you give Migrate a target), but the CLI needs one for its targeted
311
+ * operations — and routing them here keeps ONE execution path, so every
312
+ * command gets the same transaction and history handling.
313
+ */
314
+ async applyMigration(id) {
315
+ await this.historyRepository.createIfNotExists();
316
+ return this._executeMigration(id, 'up');
317
+ }
318
+
319
+ /** Revert one migration and remove its history row. */
320
+ async revertMigration(id) {
321
+ await this.historyRepository.createIfNotExists();
322
+ return this._executeMigration(id, 'down');
323
+ }
324
+
325
+ /**
326
+ * Bring the database to `targetMigration` (EF: Migrator.Migrate).
327
+ *
328
+ * migrate() -> apply every pending migration
329
+ * migrate('Name') -> migrate up or down to that migration
330
+ * migrate('0') -> revert everything (EF's InitialDatabase)
331
+ *
332
+ * Creates the database and the history table if they are missing, then reverts
333
+ * newest-first and applies oldest-first, recording each migration as it goes so
334
+ * an interrupted run resumes from where it stopped.
335
+ */
336
+ async migrate(targetMigration = null) {
337
+ if (this.databaseCreator && !(await this.databaseCreator.exists())) {
338
+ await this.databaseCreator.create();
339
+ }
340
+ await this.historyRepository.createIfNotExists();
341
+
342
+ const plan = await this.plan(targetMigration);
343
+ const reverted = [];
344
+ const applied = [];
345
+
346
+ for (const id of plan.migrationsToRevert) {
347
+ await this._executeMigration(id, 'down');
348
+ reverted.push(id);
349
+ }
350
+ for (const id of plan.migrationsToApply) {
351
+ await this._executeMigration(id, 'up');
352
+ applied.push(id);
353
+ }
354
+ if (!applied.length && !reverted.length) this._log('migrationsNotApplied');
355
+
356
+ return { applied, reverted, targetMigration: plan.targetMigration };
357
+ }
358
+ }
359
+
360
+ export default Migrator;
361
+ export { Migrator };