SPB Git

Repository Public

db.ts 1.3 KB 32 lines typescript

1import postgres from "postgres"2import fs from "node:fs"3import path from "node:path"4import { fileURLToPath } from "node:url"5import { config } from "./config.js"67export const sql = postgres(config.databaseUrl, { max: 12, onnotice: () => {}, types: { bigint: { to: 20, from: [20], serialize: (x: number) => String(x), parse: (x: string) => Number(x) } } })8export type Sql = typeof sql910function migrationsDir(): string {11  const here = path.dirname(fileURLToPath(import.meta.url))12  for (const c of [path.join(here, "../db/migrations"), path.join(here, "../../db/migrations"), path.resolve("db/migrations")])13    if (fs.existsSync(c)) return c14  throw new Error("db/migrations not found")15}1617export async function migrate(log: (m: string) => void = () => {}) {18  await sql`create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())`19  const dir = migrationsDir()20  const files = fs.readdirSync(dir).filter((f) => /^\d+_.*\.sql$/.test(f)).sort()21  for (const f of files) {22    const done = await sql`select 1 from schema_migrations where name = ${f}`23    if (done.length) continue24    const text = fs.readFileSync(path.join(dir, f), "utf8")25    await sql.begin(async (tx) => {26      await tx.unsafe(text)27      await tx`insert into schema_migrations (name) values (${f})`28    })29    log(`migration applied: ${f}`)30  }31}32
Files main
Menu

Theme