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.
- package/CHANGES.md +166 -0
- package/Entity/entityTrackerModel.js +0 -3
- package/Migrations/DatabaseFacade.js +230 -0
- package/Migrations/HistoryRepository.js +278 -0
- package/Migrations/HistoryRow.js +26 -0
- package/Migrations/MigrationsAssembly.js +83 -0
- package/Migrations/Migrator.js +361 -0
- package/Migrations/RelationalDatabaseCreator.js +363 -0
- package/Migrations/cli.js +245 -263
- package/Migrations/migrationId.js +32 -0
- package/Migrations/migrationSQLiteQuery.js +3 -3
- package/SQLLiteEngine.js +4 -1
- package/context.js +11 -0
- package/mySQLEngine.js +1 -1
- package/package.json +12 -3
package/Migrations/cli.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// version 0.1.0 - ESM only
|
|
4
|
-
// https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/
|
|
5
4
|
// how to add environment variables on cli call example - master=development masterrecord add-migration auth authContext
|
|
6
5
|
|
|
7
6
|
import { program } from 'commander';
|
|
@@ -13,6 +12,8 @@ import { resolveMigrationsDirectory, toPosixPath } from './pathUtils.js';
|
|
|
13
12
|
import Migration from './migrations.js';
|
|
14
13
|
import schema from './schema.js';
|
|
15
14
|
import { instantiateReadyContext } from './contextInit.js';
|
|
15
|
+
import Migrator from './Migrator.js';
|
|
16
|
+
import MigrationsAssembly from './MigrationsAssembly.js';
|
|
16
17
|
|
|
17
18
|
const __filename = fileURLToPath(import.meta.url);
|
|
18
19
|
const __dirname = path.dirname(__filename);
|
|
@@ -68,7 +69,6 @@ function __normalizeSnapshotPaths(snapshot){
|
|
|
68
69
|
}
|
|
69
70
|
return snapshot;
|
|
70
71
|
}
|
|
71
|
-
|
|
72
72
|
// Extract numeric timestamp from migration filename (e.g., 1737999999999_name_migration.js)
|
|
73
73
|
function __getMigrationTimestamp(file){
|
|
74
74
|
try{
|
|
@@ -82,131 +82,6 @@ function __getMigrationTimestamp(file){
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
// ============================================================================
|
|
86
|
-
// Migration tracking — one row per applied migration filename.
|
|
87
|
-
// Without this, update-database cannot tell which files are pending, so it
|
|
88
|
-
// used to run only the last one and silently skip the rest.
|
|
89
|
-
// ============================================================================
|
|
90
|
-
|
|
91
|
-
const __MIGRATIONS_TABLE__ = '_masterrecord_migrations';
|
|
92
|
-
|
|
93
|
-
async function __ensureMigrationsTable(ctx){
|
|
94
|
-
if (ctx.isSQLite) {
|
|
95
|
-
await ctx._execute(`CREATE TABLE IF NOT EXISTS [${__MIGRATIONS_TABLE__}] (
|
|
96
|
-
migration_name TEXT PRIMARY KEY,
|
|
97
|
-
applied_at TEXT NOT NULL
|
|
98
|
-
)`);
|
|
99
|
-
} else if (ctx.isMySQL) {
|
|
100
|
-
await ctx._execute(`CREATE TABLE IF NOT EXISTS \`${__MIGRATIONS_TABLE__}\` (
|
|
101
|
-
migration_name VARCHAR(255) PRIMARY KEY,
|
|
102
|
-
applied_at VARCHAR(64) NOT NULL
|
|
103
|
-
)`);
|
|
104
|
-
} else if (ctx.isPostgres) {
|
|
105
|
-
await ctx._execute(`CREATE TABLE IF NOT EXISTS "${__MIGRATIONS_TABLE__}" (
|
|
106
|
-
migration_name VARCHAR(255) PRIMARY KEY,
|
|
107
|
-
applied_at VARCHAR(64) NOT NULL
|
|
108
|
-
)`);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
async function __getAppliedMigrations(ctx){
|
|
113
|
-
const applied = new Set();
|
|
114
|
-
const engine = ctx._SQLEngine;
|
|
115
|
-
let rows;
|
|
116
|
-
try {
|
|
117
|
-
if (ctx.isSQLite) {
|
|
118
|
-
rows = engine.db.prepare(`SELECT migration_name FROM [${__MIGRATIONS_TABLE__}]`).all();
|
|
119
|
-
} else if (ctx.isMySQL) {
|
|
120
|
-
rows = await engine._runWithParams(`SELECT migration_name FROM \`${__MIGRATIONS_TABLE__}\``, []);
|
|
121
|
-
} else if (ctx.isPostgres) {
|
|
122
|
-
const r = await engine._runWithParams(`SELECT migration_name FROM "${__MIGRATIONS_TABLE__}"`, []);
|
|
123
|
-
rows = r && r.rows ? r.rows : [];
|
|
124
|
-
}
|
|
125
|
-
} catch (_) {
|
|
126
|
-
rows = [];
|
|
127
|
-
}
|
|
128
|
-
for (const r of (rows || [])) {
|
|
129
|
-
if (r && r.migration_name) applied.add(r.migration_name);
|
|
130
|
-
}
|
|
131
|
-
return applied;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
async function __recordMigrationApplied(ctx, migrationName){
|
|
135
|
-
const appliedAt = new Date().toISOString();
|
|
136
|
-
if (ctx.isSQLite) {
|
|
137
|
-
await ctx._execute(`INSERT INTO [${__MIGRATIONS_TABLE__}] (migration_name, applied_at) VALUES (?, ?)`, [migrationName, appliedAt]);
|
|
138
|
-
} else if (ctx.isMySQL) {
|
|
139
|
-
await ctx._execute(`INSERT INTO \`${__MIGRATIONS_TABLE__}\` (migration_name, applied_at) VALUES (?, ?)`, [migrationName, appliedAt]);
|
|
140
|
-
} else if (ctx.isPostgres) {
|
|
141
|
-
await ctx._execute(`INSERT INTO "${__MIGRATIONS_TABLE__}" (migration_name, applied_at) VALUES ($1, $2)`, [migrationName, appliedAt]);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
async function __removeMigrationApplied(ctx, migrationName){
|
|
146
|
-
if (ctx.isSQLite) {
|
|
147
|
-
await ctx._execute(`DELETE FROM [${__MIGRATIONS_TABLE__}] WHERE migration_name = ?`, [migrationName]);
|
|
148
|
-
} else if (ctx.isMySQL) {
|
|
149
|
-
await ctx._execute(`DELETE FROM \`${__MIGRATIONS_TABLE__}\` WHERE migration_name = ?`, [migrationName]);
|
|
150
|
-
} else if (ctx.isPostgres) {
|
|
151
|
-
await ctx._execute(`DELETE FROM "${__MIGRATIONS_TABLE__}" WHERE migration_name = $1`, [migrationName]);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** Applied migrations with timestamps: [{ migration_name, applied_at }] (EF `migrations list`). */
|
|
156
|
-
async function __getAppliedMigrationRows(ctx){
|
|
157
|
-
const engine = ctx._SQLEngine;
|
|
158
|
-
try {
|
|
159
|
-
if (ctx.isSQLite) {
|
|
160
|
-
return engine.db.prepare(`SELECT migration_name, applied_at FROM [${__MIGRATIONS_TABLE__}] ORDER BY applied_at`).all();
|
|
161
|
-
} else if (ctx.isMySQL) {
|
|
162
|
-
return await engine._runWithParams(`SELECT migration_name, applied_at FROM \`${__MIGRATIONS_TABLE__}\` ORDER BY applied_at`, []);
|
|
163
|
-
} else if (ctx.isPostgres) {
|
|
164
|
-
const r = await engine._runWithParams(`SELECT migration_name, applied_at FROM "${__MIGRATIONS_TABLE__}" ORDER BY applied_at`, []);
|
|
165
|
-
return r && r.rows ? r.rows : [];
|
|
166
|
-
}
|
|
167
|
-
} catch (_) { /* table may not exist yet */ }
|
|
168
|
-
return [];
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Apply ONE migration step atomically (EF Core: each migration runs in its own
|
|
173
|
-
* transaction). The migration's DDL/DML and its tracking-table row commit or
|
|
174
|
-
* roll back together, so a failure can never leave a half-applied schema that
|
|
175
|
-
* is (or isn't) recorded.
|
|
176
|
-
* - PostgreSQL: transactional DDL -> BEGIN ... COMMIT.
|
|
177
|
-
* - SQLite: transactional DDL too, but `PRAGMA foreign_keys` is a no-op inside
|
|
178
|
-
* a transaction and the table-rebuild path relies on toggling it, so FK
|
|
179
|
-
* enforcement is switched off BEFORE the transaction and restored after
|
|
180
|
-
* (exactly what EF does for SQLite rebuilds).
|
|
181
|
-
* - MySQL: DDL implicitly commits, so a migration cannot be made atomic there
|
|
182
|
-
* (EF documents the same limitation); statements run directly.
|
|
183
|
-
* Runs on the migration's own context (it shares the engine/connection with
|
|
184
|
-
* `contextInstance`), so the tracking row is written inside the same transaction.
|
|
185
|
-
*/
|
|
186
|
-
async function __applyMigrationStep(contextInstance, instance, tableObj, migrationName, direction = 'up'){
|
|
187
|
-
const ctx = (instance && instance.context) ? instance.context : contextInstance;
|
|
188
|
-
const run = async () => {
|
|
189
|
-
if (direction === 'down') await instance.down(tableObj); else await instance.up(tableObj);
|
|
190
|
-
if (typeof instance.finalize === 'function') await instance.finalize();
|
|
191
|
-
if (direction === 'down') await __removeMigrationApplied(ctx, migrationName);
|
|
192
|
-
else await __recordMigrationApplied(ctx, migrationName);
|
|
193
|
-
};
|
|
194
|
-
if (ctx.isMySQL || typeof ctx.transaction !== 'function') { await run(); return 'autocommit'; }
|
|
195
|
-
|
|
196
|
-
let fkWasOn = false;
|
|
197
|
-
if (ctx.isSQLite) {
|
|
198
|
-
await ctx._ensureReady();
|
|
199
|
-
try { fkWasOn = ctx._SQLEngine.db.pragma('foreign_keys', { simple: true }) === 1; } catch (_) { /* older driver */ }
|
|
200
|
-
if (fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = OFF'); } catch (_) { /* ignore */ } }
|
|
201
|
-
}
|
|
202
|
-
try {
|
|
203
|
-
await ctx.transaction(run);
|
|
204
|
-
return 'transaction';
|
|
205
|
-
} finally {
|
|
206
|
-
if (ctx.isSQLite && fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = ON'); } catch (_) { /* ignore */ } }
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
85
|
/** Resolve everything a migration command needs for a context (snapshot, files, constructor). */
|
|
211
86
|
async function __resolveMigrationPlan(contextFileName){
|
|
212
87
|
const executedLocation = process.cwd();
|
|
@@ -653,46 +528,51 @@ program.hook('preAction', () => {
|
|
|
653
528
|
// no-ops on undefined `table.col`) make this safe in practice.
|
|
654
529
|
const tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
|
|
655
530
|
|
|
656
|
-
//
|
|
657
|
-
//
|
|
658
|
-
//
|
|
531
|
+
// EF: `dotnet ef database update` is a thin shell over IMigrator.Migrate().
|
|
532
|
+
// Planning, the per-migration transaction and the history bookkeeping all
|
|
533
|
+
// live in Migrations/Migrator.js — this command only supplies the snapshot,
|
|
534
|
+
// the migration files and the console output.
|
|
535
|
+
let currentMigration = null;
|
|
536
|
+
const migrator = new Migrator({
|
|
537
|
+
context: contextInstance,
|
|
538
|
+
contextCtor: ContextCtor,
|
|
539
|
+
snapshot: contextSnapshot,
|
|
540
|
+
tableObj,
|
|
541
|
+
migrationsAssembly: new MigrationsAssembly({ files: mFiles }),
|
|
542
|
+
historyRepository: contextInstance.database.historyRepository,
|
|
543
|
+
databaseCreator: contextInstance.database.databaseCreator,
|
|
544
|
+
loadMigration: __loadUserModule,
|
|
545
|
+
logger: {
|
|
546
|
+
migrationApplying: (id) => { currentMigration = id; console.log(`\n → ${id}`); },
|
|
547
|
+
migrationApplied: (id, mode) => console.log(` ✓ applied${mode === 'transaction' ? ' (transactional)' : ''}`),
|
|
548
|
+
},
|
|
549
|
+
});
|
|
550
|
+
|
|
659
551
|
try {
|
|
660
|
-
await
|
|
552
|
+
const alreadyApplied = await contextInstance.database.getAppliedMigrations();
|
|
553
|
+
const pendingCount = mFiles.filter(f => !alreadyApplied.includes(path.basename(f))).length;
|
|
554
|
+
if (pendingCount === 0) {
|
|
555
|
+
console.log(`\n✓ All migrations already applied (${alreadyApplied.length} on record). Database is up to date.`);
|
|
556
|
+
} else {
|
|
557
|
+
console.log(`\n🚀 Running ${pendingCount} pending migration(s)...`);
|
|
558
|
+
}
|
|
661
559
|
} catch (err) {
|
|
662
|
-
console.error(`\n❌ Error - Could not
|
|
560
|
+
console.error(`\n❌ Error - Could not read the migration tracking table`);
|
|
663
561
|
console.error(`\nDetails: ${err.message}`);
|
|
664
562
|
await __cleanupAndExit(contextInstance, 1);
|
|
665
563
|
}
|
|
666
564
|
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
console.
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
for (const mFile of pending) {
|
|
677
|
-
const migrationName = path.basename(mFile);
|
|
678
|
-
console.log(`\n → ${migrationName}`);
|
|
679
|
-
try {
|
|
680
|
-
const MigrationCtor = await __loadUserModule(mFile);
|
|
681
|
-
const instance = new MigrationCtor(ContextCtor);
|
|
682
|
-
// Atomic: DDL + tracking row commit/roll back together (EF: one
|
|
683
|
-
// transaction per migration; MySQL DDL autocommits — see helper).
|
|
684
|
-
const mode = await __applyMigrationStep(contextInstance, instance, tableObj, migrationName, 'up');
|
|
685
|
-
console.log(` ✓ applied${mode === 'transaction' ? ' (transactional)' : ''}`);
|
|
686
|
-
} catch (err) {
|
|
687
|
-
console.error(`\n❌ Error - Migration '${migrationName}' failed during execution`);
|
|
688
|
-
console.error(`\nDetails: ${err.message}`);
|
|
689
|
-
if (err.stack) {
|
|
690
|
-
console.error(`\nStack trace:`);
|
|
691
|
-
console.error(err.stack);
|
|
692
|
-
}
|
|
693
|
-
console.error(`\n💡 Earlier migrations (if any) were already applied and recorded. Fix the failing migration and re-run update-database to resume from this point.`);
|
|
694
|
-
await __cleanupAndExit(contextInstance, 1);
|
|
565
|
+
try {
|
|
566
|
+
await migrator.migrate();
|
|
567
|
+
} catch (err) {
|
|
568
|
+
console.error(`\n❌ Error - Migration '${currentMigration || "(unknown)"}' failed during execution`);
|
|
569
|
+
console.error(`\nDetails: ${err.message}`);
|
|
570
|
+
if (err.stack) {
|
|
571
|
+
console.error(`\nStack trace:`);
|
|
572
|
+
console.error(err.stack);
|
|
695
573
|
}
|
|
574
|
+
console.error(`\n💡 Earlier migrations (if any) were already applied and recorded. Fix the failing migration and re-run update-database to resume from this point.`);
|
|
575
|
+
await __cleanupAndExit(contextInstance, 1);
|
|
696
576
|
}
|
|
697
577
|
|
|
698
578
|
console.log(`\n💾 Updating snapshot...`);
|
|
@@ -813,29 +693,30 @@ program.hook('preAction', () => {
|
|
|
813
693
|
// latest migration file on disk if the tracking table is missing or
|
|
814
694
|
// empty (preserves legacy behavior for users who haven't run
|
|
815
695
|
// update-database under the tracked system yet).
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
696
|
+
// Reverting goes through Migrator too, so a rollback gets the same
|
|
697
|
+
// per-migration transaction and history bookkeeping as applying does
|
|
698
|
+
// (it used to run down() outside any transaction).
|
|
699
|
+
const downMigrator = new Migrator({
|
|
700
|
+
context: contextInstance,
|
|
701
|
+
contextCtor: ContextCtor,
|
|
702
|
+
snapshot: contextSnapshot,
|
|
703
|
+
tableObj,
|
|
704
|
+
migrationsAssembly: new MigrationsAssembly({ files: mFiles }),
|
|
705
|
+
historyRepository: contextInstance.database.historyRepository,
|
|
706
|
+
databaseCreator: contextInstance.database.databaseCreator,
|
|
707
|
+
loadMigration: __loadUserModule,
|
|
708
|
+
});
|
|
709
|
+
const applied = await contextInstance.database.getAppliedMigrations();
|
|
819
710
|
let rollbackName;
|
|
820
|
-
if (applied.
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
711
|
+
if (applied.length > 0) {
|
|
712
|
+
rollbackName = applied[applied.length - 1];
|
|
713
|
+
// EF reverts by targeting the migration BEFORE the one being rolled back.
|
|
714
|
+
const target = applied.length > 1 ? applied[applied.length - 2] : Migrator.InitialDatabase;
|
|
715
|
+
await downMigrator.migrate(target);
|
|
825
716
|
} else {
|
|
826
|
-
|
|
827
|
-
rollbackName = path.basename(rollbackFile);
|
|
717
|
+
rollbackName = path.basename(mFiles[mFiles.length - 1]);
|
|
828
718
|
console.log(`⚠️ No applied-migration record found; falling back to latest file on disk: ${rollbackName}`);
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
const MigCtor = await __loadUserModule(rollbackFile);
|
|
832
|
-
const migInstance = new MigCtor(ContextCtor);
|
|
833
|
-
if(typeof migInstance.down === 'function'){
|
|
834
|
-
await migInstance.down(tableObj);
|
|
835
|
-
if (typeof migInstance.finalize === 'function') await migInstance.finalize();
|
|
836
|
-
await __removeMigrationApplied(contextInstance, rollbackName);
|
|
837
|
-
}else{
|
|
838
|
-
console.log(`Warning - Migration '${rollbackName}' has no down method; skipping.`);
|
|
719
|
+
await downMigrator.revertMigration(rollbackName);
|
|
839
720
|
}
|
|
840
721
|
|
|
841
722
|
// Update snapshot
|
|
@@ -967,8 +848,8 @@ program.hook('preAction', () => {
|
|
|
967
848
|
try {
|
|
968
849
|
const plan = await __resolveMigrationPlan(contextFileName);
|
|
969
850
|
contextInstance = await instantiateReadyContext(plan.ContextCtor);
|
|
970
|
-
const rows = await
|
|
971
|
-
const appliedMap = new Map(rows.map(r => [r.
|
|
851
|
+
const rows = await contextInstance.database.getAppliedMigrationRows();
|
|
852
|
+
const appliedMap = new Map(rows.map(r => [r.migrationId, r.appliedAt]));
|
|
972
853
|
const names = plan.mFiles.map(f => path.basename(f));
|
|
973
854
|
const pending = names.filter(n => !appliedMap.has(n));
|
|
974
855
|
const orphans = [...appliedMap.keys()].filter(n => !names.includes(n));
|
|
@@ -1008,8 +889,8 @@ program.hook('preAction', () => {
|
|
|
1008
889
|
const latest = plan.mFiles[plan.mFiles.length - 1];
|
|
1009
890
|
const name = path.basename(latest);
|
|
1010
891
|
contextInstance = await instantiateReadyContext(plan.ContextCtor);
|
|
1011
|
-
const rows = await
|
|
1012
|
-
const appliedNames = new Set(rows.map(r => r.
|
|
892
|
+
const rows = await contextInstance.database.getAppliedMigrationRows();
|
|
893
|
+
const appliedNames = new Set(rows.map(r => r.migrationId));
|
|
1013
894
|
if (appliedNames.has(name)) {
|
|
1014
895
|
if (!(cmdOpts && cmdOpts.force)) {
|
|
1015
896
|
console.error(`❌ Migration '${name}' has been applied to the database. Revert it first with 'masterrecord update-database-down ${plan.contextFileName}', or pass --force to revert and remove it.`);
|
|
@@ -1020,12 +901,18 @@ program.hook('preAction', () => {
|
|
|
1020
901
|
const migration = new Migration();
|
|
1021
902
|
const cleanEntities = migration.cleanEntities(contextInstance.__entities);
|
|
1022
903
|
const tableObj = migration.buildUpObject(plan.contextSnapshot.schema, cleanEntities);
|
|
1023
|
-
const
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
904
|
+
const removeMigrator = new Migrator({
|
|
905
|
+
context: contextInstance,
|
|
906
|
+
contextCtor: plan.ContextCtor,
|
|
907
|
+
snapshot: plan.contextSnapshot,
|
|
908
|
+
tableObj,
|
|
909
|
+
migrationsAssembly: new MigrationsAssembly({ files: plan.mFiles }),
|
|
910
|
+
historyRepository: contextInstance.database.historyRepository,
|
|
911
|
+
databaseCreator: contextInstance.database.databaseCreator,
|
|
912
|
+
loadMigration: __loadUserModule,
|
|
913
|
+
});
|
|
914
|
+
const mode = await removeMigrator.revertMigration(name);
|
|
1027
915
|
console.log(`↩ Reverted '${name}' (${mode})`);
|
|
1028
|
-
try { if (instance.context && instance.context !== contextInstance && typeof instance.context.close === 'function') await instance.context.close(); } catch (_) { /* best-effort */ }
|
|
1029
916
|
// Snapshot follows the applied state: previous applied migration becomes the latest.
|
|
1030
917
|
const remaining = plan.mFiles.filter(f => path.basename(f) !== name && appliedNames.has(path.basename(f)));
|
|
1031
918
|
migration.createSnapShot({
|
|
@@ -1050,60 +937,43 @@ program.hook('preAction', () => {
|
|
|
1050
937
|
program
|
|
1051
938
|
.command('script <contextFileName>')
|
|
1052
939
|
.option('-o, --output <file>', 'write the SQL to a file instead of stdout')
|
|
940
|
+
.option('--idempotent', 'guard each migration so the script can be run against any database (EF --idempotent)')
|
|
1053
941
|
.description('Generate the SQL for pending migrations without applying them (for DBA review)')
|
|
1054
942
|
.action(async function(contextFileName, cmdOpts){
|
|
1055
943
|
let contextInstance = null;
|
|
1056
944
|
try {
|
|
1057
945
|
const plan = await __resolveMigrationPlan(contextFileName);
|
|
1058
946
|
contextInstance = await instantiateReadyContext(plan.ContextCtor);
|
|
1059
|
-
const applied = await
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
const
|
|
1063
|
-
|
|
1064
|
-
|
|
947
|
+
const applied = await contextInstance.database.getAppliedMigrations();
|
|
948
|
+
|
|
949
|
+
// EF: `dotnet ef migrations script` is a shell over IMigrator.GenerateScript().
|
|
950
|
+
const scriptMigrator = new Migrator({
|
|
951
|
+
context: contextInstance,
|
|
952
|
+
contextCtor: plan.ContextCtor,
|
|
953
|
+
snapshot: plan.contextSnapshot,
|
|
954
|
+
migrationsAssembly: new MigrationsAssembly({ files: plan.mFiles }),
|
|
955
|
+
historyRepository: contextInstance.database.historyRepository,
|
|
956
|
+
databaseCreator: contextInstance.database.databaseCreator,
|
|
957
|
+
loadMigration: __loadUserModule,
|
|
958
|
+
});
|
|
959
|
+
|
|
960
|
+
const result = await scriptMigrator.generateScript(null, null, {
|
|
961
|
+
appliedMigrations: applied,
|
|
962
|
+
idempotent: !!(cmdOpts && cmdOpts.idempotent),
|
|
963
|
+
});
|
|
964
|
+
const pendingCount = result.migrationsToApply.length;
|
|
965
|
+
const out = [
|
|
1065
966
|
`-- masterrecord migration script for '${plan.contextFileName}'`,
|
|
1066
|
-
`-- generated ${new Date().toISOString()} — ${
|
|
967
|
+
`-- generated ${new Date().toISOString()} — ${pendingCount} pending migration(s). This script was NOT applied.`,
|
|
1067
968
|
`-- Introspection (table/column checks) ran against the live database; statements below are what update-database would execute.`,
|
|
1068
969
|
'',
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
return (p && p.length) ? `${s}; -- params: ${JSON.stringify(p)}` : `${s};`;
|
|
1073
|
-
};
|
|
1074
|
-
for (const mFile of pending) {
|
|
1075
|
-
const name = path.basename(mFile);
|
|
1076
|
-
const MigrationCtor = await __loadUserModule(mFile);
|
|
1077
|
-
const instance = new MigrationCtor(plan.ContextCtor);
|
|
1078
|
-
const mctx = instance.context || contextInstance;
|
|
1079
|
-
const captured = [];
|
|
1080
|
-
// Capture instead of execute: schema.js issues all DDL/DML through
|
|
1081
|
-
// context._execute; engine-level introspection (tableExists/getTableInfo)
|
|
1082
|
-
// is untouched so the plan reflects the real database state.
|
|
1083
|
-
const patch = (c) => {
|
|
1084
|
-
const orig = c._execute;
|
|
1085
|
-
c._execute = (q, p) => { captured.push(fmt(q, p)); return Promise.resolve({ changes: 0, rowCount: 0, affectedRows: 0 }); };
|
|
1086
|
-
return () => { c._execute = orig; };
|
|
1087
|
-
};
|
|
1088
|
-
const restores = [patch(mctx)];
|
|
1089
|
-
if (mctx !== contextInstance) restores.push(patch(contextInstance));
|
|
1090
|
-
try {
|
|
1091
|
-
await instance.up(tableObj);
|
|
1092
|
-
if (typeof instance.finalize === 'function') await instance.finalize();
|
|
1093
|
-
await __recordMigrationApplied(mctx, name); // captured, not executed
|
|
1094
|
-
} finally {
|
|
1095
|
-
for (const r of restores) r();
|
|
1096
|
-
}
|
|
1097
|
-
lines.push(`-- Migration: ${name}`);
|
|
1098
|
-
lines.push(...captured);
|
|
1099
|
-
lines.push('');
|
|
1100
|
-
try { if (mctx !== contextInstance && typeof mctx.close === 'function') await mctx.close(); } catch (_) { /* best-effort */ }
|
|
1101
|
-
}
|
|
1102
|
-
const out = lines.join('\n');
|
|
970
|
+
result.sql,
|
|
971
|
+
].join('\n');
|
|
972
|
+
|
|
1103
973
|
if (cmdOpts && cmdOpts.output) {
|
|
1104
974
|
const target = path.resolve(cmdOpts.output);
|
|
1105
975
|
fs.writeFileSync(target, out, 'utf8');
|
|
1106
|
-
console.log(`✓ SQL script for ${
|
|
976
|
+
console.log(`✓ SQL script for ${pendingCount} pending migration(s) written to ${target}`);
|
|
1107
977
|
} else {
|
|
1108
978
|
process.stdout.write(out + '\n');
|
|
1109
979
|
}
|
|
@@ -1462,47 +1332,40 @@ program.hook('preAction', () => {
|
|
|
1462
1332
|
// latest migration file and never consulted/wrote the tracking table,
|
|
1463
1333
|
// so earlier pending migrations were silently skipped and nothing was
|
|
1464
1334
|
// recorded ("schema changes silently stop applying").
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1335
|
+
// Same Migrator the single-context update-database uses, so this batch
|
|
1336
|
+
// command can never drift from it again.
|
|
1337
|
+
let currentName = null;
|
|
1338
|
+
const batchMigrator = new Migrator({
|
|
1339
|
+
context: contextInstance,
|
|
1340
|
+
contextCtor: ContextCtor,
|
|
1341
|
+
snapshot: entry.cs,
|
|
1342
|
+
tableObj,
|
|
1343
|
+
migrationsAssembly: new MigrationsAssembly({ files: mFiles }),
|
|
1344
|
+
historyRepository: contextInstance.database.historyRepository,
|
|
1345
|
+
databaseCreator: contextInstance.database.databaseCreator,
|
|
1346
|
+
loadMigration: __loadUserModule,
|
|
1347
|
+
logger: { migrationApplying: (id) => { currentName = id; } },
|
|
1348
|
+
});
|
|
1476
1349
|
|
|
1477
1350
|
let appliedCount = 0;
|
|
1478
1351
|
let ctxFailed = false;
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
const mc = inst && (inst.context || inst._context);
|
|
1490
|
-
if (mc && mc !== contextInstance && typeof mc.close === 'function') { await mc.close(); }
|
|
1491
|
-
} catch(_){ /* best-effort teardown */ }
|
|
1492
|
-
} catch (err) {
|
|
1493
|
-
console.error(`❌ ${entry.ctxName}: migration '${migrationName}' failed — ${err.message}`);
|
|
1494
|
-
console.error(` Earlier migrations (if any) were applied and recorded. Fix and re-run to resume.`);
|
|
1495
|
-
ctxFailed = true;
|
|
1496
|
-
anyFailed = true;
|
|
1497
|
-
break;
|
|
1498
|
-
}
|
|
1352
|
+
let recordedBefore = 0;
|
|
1353
|
+
try {
|
|
1354
|
+
recordedBefore = (await contextInstance.database.getAppliedMigrations()).length;
|
|
1355
|
+
const result = await batchMigrator.migrate();
|
|
1356
|
+
appliedCount = result.applied.length;
|
|
1357
|
+
} catch (err) {
|
|
1358
|
+
console.error(`❌ ${entry.ctxName}: migration '${currentName || "(unknown)"}' failed — ${err.message}`);
|
|
1359
|
+
console.error(` Earlier migrations (if any) were applied and recorded. Fix and re-run to resume.`);
|
|
1360
|
+
ctxFailed = true;
|
|
1361
|
+
anyFailed = true;
|
|
1499
1362
|
}
|
|
1500
1363
|
|
|
1501
1364
|
if (ctxFailed) {
|
|
1502
1365
|
summary.push({ ctxName: entry.ctxName, status: `FAILED (after ${appliedCount} applied)`, applied: appliedCount });
|
|
1503
1366
|
} else {
|
|
1504
1367
|
if (appliedCount === 0) {
|
|
1505
|
-
console.log(`✓ ${entry.ctxName}: up to date (${
|
|
1368
|
+
console.log(`✓ ${entry.ctxName}: up to date (${recordedBefore} on record)`);
|
|
1506
1369
|
} else {
|
|
1507
1370
|
console.log(`✓ ${entry.ctxName}: applied ${appliedCount} migration(s)`);
|
|
1508
1371
|
}
|
|
@@ -1622,6 +1485,125 @@ program.hook('preAction', () => {
|
|
|
1622
1485
|
});
|
|
1623
1486
|
|
|
1624
1487
|
|
|
1488
|
+
|
|
1489
|
+
// ============================================================================
|
|
1490
|
+
// EF Core database creation + history (see Migrations/RelationalDatabaseCreator.js,
|
|
1491
|
+
// Migrations/HistoryRepository.js, Migrations/DatabaseFacade.js)
|
|
1492
|
+
// ============================================================================
|
|
1493
|
+
|
|
1494
|
+
/**
|
|
1495
|
+
* Resolve a context CLASS by name: prefer the snapshot's recorded location (the
|
|
1496
|
+
* same resolution every other command uses), and fall back to searching for the
|
|
1497
|
+
* context file so `ensure-created` works on a project with no migrations yet.
|
|
1498
|
+
*/
|
|
1499
|
+
async function __resolveContextCtor(executedLocation, contextFileName){
|
|
1500
|
+
const snaps = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
|
|
1501
|
+
if (snaps && snaps[0]) {
|
|
1502
|
+
const file = path.resolve(executedLocation, snaps[0]);
|
|
1503
|
+
try {
|
|
1504
|
+
const snapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
1505
|
+
const contextAbs = path.resolve(path.dirname(file), snapshot.contextLocation || '');
|
|
1506
|
+
if (fs.existsSync(contextAbs)) return await __loadUserModule(contextAbs);
|
|
1507
|
+
} catch (_) { /* fall through to the file search */ }
|
|
1508
|
+
}
|
|
1509
|
+
const candidates = globSync(`**/${contextFileName}.js`, {
|
|
1510
|
+
cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true,
|
|
1511
|
+
ignore: ['**/node_modules/**', '**/*_migration.js'],
|
|
1512
|
+
});
|
|
1513
|
+
if (!candidates || !candidates.length) {
|
|
1514
|
+
throw new Error(`Cannot find a context named '${contextFileName}' in '${executedLocation}'. Expected ${contextFileName}.js (or a ${contextFileName}_contextSnapShot.json).`);
|
|
1515
|
+
}
|
|
1516
|
+
return await __loadUserModule(path.resolve(executedLocation, candidates[0]));
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
program
|
|
1520
|
+
.command('ensure-created <contextFileName>')
|
|
1521
|
+
.alias('ec')
|
|
1522
|
+
.description('Create the database and every table in the model when the database has no tables (EF: EnsureCreated). Does not use migrations and never alters an existing table.')
|
|
1523
|
+
.action(async function(contextFileName){
|
|
1524
|
+
const executedLocation = process.cwd();
|
|
1525
|
+
let ctx = null;
|
|
1526
|
+
try {
|
|
1527
|
+
const ContextCtor = await __resolveContextCtor(executedLocation, contextFileName.toLowerCase());
|
|
1528
|
+
ctx = await instantiateReadyContext(ContextCtor);
|
|
1529
|
+
const created = await ctx.database.ensureCreated();
|
|
1530
|
+
if (created) {
|
|
1531
|
+
console.log('✓ Database and schema created');
|
|
1532
|
+
} else if (await ctx.database.hasTables()) {
|
|
1533
|
+
console.log('✓ Database already has tables — nothing to do (EnsureCreated never alters an existing schema; use update-database for that)');
|
|
1534
|
+
} else {
|
|
1535
|
+
console.log('✓ Database already up to date');
|
|
1536
|
+
}
|
|
1537
|
+
await __cleanupAndExit(ctx, 0);
|
|
1538
|
+
} catch (e) {
|
|
1539
|
+
console.error('❌ ensure-created failed:', e.message);
|
|
1540
|
+
await __cleanupAndExit(ctx, 1);
|
|
1541
|
+
}
|
|
1542
|
+
});
|
|
1543
|
+
|
|
1544
|
+
program
|
|
1545
|
+
.command('ensure-deleted <contextFileName>')
|
|
1546
|
+
.alias('edel')
|
|
1547
|
+
.option('-f, --force', 'confirm that the database and ALL of its data may be destroyed')
|
|
1548
|
+
.description('Drop the database if it exists (EF: EnsureDeleted). Requires --force.')
|
|
1549
|
+
.action(async function(contextFileName, options){
|
|
1550
|
+
const executedLocation = process.cwd();
|
|
1551
|
+
let ctx = null;
|
|
1552
|
+
try {
|
|
1553
|
+
const ContextCtor = await __resolveContextCtor(executedLocation, contextFileName.toLowerCase());
|
|
1554
|
+
ctx = await instantiateReadyContext(ContextCtor);
|
|
1555
|
+
if (!options.force) {
|
|
1556
|
+
console.error('❌ ensure-deleted DROPS the database and every row in it. Re-run with --force if that is what you want.');
|
|
1557
|
+
await __cleanupAndExit(ctx, 1);
|
|
1558
|
+
return;
|
|
1559
|
+
}
|
|
1560
|
+
const deleted = await ctx.database.ensureDeleted();
|
|
1561
|
+
console.log(deleted ? '✓ Database deleted' : '✓ No database to delete');
|
|
1562
|
+
await __cleanupAndExit(ctx, 0);
|
|
1563
|
+
} catch (e) {
|
|
1564
|
+
console.error('❌ ensure-deleted failed:', e.message);
|
|
1565
|
+
await __cleanupAndExit(ctx, 1);
|
|
1566
|
+
}
|
|
1567
|
+
});
|
|
1568
|
+
|
|
1569
|
+
program
|
|
1570
|
+
.command('baseline <contextFileName> [migrationName]')
|
|
1571
|
+
.description('Record a migration as applied WITHOUT running it — brings a database that already has the schema under migration control (EF: insert the history row). Use --all for every migration on disk.')
|
|
1572
|
+
.option('-a, --all', 'baseline every migration file found, not just one')
|
|
1573
|
+
.action(async function(contextFileName, migrationName, options){
|
|
1574
|
+
const executedLocation = process.cwd();
|
|
1575
|
+
let ctx = null;
|
|
1576
|
+
try {
|
|
1577
|
+
if (!migrationName && !options.all) {
|
|
1578
|
+
console.error('❌ baseline needs a migration name, or --all.');
|
|
1579
|
+
process.exit(1);
|
|
1580
|
+
}
|
|
1581
|
+
const ContextCtor = await __resolveContextCtor(executedLocation, contextFileName.toLowerCase());
|
|
1582
|
+
ctx = await instantiateReadyContext(ContextCtor);
|
|
1583
|
+
|
|
1584
|
+
let ids;
|
|
1585
|
+
if (options.all) {
|
|
1586
|
+
ids = globSync('**/*_migration.js', { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, ignore: ['**/node_modules/**'] })
|
|
1587
|
+
.map(f => path.basename(f))
|
|
1588
|
+
.sort((a, b) => __getMigrationTimestamp(a) - __getMigrationTimestamp(b));
|
|
1589
|
+
if (!ids.length) { console.log('No migration files found.'); await __cleanupAndExit(ctx, 0); return; }
|
|
1590
|
+
} else {
|
|
1591
|
+
ids = [path.basename(migrationName)];
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
let recorded = 0;
|
|
1595
|
+
for (const id of ids) {
|
|
1596
|
+
if (await ctx.database.baseline(id)) { console.log(` ✓ baselined ${id}`); recorded++; }
|
|
1597
|
+
else { console.log(` · already applied ${id}`); }
|
|
1598
|
+
}
|
|
1599
|
+
console.log(`✓ Baseline complete — ${recorded} migration(s) recorded as applied, no SQL executed.`);
|
|
1600
|
+
await __cleanupAndExit(ctx, 0);
|
|
1601
|
+
} catch (e) {
|
|
1602
|
+
console.error('❌ baseline failed:', e.message);
|
|
1603
|
+
await __cleanupAndExit(ctx, 1);
|
|
1604
|
+
}
|
|
1605
|
+
});
|
|
1606
|
+
|
|
1625
1607
|
program.parse(process.argv);
|
|
1626
1608
|
|
|
1627
1609
|
// Handle manual '-V' alias
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Migration identifiers. Shared by MigrationsAssembly (which orders the files on
|
|
2
|
+
// disk) and HistoryRepository (which orders the rows in the history table) so the
|
|
3
|
+
// two can never disagree about what "the next migration" is.
|
|
4
|
+
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
/** EF's Migration.InitialDatabase sentinel — "revert everything". */
|
|
8
|
+
export const INITIAL_DATABASE = '0';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The timestamp prefix of `<timestamp>_<Name>_migration.js`. Ids without one sort
|
|
12
|
+
* last, then by name.
|
|
13
|
+
*/
|
|
14
|
+
export function timestampOf(id) {
|
|
15
|
+
const m = /^(\d+)_/.exec(path.basename(String(id)));
|
|
16
|
+
return m ? Number(m[1]) : Number.MAX_SAFE_INTEGER;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Order migration ids the way EF orders MigrationIds: chronologically.
|
|
21
|
+
*
|
|
22
|
+
* EF can compare its ids as strings because they are fixed-width
|
|
23
|
+
* (`20260101120000_Name`). masterrecord's are epoch milliseconds, which are only
|
|
24
|
+
* the same width by coincidence — `900_A` must still come before `1000_B`, and a
|
|
25
|
+
* plain string comparison puts them the wrong way round.
|
|
26
|
+
*/
|
|
27
|
+
export function compareMigrationIds(a, b) {
|
|
28
|
+
const ta = timestampOf(a);
|
|
29
|
+
const tb = timestampOf(b);
|
|
30
|
+
if (ta !== tb) return ta < tb ? -1 : 1;
|
|
31
|
+
return String(a).localeCompare(String(b));
|
|
32
|
+
}
|