forked from mtusi2026/mtusi2026lab7
80 lines
2.3 KiB
TypeScript
80 lines
2.3 KiB
TypeScript
import { readdir, readFile } from 'node:fs/promises';
|
|
import { dirname, join } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { parseDatabaseConfig } from '../config/app-config.schema.js';
|
|
import { MetricsService } from '../metrics/metrics.service.js';
|
|
import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js';
|
|
import { TlsMaterialManager } from '../security/tls-material.js';
|
|
import { DatabaseClient } from './database.client.js';
|
|
|
|
const migrationsDirectory = join(
|
|
dirname(fileURLToPath(import.meta.url)),
|
|
'migrations',
|
|
);
|
|
|
|
async function migrationFiles(): Promise<string[]> {
|
|
const files = await readdir(migrationsDirectory);
|
|
return files.filter((file) => /^\d+_.+\.sql$/u.test(file)).sort();
|
|
}
|
|
|
|
export async function runMigrations(database: DatabaseClient): Promise<void> {
|
|
await database.query(
|
|
'migrations.ensure_table',
|
|
`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version text PRIMARY KEY,
|
|
applied_at timestamptz NOT NULL DEFAULT now()
|
|
)`,
|
|
);
|
|
|
|
for (const version of await migrationFiles()) {
|
|
await database.withTransaction(async (client) => {
|
|
const applied = await client.query({
|
|
text: 'SELECT version FROM schema_migrations WHERE version = $1',
|
|
values: [version],
|
|
});
|
|
if (applied.rowCount) return;
|
|
|
|
const sql = await readFile(
|
|
join(migrationsDirectory, version),
|
|
'utf8',
|
|
);
|
|
await client.query(sql);
|
|
await client.query({
|
|
text: 'INSERT INTO schema_migrations (version) VALUES ($1)',
|
|
values: [version],
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const rawEnv = process.env as Record<string, unknown>;
|
|
const config = parseDatabaseConfig(rawEnv);
|
|
const tlsMaterial = TlsMaterialManager.initFromEnv('migrator', rawEnv);
|
|
const secretsStore = await RuntimeSecretsStore.bootstrap(
|
|
'migrator',
|
|
tlsMaterial,
|
|
rawEnv,
|
|
undefined,
|
|
{ background: false },
|
|
);
|
|
const database = new DatabaseClient(
|
|
{
|
|
get: (key: keyof typeof config) => config[key],
|
|
getOrThrow: (key: keyof typeof config) => config[key],
|
|
} as never,
|
|
new MetricsService(),
|
|
tlsMaterial,
|
|
secretsStore,
|
|
);
|
|
try {
|
|
await runMigrations(database);
|
|
} finally {
|
|
await database.onModuleDestroy();
|
|
secretsStore.close();
|
|
tlsMaterial.onModuleDestroy();
|
|
}
|
|
}
|
|
|
|
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
|