import type { mongo } from 'mongoose'; import { AUCTION_CANCELLATION_CLEANUP_INDEX } from '../auction-cancellation-index'; /** Creates only this additive index; never drops or rebuilds other indexes. */ export async function migrateAuctionCancellationIndex( db: mongo.Db, { dryRun = true }: { dryRun?: boolean } = {}, ) { const { key, options } = AUCTION_CANCELLATION_CLEANUP_INDEX; const collection = db.collection('match'); const indexes = await collection .listIndexes() .toArray() .catch((error: unknown) => { if (error instanceof Error && 'code' in error && error.code === 26) return []; throw error; }); const existing = indexes.find((index) => index.name === options.name); if ( existing && (JSON.stringify(existing.key) !== JSON.stringify(key) || JSON.stringify(existing.partialFilterExpression) !== JSON.stringify(options.partialFilterExpression) || existing.unique === true || existing.sparse === true || existing.hidden === true) ) { throw new Error( `Index ${options.name} already exists with a different definition.`, ); } if (!dryRun) await collection.createIndex(key, options); return { dryRun, alreadyPresent: Boolean(existing), index: { key, ...options }, }; }