2024-10-23 16:09:10 +00:00
|
|
|
import {
|
|
|
|
Kysely,
|
|
|
|
Migrator,
|
|
|
|
PostgresDialect,
|
|
|
|
FileMigrationProvider
|
|
|
|
} from 'https://cdn.jsdelivr.net/npm/kysely/dist/esm/index.js'
|
|
|
|
|
|
|
|
/// <reference types="npm:@types/pg" />
|
|
|
|
// @deno-types="npm:@types/pg"
|
2024-10-19 10:00:35 +00:00
|
|
|
import { Pool } from "npm:pg";
|
|
|
|
import { Database } from "./scheme.ts"
|
|
|
|
import { CompiledConfig } from "../cfg/config.ts";
|
|
|
|
import { promises as fs } from 'node:fs'
|
|
|
|
import * as path from 'node:path'
|
|
|
|
|
|
|
|
|
|
|
|
export type SetupDbOutput = {
|
|
|
|
pool: Pool,
|
|
|
|
db: Kysely<Database>,
|
|
|
|
}
|
|
|
|
export const setupDB = async (cfg: CompiledConfig): Promise<SetupDbOutput> => {
|
|
|
|
const pool = new Pool(cfg.pgPoolCfg)
|
|
|
|
const dialect = new PostgresDialect({ pool })
|
|
|
|
const db = new Kysely<Database>({ dialect })
|
|
|
|
|
|
|
|
if (cfg.migrationCfg && cfg.migrationCfg.applyMigrations) {
|
|
|
|
const migrator = new Migrator({
|
|
|
|
db,
|
|
|
|
provider: new FileMigrationProvider({
|
|
|
|
fs,
|
|
|
|
path,
|
|
|
|
migrationFolder: cfg.migrationCfg.migrationsPath,
|
|
|
|
}),
|
|
|
|
allowUnorderedMigrations: true
|
|
|
|
})
|
|
|
|
await migrator.migrateToLatest()
|
|
|
|
}
|
|
|
|
return { pool, db }
|
|
|
|
}
|