drop DB functionality added

This commit is contained in:
Dmitry Anderson 2024-10-25 20:10:48 +02:00
parent ce6802faff
commit a1e6284a16
2 changed files with 89 additions and 66 deletions

View File

@ -13,30 +13,30 @@ export const DEFAULT_DB_PORT = 5432
export const DEFAULT_DB_TLS = false export const DEFAULT_DB_TLS = false
export const loadConfig = (): CompiledConfig => { export const loadConfig = (): CompiledConfig => {
const cfg = getConfig() const cfg = getConfig()
const pgPoolCfg: PoolConfig = { const pgPoolCfg: PoolConfig = {
host: cfg.db_host || DEFAULT_DB_HOST, host: cfg.db_host || DEFAULT_DB_HOST,
user: cfg.db_user || DEFAULT_DB_USER, user: cfg.db_user || DEFAULT_DB_USER,
database: cfg.db_name || DEFAULT_DB_NAME, database: cfg.db_name || DEFAULT_DB_NAME,
port: cfg.db_port || DEFAULT_DB_PORT, port: cfg.db_port || DEFAULT_DB_PORT,
ssl: cfg.db_tls || DEFAULT_DB_TLS, ssl: cfg.db_tls || DEFAULT_DB_TLS,
password: cfg.db_password, password: cfg.db_password,
} }
const botCfg: BotConfig = { const botCfg: BotConfig = {
mode: BotMode.normal, mode: BotMode.normal,
bot_token: cfg.bot_token, bot_token: cfg.bot_token,
chat_id: MIC_CHAT_ID, chat_id: MIC_CHAT_ID,
admin_ids: [ admin_ids: [
MR_ANDERSON_ID, MR_ANDERSON_ID,
] ]
} }
return { return {
pgPoolCfg, botCfg, pgPoolCfg, botCfg,
migrationCfg: { migrationCfg: {
dropDb: cfg.drop_db, dropDb: cfg.drop_db,
applyMigrations: cfg.apply_migrations, applyMigrations: cfg.apply_migrations,
migrationsPath: import.meta.dirname ? migrationsPath: import.meta.dirname ?
path.join(import.meta.dirname, 'migrations') : '/app/migrations', path.join(import.meta.dirname, 'migrations') : '/app/migrations',
}
} }
}
} }

View File

@ -10,54 +10,77 @@ import pg from "npm:pg";
import { Database } from "./scheme.ts" import { Database } from "./scheme.ts"
import { CompiledConfig } from "../cfg/config.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 = { export type SetupDbOutput = {
pool: pg.Pool, pool: pg.Pool,
db: Kysely<Database>, db: Kysely<Database>,
} }
export const setupDB = async (cfg: CompiledConfig): Promise<SetupDbOutput> => { export const setupDB = async (cfg: CompiledConfig): Promise<SetupDbOutput> => {
console.log("creating db instance: ", cfg.pgPoolCfg) console.log("creating db instance: ", cfg.pgPoolCfg)
const pool = new pg.Pool(cfg.pgPoolCfg) const pool = new pg.Pool(cfg.pgPoolCfg)
const dialect = new PostgresDialect({ pool }) const dialect = new PostgresDialect({ pool })
const db = new Kysely<Database>({ dialect }) const db = new Kysely<Database>({ dialect })
if (cfg.migrationCfg?.applyMigrations) { if (cfg.migrationCfg?.applyMigrations) {
console.log("applying db migrations", cfg.migrationCfg.migrationsPath) console.log("applying db migrations", cfg.migrationCfg.migrationsPath)
const migrator = new Migrator({ const migrator = new Migrator({
db, db,
provider: new FileMigrationProvider({ provider: new FileMigrationProvider({
fs: { fs: {
readdir(path) { readdir(path) {
return Promise.resolve( return Promise.resolve(
[...Deno.readDirSync(path)].map((file) => file.name) [...Deno.readDirSync(path)].map((file) => file.name)
) )
}, },
}, },
path: { path: {
join(...path) { join(...path) {
return path.join('/') return path.join('/')
}, },
}, },
migrationFolder: cfg.migrationCfg.migrationsPath, migrationFolder: cfg.migrationCfg.migrationsPath,
}), }),
allowUnorderedMigrations: true allowUnorderedMigrations: true
}) })
const { error, results } = await migrator.migrateToLatest() if (cfg.migrationCfg.dropDb) {
await dropDb(migrator, 100)
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
}
} }
const { error, results } = await migrator.migrateToLatest()
return { pool, db } 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 }
} }