use super::TableState;
use crate::detect::TableDef;
use crate::errors::{Result, WeldsError};
use crate::migrations::types::Type;
use crate::model_traits::TableIdent;
pub mod add_column;
pub mod change;
pub mod drop;
pub struct Table(Option<TableDef>);
pub fn change_table(table_state: &TableState, tablename: impl Into<String>) -> Result<Table> {
let tablename: String = tablename.into();
let syntax = table_state.0.first().map(|t| t.syntax());
let default_namespace = syntax
.and_then(TableIdent::default_namespace)
.map(|s| s.to_string());
let mut ident = TableIdent::parse(&tablename);
ident.schema = ident.schema.or(default_namespace);
let mut search: Vec<&TableDef> = table_state
.0
.iter()
.filter(|&t| t.ident().name() == ident.name())
.collect();
if ident.schema().is_some() {
search = search
.drain(..)
.filter(|&t| t.ident.schema() == ident.schema())
.collect()
}
if search.len() > 1 {
let err = format!(
"The table {} is ambiguous. This table was found under multiple schemanames. Please include the schema name when migrating.",
tablename
);
Err(WeldsError::MigrationError(err))?;
}
let mut search: Vec<TableDef> = search.iter().map(|&x| x.clone()).collect();
Ok(Table(search.pop()))
}
impl Table {
pub fn change(self, column_name: impl Into<String>) -> change::Change {
change::Change::new(self.0, column_name.into())
}
pub fn drop(self) -> drop::Drop {
drop::Drop::new(self.0)
}
pub fn add_column(self, column_name: impl Into<String>, ty: Type) -> add_column::AddColumn {
add_column::AddColumn::new(self.0, column_name.into(), ty)
}
}
#[cfg(feature = "mock")]
pub mod mock {
use super::*;
use crate::detect::table_def::mock::MockTableDef;
impl Table {
pub fn mock(t: MockTableDef) -> Table {
Table(Some(t.build()))
}
}
}
#[cfg(test)]
mod tests;