1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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)
    }
}