Skeleton contracts / contracts (pull_request) Canceled after 0s
routes -> http/auth -> repositories -> infra; поведение не изменилось, smoke, persistence и тесты уровня 4 перепрогнаны.
39 lines
1.8 KiB
TypeScript
39 lines
1.8 KiB
TypeScript
// Применяет версионируемые SQL-миграции из migrations/ по одному разу: node dist/migrate.js
|
|
import { readdirSync, readFileSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import pg from 'pg';
|
|
import { setting } from './config.js';
|
|
|
|
const dir = process.env.MIGRATIONS_DIR ?? fileURLToPath(new URL('../migrations', import.meta.url));
|
|
|
|
const client = new pg.Client({ connectionString: setting('DATABASE_URL'), connectionTimeoutMillis: 5000 });
|
|
await client.connect();
|
|
try {
|
|
// advisory lock: два одновременных запуска не применят миграцию дважды — второй подождёт и пропустит её
|
|
await client.query('SELECT pg_advisory_lock(20262)');
|
|
await client.query('CREATE TABLE IF NOT EXISTS schema_migrations '
|
|
+ '(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())');
|
|
const done = new Set((await client.query('SELECT version FROM schema_migrations')).rows.map((r) => r.version));
|
|
for (const file of readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
|
|
const version = file.slice(0, -4);
|
|
if (done.has(version)) {
|
|
console.log('skip', version);
|
|
continue;
|
|
}
|
|
// DDL в PostgreSQL транзакционен: миграция и запись о ней применяются целиком или никак
|
|
await client.query('BEGIN');
|
|
try {
|
|
await client.query(readFileSync(join(dir, file), 'utf8'));
|
|
await client.query('INSERT INTO schema_migrations (version) VALUES ($1)', [version]);
|
|
await client.query('COMMIT');
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
}
|
|
console.log('applied', version);
|
|
}
|
|
} finally {
|
|
await client.end();
|
|
}
|