Repository navigation
Expand file tree
/
Copy pathrun_migration.js
More file actions
76 lines (63 loc) · 2.29 KB
/
Copy pathrun_migration.js
File metadata and controls
76 lines (63 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env node
/**
* Migration runner — called by Helm pre-upgrade hook or `oc exec`.
*
* 1. Seeds migrate-mongo's `changelog` from the legacy db-migrate `migrations`
* collection (idempotent — skips if changelog already has entries).
* 2. Runs all pending migrations via migrate-mongo's programmatic API.
*
* Note: migrate-mongo v14 is ESM-only. Its CJS shim is a broken Proxy, so we
* must use dynamic import() to load it correctly.
*/
'use strict';
const CHANGELOG_COLLECTION = 'changelog';
const { buildMongoUri } = require('./config/mongo_uri');
const migrateMongoConfig = {
mongodb: { url: buildMongoUri(), options: {} },
migrationsDir: 'migrations',
changelogCollectionName: CHANGELOG_COLLECTION,
migrationFileExtension: '.js',
useFileHash: false,
moduleSystem: 'commonjs'
};
async function seedChangelog(db) {
const changelogCol = db.collection(CHANGELOG_COLLECTION);
const migrationsCol = db.collection('migrations');
const changelogCount = await changelogCol.countDocuments();
if (changelogCount > 0) {
console.log(`changelog already has ${changelogCount} entries — skipping seed.`);
return;
}
const legacyDocs = await migrationsCol.find().toArray();
if (legacyDocs.length === 0) {
console.log('No legacy migrations collection — nothing to seed.');
return;
}
// db-migrate: { name: "/20190109233701-centroidCreation", run_on: ISODate }
// migrate-mongo: { fileName: "20190109233701-centroidCreation.js", appliedAt: ISODate }
const docs = legacyDocs.map(doc => ({
fileName: doc.name.replace(/^\//, '') + '.js',
appliedAt: doc.run_on
}));
await changelogCol.insertMany(docs);
console.log(`Seeded ${docs.length} entries into changelog from legacy migrations collection.`);
}
async function run() {
const { database, config, up } = await import('migrate-mongo');
config.set(migrateMongoConfig);
const { db, client } = await database.connect();
try {
await seedChangelog(db);
const migrated = await up(db, client);
migrated.forEach(name => console.log('MIGRATED UP:', name));
if (migrated.length === 0) {
console.log('All migrations already applied.');
}
} finally {
await client.close();
}
}
run().catch(err => {
console.error('Migration failed:', err.message);
process.exit(1);
});