use sea_query::{Alias, Query, Table};
use vespertide_core::{ColumnType, TableConstraint, TableDef};
use crate::sql::helpers::{
build_drop_enum_type_sql, build_sqlite_temp_table_create, recreate_indexes_after_rebuild,
};
use crate::sql::rename_table::build_rename_table;
use crate::sql::types::{BuiltQuery, DatabaseBackend};
pub(super) fn build_delete_column_sqlite_temp_table(
table: &str,
column: &str,
table_def: &TableDef,
column_type: Option<&ColumnType>,
pending_constraints: &[TableConstraint],
) -> Vec<BuiltQuery> {
let mut stmts = Vec::with_capacity(4 + table_def.constraints.len());
let temp_table = format!("{table}_temp");
let new_columns: Vec<_> = table_def
.columns
.iter()
.filter(|c| c.name != column)
.cloned()
.collect();
let new_constraints: Vec<_> = table_def
.constraints
.iter()
.filter(|c| {
if let TableConstraint::Check { expr, .. } = c {
return !expr.contains(&format!("\"{column}\"")) && !expr.contains(column);
}
!c.columns().iter().any(|col| col == column)
})
.cloned()
.collect();
let create_query = build_sqlite_temp_table_create(
DatabaseBackend::Sqlite,
&temp_table,
table,
&new_columns,
&new_constraints,
);
stmts.push(create_query);
let column_aliases: Vec<Alias> = new_columns.iter().map(|c| Alias::new(&c.name)).collect();
let mut select_query = Query::select();
for col_alias in &column_aliases {
select_query.column(col_alias.clone());
}
select_query.from(Alias::new(table));
let insert_stmt = Query::insert()
.into_table(Alias::new(&temp_table))
.columns(column_aliases.clone())
.select_from(select_query)
.unwrap()
.to_owned();
stmts.push(BuiltQuery::Insert(Box::new(insert_stmt)));
let drop_table = Table::drop().table(Alias::new(table)).to_owned();
stmts.push(BuiltQuery::DropTable(Box::new(drop_table)));
stmts.push(build_rename_table(&temp_table, table));
stmts.extend(recreate_indexes_after_rebuild(
table,
&new_constraints,
pending_constraints,
));
if let Some(col_type) = column_type
&& let Some(drop_type_sql) = build_drop_enum_type_sql(table, col_type)
{
stmts.push(BuiltQuery::Raw(drop_type_sql));
}
stmts
}