9781cd9ed2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
43 lines
1.8 KiB
TypeScript
43 lines
1.8 KiB
TypeScript
import { getDb } from "@/lib/db/mongo";
|
||
import { connectMongoose } from "@/lib/db/mongoose";
|
||
import { migration as m001 } from "./001-initial-indexes";
|
||
import { migration as m002 } from "./002-accounts-categories";
|
||
import { migration as m003 } from "./003-transactions";
|
||
import { migration as m004 } from "./004-attachments-reconciliation";
|
||
import { migration as m005 } from "./005-recurring";
|
||
import { migration as m006 } from "./006-card-statements";
|
||
import { migration as m007 } from "./007-contacts";
|
||
import { migration as m008 } from "./008-in-kind";
|
||
import type { Migration } from "./types";
|
||
|
||
/** Sıralı migration listesi. Yeni migration: dosyayı ekle ve buraya sırayla ekle. */
|
||
export const MIGRATIONS: Migration[] = [m001, m002, m003, m004, m005, m006, m007, m008];
|
||
|
||
const COLLECTION = "migrations";
|
||
|
||
/**
|
||
* Uygulanmamış migration'ları sırayla çalıştırır; her biri bir kez (`migrations` koleksiyonu).
|
||
* Aynı anda iki çalıştırma olursa benzersiz `name` index'i ikinci kaydı reddeder.
|
||
*/
|
||
export async function runMigrations(log: (line: string) => void = console.log): Promise<string[]> {
|
||
const db = getDb();
|
||
await connectMongoose();
|
||
const col = db.collection<{ name: string; appliedAt: Date; durationMs: number }>(COLLECTION);
|
||
await col.createIndex({ name: 1 }, { unique: true });
|
||
const applied = new Set(
|
||
(await col.find({}, { projection: { name: 1 } }).toArray()).map((d) => d.name),
|
||
);
|
||
|
||
const ran: string[] = [];
|
||
for (const m of MIGRATIONS) {
|
||
if (applied.has(m.name)) continue;
|
||
const started = Date.now();
|
||
await m.up(db);
|
||
await col.insertOne({ name: m.name, appliedAt: new Date(), durationMs: Date.now() - started });
|
||
ran.push(m.name);
|
||
log(`✓ Migration: ${m.name} — ${m.description}`);
|
||
}
|
||
if (!ran.length) log("• Bekleyen migration yok.");
|
||
return ran;
|
||
}
|