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 const dropDb = async (migrator: Migrator, downLimit?: number) => {
console.log(`droping the DB`)
let downCounter: number = 0 // to prevent infinite loop
while (true) {
if (downLimit && downCounter === downLimit) return
const { results } = await migrator.migrateDown()
if (!results) continue
for (const { status, migrationName } of results) {
if (status === "Error" || status === "NotExecuted") {
return
}
console.log(`down migration "${migrationName}" was executed successfully`)
}
downCounter++
}
}
export type SetupDbOutput = {
pool: pg.Pool,
db: Kysely,
}
export const setupDB = async (cfg: CompiledConfig): Promise => {
console.log("creating db instance: ", cfg.pgPoolCfg)
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
})
if (cfg.migrationCfg.dropDb) {
await dropDb(migrator, 100)
}
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 }
}