migrate.ts
TypeScript · 49 рядків
1// Створення бази й міграції migrations/*.sql по порядку; кожен файл — одна транзакція, версія — ім'я файлу.
2import { readdirSync, readFileSync } from 'node:fs';
3import { dirname, join } from 'node:path';
4import { fileURLToPath } from 'node:url';
5import pg from 'pg';
6
7const MIGRATIONS = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'migrations');
8
9/** Створити базу, якщо її немає (drop — перестворити), з розширенням pg_stat_statements. */
10export async function ensureDatabase(serverUrl: string, name: string, drop = false): Promise<void> {
11 const id = pg.Client.prototype.escapeIdentifier(name);
12 const admin = new pg.Client({ connectionString: `${serverUrl}/postgres` });
13 await admin.connect();
14 try {
15 if (drop) await admin.query(`DROP DATABASE IF EXISTS ${id} WITH (FORCE)`);
16 const exists = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [name]);
17 if (!exists.rowCount) await admin.query(`CREATE DATABASE ${id}`);
18 } finally {
19 await admin.end();
20 }
21 const c = new pg.Client({ connectionString: `${serverUrl}/${name}` });
22 await c.connect();
23 await c.query('CREATE EXTENSION IF NOT EXISTS pg_stat_statements').catch(() => {});
24 await c.end();
25}
26
27export async function migrate(pool: pg.Pool): Promise<string[]> {
28 const has = (await pool.query(`SELECT to_regclass('stock.schema_migrations') IS NOT NULL AS ok`)).rows[0].ok;
29 const done = new Set<string>(has ? (await pool.query('SELECT version FROM stock.schema_migrations')).rows.map((r) => r.version) : []);
30 const applied: string[] = [];
31 for (const f of readdirSync(MIGRATIONS).filter((x) => x.endsWith('.sql')).sort()) {
32 const version = f.replace(/\.sql$/, '');
33 if (done.has(version)) continue;
34 const c = await pool.connect();
35 try {
36 await c.query('BEGIN');
37 await c.query(readFileSync(join(MIGRATIONS, f), 'utf8'));
38 await c.query('COMMIT');
39 applied.push(version);
40 } catch (e) {
41 await c.query('ROLLBACK');
42 throw e;
43 } finally {
44 c.release();
45 }
46 }
47 return applied;
48}
49