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";
|
|
|
|
|
|
|
|
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-24 08:35:13 +00:00
|
|
|
console.log("creating db instance")
|
|
|
|
const pool = new pg.Pool(cfg.pgPoolCfg)
|
2024-10-19 10:00:35 +00:00
|
|
|
const dialect = new PostgresDialect({ pool })
|
|
|
|
const db = new Kysely<Database>({ dialect })
|
|
|
|
|
2024-10-24 08:35:13 +00:00
|
|
|
if (cfg.migrationCfg?.applyMigrations) {
|
|
|
|
console.log("applying db migrations", cfg.migrationCfg.migrationsPath)
|
2024-10-19 10:00:35 +00:00
|
|
|
const migrator = new Migrator({
|
|
|
|
db,
|
|
|
|
provider: new FileMigrationProvider({
|
2024-10-24 08:35:13 +00:00
|
|
|
fs: {
|
|
|
|
readdir(path) {
|
|
|
|
return Promise.resolve(
|
|
|
|
[...Deno.readDirSync(path)].map((file) => file.name)
|
|
|
|
)
|
|
|
|
},
|
|
|
|
},
|
|
|
|
path: {
|
|
|
|
join(...path) {
|
|
|
|
return path.join('/')
|
|
|
|
},
|
|
|
|
},
|
2024-10-19 10:00:35 +00:00
|
|
|
migrationFolder: cfg.migrationCfg.migrationsPath,
|
|
|
|
}),
|
|
|
|
allowUnorderedMigrations: true
|
|
|
|
})
|
2024-10-24 08:35:13 +00:00
|
|
|
|
|
|
|
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-24 08:35:13 +00:00
|
|
|
|
2024-10-19 10:00:35 +00:00
|
|
|
return { pool, db }
|
|
|
|
}
|