feat(db-migrate): add DROP_EXISTING_TABLES support
When DROP_EXISTING_TABLES=true, drop all existing tables before running migrations.
This commit is contained in:
parent
dade35b328
commit
81c00eca96
1 changed files with 32 additions and 0 deletions
|
|
@ -21,6 +21,14 @@ async fn main() -> Result<()> {
|
|||
.context("Failed to connect to database")?;
|
||||
tracing::info!("Connected to database");
|
||||
|
||||
let drop_existing = std::env::var("DROP_EXISTING_TABLES")
|
||||
.unwrap_or_default()
|
||||
.to_lowercase();
|
||||
|
||||
if drop_existing == "true" || drop_existing == "1" || drop_existing == "yes" {
|
||||
drop_all_tables(&pool).await?;
|
||||
}
|
||||
|
||||
let migrations_dir = std::env::var("MIGRATIONS_DIR")
|
||||
.unwrap_or_else(|_| "/migrations".to_string());
|
||||
|
||||
|
|
@ -30,6 +38,30 @@ async fn main() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
async fn drop_all_tables(pool: &sqlx::PgPool) -> Result<()> {
|
||||
tracing::warn!("DROP_EXISTING_TABLES is enabled - dropping all tables!");
|
||||
|
||||
let rows: Vec<(String,)> = sqlx::query_as("SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
if rows.is_empty() {
|
||||
tracing::info!("No tables to drop");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
tracing::info!("Found {} tables to drop", rows.len());
|
||||
|
||||
for (table_name,) in rows {
|
||||
let sql = format!("DROP TABLE IF EXISTS \"{}\" CASCADE", table_name);
|
||||
tracing::info!("Dropping table: {}", table_name);
|
||||
sqlx::raw_sql(&sql).execute(pool).await?;
|
||||
}
|
||||
|
||||
tracing::info!("All tables dropped successfully");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_migrations(pool: &sqlx::PgPool, migrations_dir: &str) -> Result<()> {
|
||||
let migrations_path = Path::new(migrations_dir);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue