use crate::SqlUp;
#[derive(Clone, Debug, Default)]
pub struct ForeignKey {
pub columns: Vec<String>,
pub foreign_table: String,
pub foreign_columns: Vec<String>,
pub name: Option<String>,
}
impl ForeignKey {
pub fn new(foreign_table: &str) -> ForeignKey {
let mut column = foreign_table.to_string();
column.push_str("_id");
Self::for_column(foreign_table, "id", column.as_str())
}
pub fn with_name(foreign_table: &str, foreign_column: &str, name: &str) -> ForeignKey {
let mut column = foreign_table.to_string();
column.push('_');
column.push_str(foreign_column);
ForeignKey {
columns: vec![column.clone()],
foreign_table: foreign_table.to_string(),
foreign_columns: vec![foreign_column.to_string()],
name: Some(name.to_string()),
}
}
pub fn for_column(foreign_table: &str, foreign_column: &str, column: &str) -> ForeignKey {
ForeignKey {
columns: vec![column.to_string()],
foreign_table: foreign_table.to_string(),
foreign_columns: vec![foreign_column.to_string()],
name: None,
}
}
}
impl SqlUp for ForeignKey {
fn sqlite_up(&self) -> Option<String> {
let name = match self.name {
Some(ref name) => {
format!(" {} ", name)
}
None => "".into(),
};
let sql = format!(
"FOREIGN KEY {} ({}) REFERENCES {} ({})",
name,
self.columns.join(", "),
self.foreign_table,
self.foreign_columns.join(", ")
);
Some(sql)
}
}