import { Kysely, Migrator, PostgresDialect, FileMigrationProvider } from 'npm:kysely' /// import pg from "npm:pg"; import { Database } from "./scheme.ts" import { CompiledConfig } from "../cfg/config.ts"; export type SetupDbOutput = { pool: pg.Pool, db: Kysely, } export const setupDB = async (cfg: CompiledConfig): Promise => { console.log("creating db instance") const pool = new pg.Pool(cfg.pgPoolCfg) const dialect = new PostgresDialect({ pool }) const db = new Kysely({ dialect }) if (cfg.migrationCfg?.applyMigrations) { console.log("applying db migrations", cfg.migrationCfg.migrationsPath) const migrator = new Migrator({ db, provider: new FileMigrationProvider({ fs: { readdir(path) { return Promise.resolve( [...Deno.readDirSync(path)].map((file) => file.name) ) }, }, path: { join(...path) { return path.join('/') }, }, migrationFolder: cfg.migrationCfg.migrationsPath, }), allowUnorderedMigrations: true }) const { error, results } = await migrator.migrateToLatest() results?.forEach((it) => { if (it.status === 'Success') { console.log(`migration "${it.migrationName}" was executed successfully`) } else if (it.status === 'Error') { console.error(`failed to execute migration "${it.migrationName}"`) } }) if (error) { console.error('failed to migrate') console.error(error) throw error } } return { pool, db } }