|
| 1 | +/** |
| 2 | + * @file Add index on `payload.release` for all per-project events collections |
| 3 | + * Collections pattern: `events:{projectId}` in the events database |
| 4 | + */ |
| 5 | +module.exports = { |
| 6 | + async up(db) { |
| 7 | + const indexSpec = { 'payload.release': 1 }; |
| 8 | + const indexOptions = { |
| 9 | + name: 'payloadRelease', |
| 10 | + background: true, |
| 11 | + sparse: true, |
| 12 | + }; |
| 13 | + |
| 14 | + const collections = await db.listCollections().toArray(); |
| 15 | + const targetCollections = collections |
| 16 | + .map(c => c.name) |
| 17 | + .filter(name => name && name.startsWith('events:')); |
| 18 | + |
| 19 | + console.log(`Found ${targetCollections.length} events collections`); |
| 20 | + |
| 21 | + for (const name of targetCollections) { |
| 22 | + const coll = db.collection(name); |
| 23 | + const existing = await coll.indexes(); |
| 24 | + |
| 25 | + const alreadyExists = existing.some(idx => idx.name === indexOptions.name) || |
| 26 | + existing.some(idx => idx.key && idx.key['payload.release'] === 1); |
| 27 | + |
| 28 | + if (alreadyExists) { |
| 29 | + console.log(`Index already exists on ${name}. Skipped.`); |
| 30 | + continue; |
| 31 | + } |
| 32 | + |
| 33 | + console.log(`Creating index ${indexOptions.name} on ${name}...`); |
| 34 | + await coll.createIndex(indexSpec, indexOptions); |
| 35 | + } |
| 36 | + }, |
| 37 | + |
| 38 | + async down(db) { |
| 39 | + const indexName = 'idx_payload_release'; |
| 40 | + |
| 41 | + const collections = await db.listCollections().toArray(); |
| 42 | + const targetCollections = collections |
| 43 | + .map(c => c.name) |
| 44 | + .filter(name => name && name.startsWith('events:')); |
| 45 | + |
| 46 | + console.log(`Found ${targetCollections.length} events collections`); |
| 47 | + |
| 48 | + for (const name of targetCollections) { |
| 49 | + const coll = db.collection(name); |
| 50 | + |
| 51 | + try { |
| 52 | + console.log(`Dropping index ${indexName} on ${name}...`); |
| 53 | + await coll.dropIndex(indexName); |
| 54 | + } catch (e) { |
| 55 | + // If index does not exist, ignore |
| 56 | + if (e && e.codeName !== 'IndexNotFound') { |
| 57 | + throw e; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + }, |
| 62 | +}; |
0 commit comments