mic-bot/repo/setup_db.ts
2024-10-24 16:39:42 +02:00

64 lines
1.9 KiB
TypeScript

import {
Kysely,
Migrator,
PostgresDialect,
FileMigrationProvider
} from 'npm:kysely'
/// <reference types="npm:@types/pg" />
import pg from "npm:pg";
import { Database } from "./scheme.ts"
import { CompiledConfig } from "../cfg/config.ts";
export type SetupDbOutput = {
pool: pg.Pool,
db: Kysely<Database>,
}
export const setupDB = async (cfg: CompiledConfig): Promise<SetupDbOutput> => {
console.log("creating db instance: ", cfg.pgPoolCfg)
const pool = new pg.Pool(cfg.pgPoolCfg)
const dialect = new PostgresDialect({ pool })
const db = new Kysely<Database>({ 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 }
}