Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
49
packages/khb_common/src/db/index.ts
Normal file
49
packages/khb_common/src/db/index.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import pg from "pg";
|
||||
|
||||
export type Pool = pg.Pool;
|
||||
export type Queryable = Pick<pg.Pool, "query">;
|
||||
|
||||
export function createPool(url: string, max = 5): Pool {
|
||||
return new pg.Pool({ connectionString: url, max });
|
||||
}
|
||||
|
||||
/** Выполняет fn в транзакции. */
|
||||
export async function withTx<T>(pool: Pool, fn: (c: pg.PoolClient) => Promise<T>): Promise<T> {
|
||||
const c = await pool.connect();
|
||||
try {
|
||||
await c.query("begin");
|
||||
const r = await fn(c);
|
||||
await c.query("commit");
|
||||
return r;
|
||||
} catch (e) {
|
||||
await c.query("rollback").catch(() => undefined);
|
||||
throw e;
|
||||
} finally {
|
||||
c.release();
|
||||
}
|
||||
}
|
||||
|
||||
/** Применяет *.sql из папки по порядку имён; журнал - таблица schema_migrations. Возвращает применённые. */
|
||||
export async function migrate(pool: Pool, dir: string = migrationsDir): Promise<string[]> {
|
||||
await pool.query(
|
||||
"create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())",
|
||||
);
|
||||
const applied = new Set((await pool.query("select name from schema_migrations")).rows.map((r) => r.name as string));
|
||||
const done: string[] = [];
|
||||
for (const file of readdirSync(dir).filter((f) => f.endsWith(".sql")).sort()) {
|
||||
if (applied.has(file)) continue;
|
||||
const sql = readFileSync(join(dir, file), "utf8");
|
||||
await withTx(pool, async (c) => {
|
||||
await c.query(sql);
|
||||
await c.query("insert into schema_migrations (name) values ($1)", [file]);
|
||||
});
|
||||
done.push(file);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
/** Папка migrations пакета khb_common (работает и из src, и из dist). */
|
||||
export const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "migrations");
|
||||
Reference in New Issue
Block a user