ЛР 2 — БПИ2303 — Морару — на 5 (трек 2)
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
TypeScript/Node API на PostgreSQL с сессиями в Valkey (AOF), миграции, compose-стенд, restart hook, тесты уровня 4 и эксперимент трека 2 (планы запроса на 240k сообщений, стоимость записи, backup/restore).
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
// Apply versioned SQL migrations once each: node dist/migrate.js
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import pg from 'pg';
|
||||
|
||||
/** NAME_FILE (Docker secret path) wins over NAME; secret values are never logged. */
|
||||
export function setting(name: string, fallback?: string): string {
|
||||
const file = process.env[name + '_FILE'];
|
||||
if (file) return readFileSync(file, 'utf8').trim();
|
||||
const value = process.env[name] ?? fallback;
|
||||
if (value === undefined) throw new Error('missing setting ' + name);
|
||||
return value;
|
||||
}
|
||||
|
||||
const dir = process.env.MIGRATIONS_DIR ?? fileURLToPath(new URL('../migrations', import.meta.url));
|
||||
|
||||
async function migrate() {
|
||||
const client = new pg.Client({ connectionString: setting('DATABASE_URL'), connectionTimeoutMillis: 5000 });
|
||||
await client.connect();
|
||||
try {
|
||||
// one runner at a time; a concurrent runner waits and then skips what is applied
|
||||
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;
|
||||
}
|
||||
await client.query('BEGIN'); // DDL is transactional in PostgreSQL: all or nothing
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) await migrate();
|
||||
Reference in New Issue
Block a user