use crate::pool::{backend, pool, Backend};
use larust_core::AppError;
use sha2::{Digest, Sha256};
use std::path::Path;
pub async fn run(migrations_dir: &Path) -> Result<(), AppError> {
let pool = pool()?;
let create_table = match backend() {
Backend::Sqlite => {
"CREATE TABLE IF NOT EXISTS _migrations (\
name TEXT PRIMARY KEY, \
checksum TEXT, \
applied_at TEXT NOT NULL DEFAULT (datetime('now'))\
)"
}
Backend::MySql => {
"CREATE TABLE IF NOT EXISTS _migrations (\
name VARCHAR(255) PRIMARY KEY, \
checksum TEXT, \
applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\
)"
}
Backend::Postgres => {
"CREATE TABLE IF NOT EXISTS _migrations (\
name TEXT PRIMARY KEY, \
checksum TEXT, \
applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\
)"
}
};
sqlx::query(create_table)
.execute(pool)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
if backend() == Backend::Sqlite {
if let Err(error) = sqlx::query("ALTER TABLE _migrations ADD COLUMN checksum TEXT")
.execute(pool)
.await
{
let duplicate_column = matches!(&error, sqlx::Error::Database(database)
if database.message().contains("duplicate column name"));
if !duplicate_column {
return Err(AppError::Internal(Box::new(error)));
}
}
}
let mut files: Vec<_> = std::fs::read_dir(migrations_dir)
.map_err(|e| AppError::Internal(Box::new(e)))?
.filter_map(|entry| entry.ok())
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "sql"))
.collect();
files.sort();
for path in files {
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default()
.to_string();
let sql = std::fs::read_to_string(&path).map_err(|e| AppError::Internal(Box::new(e)))?;
let checksum = format!("{:x}", Sha256::digest(sql.as_bytes()));
let select_applied_sql = match backend() {
Backend::Sqlite | Backend::MySql => {
"SELECT name, checksum FROM _migrations WHERE name = ?"
}
Backend::Postgres => "SELECT name, checksum FROM _migrations WHERE name = $1",
};
let already_applied: Option<(String, Option<String>)> = sqlx::query_as(select_applied_sql)
.bind(&name)
.fetch_optional(pool)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
if let Some((_, stored_checksum)) = already_applied {
match stored_checksum {
Some(stored_checksum) if stored_checksum != checksum => {
return Err(AppError::Internal(Box::new(std::io::Error::other(format!(
"migration {name} was changed after it was applied; create a new migration instead"
)))));
}
Some(_) => {}
None => {
let update_checksum_sql = match backend() {
Backend::Sqlite | Backend::MySql => {
"UPDATE _migrations SET checksum = ? WHERE name = ?"
}
Backend::Postgres => "UPDATE _migrations SET checksum = $1 WHERE name = $2",
};
sqlx::query(update_checksum_sql)
.bind(&checksum)
.bind(&name)
.execute(pool)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
}
}
continue;
}
let mut tx = pool
.begin()
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
sqlx::raw_sql(&sql)
.execute(&mut *tx)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
let insert_migration_sql = match backend() {
Backend::Sqlite | Backend::MySql => {
"INSERT INTO _migrations (name, checksum) VALUES (?, ?)"
}
Backend::Postgres => "INSERT INTO _migrations (name, checksum) VALUES ($1, $2)",
};
sqlx::query(insert_migration_sql)
.bind(&name)
.bind(&checksum)
.execute(&mut *tx)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
tx.commit()
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
println!("Migrated: {name}");
}
Ok(())
}
pub async fn fresh(migrations_dir: &Path) -> Result<(), AppError> {
let pool = pool()?;
let tables: Vec<String> = crate::introspect::table_names()
.await?
.into_iter()
.filter(|table| table != "sessions")
.collect();
let mut conn = pool
.acquire()
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
if backend() == Backend::Sqlite {
sqlx::raw_sql("PRAGMA foreign_keys = OFF")
.execute(&mut *conn)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
} else if backend() == Backend::MySql {
sqlx::raw_sql("SET FOREIGN_KEY_CHECKS = 0")
.execute(&mut *conn)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
}
for table in &tables {
let sql = if backend() == Backend::Postgres {
format!("DROP TABLE \"{table}\" CASCADE")
} else {
format!("DROP TABLE \"{table}\"")
};
sqlx::raw_sql(&sql)
.execute(&mut *conn)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
}
if backend() == Backend::Sqlite {
sqlx::raw_sql("PRAGMA foreign_keys = ON")
.execute(&mut *conn)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
} else if backend() == Backend::MySql {
sqlx::raw_sql("SET FOREIGN_KEY_CHECKS = 1")
.execute(&mut *conn)
.await
.map_err(|e| AppError::Internal(Box::new(e)))?;
}
drop(conn);
run(migrations_dir).await
}