Files
butcem/scripts/migrations/index.ts
T

60 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { migration as m009 } from "./009-assets";
import { migration as m010 } from "./010-budgets";
import { migration as m011 } from "./011-stock";
import { migration as m012 } from "./012-stock-counts";
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,
m009,
m010,
m011,
m012,
];
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;
}