kundencenter/apps/api/src/cli/migrate.ts

24 lines
1.3 KiB
TypeScript
Raw Normal View History

import { readdirSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import '../core/config.js';
import { pool } from '../core/db.js';
const dir = join(dirname(fileURLToPath(import.meta.url)), '../../../../migrations');
export async function migrate(): Promise<void> {
await pool.query('CREATE TABLE IF NOT EXISTS schema_migrations (name VARCHAR(200) PRIMARY KEY, applied_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3))');
const done = new Set((await pool.query('SELECT name FROM schema_migrations') as any)[0].map((r: { name: string }) => r.name));
for (const f of readdirSync(dir).filter((n) => n.endsWith('.sql')).sort()) {
if (done.has(f)) continue;
const c = await pool.getConnection();
try {
// DDL ist in MariaDB nicht transaktional; jede Migration einzeln, bei Fehler Abbruch.
const stmts = readFileSync(join(dir, f), 'utf8').replace(/^\s*--.*$/gm, '').split(/;\s*\n/).map((s) => s.trim()).filter(Boolean);
for (const st of stmts) await c.query(st);
await c.query('INSERT INTO schema_migrations (name) VALUES (?)', [f]);
console.log('migriert:', f);
} finally { c.release(); }
}
}
if (import.meta.url === `file://${process.argv[1]}`) { await migrate(); await pool.end(); }