// Changes indexes only. Run from rk-backend before deploying the stable mapping lookup. const { MongoClient, BSON } = require('mongodb'); const fs = require('node:fs/promises'); const path = require('node:path'); async function migrate() { const client = new MongoClient(process.env.MONGODB_ANLAGEN_URI || 'mongodb://localhost/rk2'); await client.connect(); try { const collection = client.db().collection('procon_zuordnungen'); const documents = await collection.find().toArray(); const indexes = await collection.indexes(); const identities = new Set(); for (const document of documents) { if (!Number.isSafeInteger(document.spsAntriebId)) throw new Error('SPS-Antrieb-ID fehlt; Migration abgebrochen.'); const identity = JSON.stringify([document.anlageId, document.verbindungId, document.spsAntriebId]); if (identities.has(identity)) throw new Error('Doppelte SPS-Antrieb-ID; Migration abgebrochen.'); identities.add(identity); } const backupDirectory = path.resolve(__dirname, '../backups/procon-mapping'); await fs.mkdir(backupDirectory, { recursive: true }); const backup = path.join(backupDirectory, `${Date.now()}.json`); await fs.writeFile(backup, BSON.EJSON.stringify({ documents, indexes }, { relaxed: false }), { flag: 'wx' }); await collection.createIndex({ anlageId: 1, verbindungId: 1, spsAntriebId: 1 }, { unique: true }); for (const index of indexes) { if (index.unique && JSON.stringify(index.key) === JSON.stringify({ anlageId: 1, verbindungId: 1, proConAggregateId: 1 })) { await collection.dropIndex(index.name); } } const after = await collection.find().toArray(); const serialize = rows => rows.map(row => BSON.EJSON.stringify(row, { relaxed: false })).sort(); if (JSON.stringify(serialize(after)) !== JSON.stringify(serialize(documents))) { throw new Error('Datenbestand hat sich parallel geaendert. Sicherung behalten und pruefen.'); } console.log(JSON.stringify({ documents: documents.length, unchanged: true, backup })); } finally { await client.close(); } } migrate().catch(error => { console.error(error.message); process.exitCode = 1; });