use crate::util::{ok, step, CliResult};
use chyabrung_db::{Db, Migrator};
use std::path::Path;
pub(crate) fn database_url() -> CliResult<String> {
chyabrung_core::config::database_url()
}
pub(crate) fn runtime() -> CliResult<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())
}
pub(crate) async fn connect() -> CliResult<Db> {
let url = database_url()?;
Db::connect(&url).await.map_err(|e| e.message().to_string())
}
pub(crate) fn migrator() -> CliResult<Migrator> {
Migrator::new().dir("migrations").map_err(|e| e.message().to_string())
}
pub fn migrate() -> CliResult {
runtime()?.block_on(async {
let db = connect().await?;
let done = migrator()?.run(&db).await.map_err(|e| e.message().to_string())?;
if done.is_empty() {
ok("nothing to migrate");
}
for m in done {
ok(&format!("migrated {m}"));
}
Ok(())
})
}
pub fn rollback(steps: u32) -> CliResult {
runtime()?.block_on(async {
let db = connect().await?;
let done = migrator()?.rollback_steps(&db, steps).await.map_err(|e| e.message().to_string())?;
if done.is_empty() {
ok("nothing to roll back");
}
for m in done {
ok(&format!("rolled back {m}"));
}
Ok(())
})
}
pub fn status() -> CliResult {
runtime()?.block_on(async {
let db = connect().await?;
let st = migrator()?.status(&db).await.map_err(|e| e.message().to_string())?;
println!("{:<8} migration", "batch");
for s in st {
let b = s.batch.map(|b| b.to_string()).unwrap_or_else(|| "pending".into());
println!("{b:<8} {}", s.name);
}
Ok(())
})
}
pub fn fresh() -> CliResult {
runtime()?.block_on(async {
let db = connect().await?;
let m = migrator()?;
m.reset(&db).await.map_err(|e| e.message().to_string())?;
let done = m.run(&db).await.map_err(|e| e.message().to_string())?;
ok(&format!("fresh database, {} migrations applied", done.len()));
Ok(())
})
}
pub fn seed() -> CliResult {
runtime()?.block_on(async {
let db = connect().await?;
let dir = Path::new("database/seeds");
if dir.is_dir() {
let mut files: Vec<_> = std::fs::read_dir(dir)
.map_err(|e| e.to_string())?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|e| e == "sql").unwrap_or(false))
.collect();
files.sort();
for f in files {
let sql = std::fs::read_to_string(&f).map_err(|e| e.to_string())?;
if sql.lines().all(|l| l.trim().is_empty() || l.trim_start().starts_with("--")) {
continue;
}
db.execute_script(&sql).await.map_err(|e| format!("{}: {}", f.display(), e.message()))?;
ok(&format!("seeded {}", f.display()));
}
}
Ok::<_, String>(())
})?;
if Path::new("src/bin/seed.rs").is_file() {
step("running src/bin/seed.rs");
crate::util::run(std::process::Command::new("cargo").args(["run", "--quiet", "--bin", "seed"]))?;
}
Ok(())
}