50 lines
1.7 KiB
JavaScript
50 lines
1.7 KiB
JavaScript
import { readdirSync, readFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import pg from "pg";
|
|
export function createPgDb(connectionString) {
|
|
const pool = new pg.Pool({ connectionString });
|
|
return {
|
|
async query(sql, params) {
|
|
return (await pool.query(sql, params)).rows;
|
|
},
|
|
async tx(fn) {
|
|
const client = await pool.connect();
|
|
const q = {
|
|
async query(sql, params) {
|
|
return (await client.query(sql, params)).rows;
|
|
},
|
|
};
|
|
try {
|
|
await client.query("begin");
|
|
const result = await fn(q);
|
|
await client.query("commit");
|
|
return result;
|
|
}
|
|
catch (e) {
|
|
await client.query("rollback");
|
|
throw e;
|
|
}
|
|
finally {
|
|
client.release();
|
|
}
|
|
},
|
|
close: () => pool.end(),
|
|
};
|
|
}
|
|
export async function migrate(db, dir = join(process.cwd(), "migrations")) {
|
|
await db.query("create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())");
|
|
const done = new Set((await db.query("select name from schema_migrations")).map((r) => r.name));
|
|
const applied = [];
|
|
for (const file of readdirSync(dir).filter((f) => f.endsWith(".sql")).sort()) {
|
|
if (done.has(file))
|
|
continue;
|
|
const sql = readFileSync(join(dir, file), "utf8");
|
|
await db.tx(async (q) => {
|
|
await q.query(sql);
|
|
await q.query("insert into schema_migrations (name) values ($1)", [file]);
|
|
});
|
|
applied.push(file);
|
|
}
|
|
return applied;
|
|
}
|