mic-bot/repo/setup_db.ts

87 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

2024-10-23 16:09:10 +00:00
import {
Kysely,
Migrator,
PostgresDialect,
FileMigrationProvider
2024-10-24 08:35:13 +00:00
} from 'npm:kysely'
2024-10-23 16:09:10 +00:00
/// <reference types="npm:@types/pg" />
2024-10-24 08:35:13 +00:00
import pg from "npm:pg";
2024-10-19 10:00:35 +00:00
import { Database } from "./scheme.ts"
import { CompiledConfig } from "../cfg/config.ts";
2024-10-25 18:10:48 +00:00
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++
}
}
2024-10-19 10:00:35 +00:00
export type SetupDbOutput = {
2024-10-24 08:35:13 +00:00
pool: pg.Pool,
2024-10-19 10:00:35 +00:00
db: Kysely<Database>,
}
export const setupDB = async (cfg: CompiledConfig): Promise<SetupDbOutput> => {
2024-10-25 18:10:48 +00:00
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
})
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
2024-10-19 10:00:35 +00:00
}
2024-10-25 18:10:48 +00:00
}
2024-10-24 08:35:13 +00:00
2024-10-25 18:10:48 +00:00
return { pool, db }
2024-10-24 14:39:42 +00:00
}