import { readdir, readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
export async function migrate(database, migrationsDir = resolve('database/migrations')) {
    await database.query(`CREATE TABLE IF NOT EXISTS schema_migrations (
    version text PRIMARY KEY,
    applied_at timestamptz NOT NULL DEFAULT now()
  )`);
    const files = (await readdir(migrationsDir)).filter((name) => name.endsWith('.sql')).sort();
    const applied = [];
    for (const file of files) {
        const found = await database.query('SELECT version FROM schema_migrations WHERE version = $1', [file]);
        if (found.rowCount)
            continue;
        const sql = await readFile(resolve(migrationsDir, file), 'utf8');
        await database.transaction(async (tx) => {
            await tx.query(sql);
            await tx.query('INSERT INTO schema_migrations(version) VALUES ($1)', [file]);
        });
        applied.push(file);
    }
    return applied;
}
//# sourceMappingURL=migrations.js.map