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
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use crate::{
    backend::SchemaBuilder, prepare::*, types::*, ForeignKeyAction, SchemaStatementBuilder,
    TableForeignKey,
};

/// Create a foreign key constraint for an existing table. Unsupported by Sqlite
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let foreign_key = ForeignKey::create()
///     .name("FK_character_font")
///     .from(Char::Table, Char::FontId)
///     .to(Font::Table, Font::Id)
///     .on_delete(ForeignKeyAction::Cascade)
///     .on_update(ForeignKeyAction::Cascade)
///     .to_owned();
///
/// assert_eq!(
///     foreign_key.to_string(MysqlQueryBuilder),
///     vec![
///         r#"ALTER TABLE `character`"#,
///         r#"ADD CONSTRAINT `FK_character_font`"#,
///         r#"FOREIGN KEY (`font_id`) REFERENCES `font` (`id`)"#,
///         r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
///     ]
///     .join(" ")
/// );
/// assert_eq!(
///     foreign_key.to_string(PostgresQueryBuilder),
///     vec![
///         r#"ALTER TABLE "character" ADD CONSTRAINT "FK_character_font""#,
///         r#"FOREIGN KEY ("font_id") REFERENCES "font" ("id")"#,
///         r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
///     ]
///     .join(" ")
/// );
/// ```
///
/// Composite key
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let foreign_key = ForeignKey::create()
///     .name("FK_character_glyph")
///     .from(Char::Table, (Char::FontId, Char::Id))
///     .to(Glyph::Table, (Char::FontId, Glyph::Id))
///     .on_delete(ForeignKeyAction::Cascade)
///     .on_update(ForeignKeyAction::Cascade)
///     .to_owned();
///
/// assert_eq!(
///     foreign_key.to_string(MysqlQueryBuilder),
///     vec![
///         r#"ALTER TABLE `character`"#,
///         r#"ADD CONSTRAINT `FK_character_glyph`"#,
///         r#"FOREIGN KEY (`font_id`, `id`) REFERENCES `glyph` (`font_id`, `id`)"#,
///         r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
///     ]
///     .join(" ")
/// );
/// assert_eq!(
///     foreign_key.to_string(PostgresQueryBuilder),
///     vec![
///         r#"ALTER TABLE "character" ADD CONSTRAINT "FK_character_glyph""#,
///         r#"FOREIGN KEY ("font_id", "id") REFERENCES "glyph" ("font_id", "id")"#,
///         r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
///     ]
///     .join(" ")
/// );
/// ```
#[derive(Debug, Clone)]
pub struct ForeignKeyCreateStatement {
    pub(crate) foreign_key: TableForeignKey,
}

impl Default for ForeignKeyCreateStatement {
    fn default() -> Self {
        Self::new()
    }
}

impl ForeignKeyCreateStatement {
    /// Construct a new [`ForeignKeyCreateStatement`]
    pub fn new() -> Self {
        Self {
            foreign_key: Default::default(),
        }
    }

    /// Set foreign key name
    pub fn name(&mut self, name: &str) -> &mut Self {
        self.foreign_key.name(name);
        self
    }

    /// Set key table and referencing table
    #[deprecated(
        since = "0.10.2",
        note = "Please use the [`ForeignKeyCreateStatement::from`] and [`ForeignKeyCreateStatement::to`]"
    )]
    pub fn table<T: 'static, R: 'static>(&mut self, table: T, ref_table: R) -> &mut Self
    where
        T: Iden,
        R: Iden,
    {
        self.foreign_key.from_tbl(table);
        self.foreign_key.to_tbl(ref_table);
        self
    }

    /// Set key column and referencing column
    #[deprecated(
        since = "0.10.2",
        note = "Please use the [`ForeignKeyCreateStatement::from`] and [`ForeignKeyCreateStatement::to`]"
    )]
    pub fn col<T: 'static, R: 'static>(&mut self, column: T, ref_column: R) -> &mut Self
    where
        T: Iden,
        R: Iden,
    {
        self.foreign_key.from_col(column);
        self.foreign_key.to_col(ref_column);
        self
    }

    /// Set key table and columns
    pub fn from<T, C>(&mut self, table: T, columns: C) -> &mut Self
    where
        T: IntoIden,
        C: IdenList,
    {
        self.foreign_key.from_tbl(table);
        for col in columns.into_iter() {
            self.foreign_key.from_col(col);
        }
        self
    }

    /// Set referencing table and columns
    pub fn to<T, C>(&mut self, table: T, columns: C) -> &mut Self
    where
        T: IntoIden,
        C: IdenList,
    {
        self.foreign_key.to_tbl(table);
        for col in columns.into_iter() {
            self.foreign_key.to_col(col);
        }
        self
    }

    /// Set key table
    pub fn from_tbl<T>(&mut self, table: T) -> &mut Self
    where
        T: IntoIden,
    {
        self.foreign_key.from_tbl(table);
        self
    }

    /// Set referencing table
    pub fn to_tbl<R>(&mut self, ref_table: R) -> &mut Self
    where
        R: IntoIden,
    {
        self.foreign_key.to_tbl(ref_table);
        self
    }

    /// Add key column
    pub fn from_col<T>(&mut self, column: T) -> &mut Self
    where
        T: IntoIden,
    {
        self.foreign_key.from_col(column);
        self
    }

    /// Add referencing column
    pub fn to_col<R>(&mut self, ref_column: R) -> &mut Self
    where
        R: IntoIden,
    {
        self.foreign_key.to_col(ref_column);
        self
    }

    /// Set on delete action
    pub fn on_delete(&mut self, action: ForeignKeyAction) -> &mut Self {
        self.foreign_key.on_delete(action);
        self
    }

    /// Set on update action
    pub fn on_update(&mut self, action: ForeignKeyAction) -> &mut Self {
        self.foreign_key.on_update(action);
        self
    }

    pub fn get_foreign_key(&self) -> &TableForeignKey {
        &self.foreign_key
    }

    pub fn take(&mut self) -> Self {
        Self {
            foreign_key: self.foreign_key.take(),
        }
    }
}

impl SchemaStatementBuilder for ForeignKeyCreateStatement {
    fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
        let mut sql = SqlWriter::new();
        schema_builder.prepare_foreign_key_create_statement(self, &mut sql);
        sql.result()
    }

    fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String {
        let mut sql = SqlWriter::new();
        schema_builder.prepare_foreign_key_create_statement(self, &mut sql);
        sql.result()
    }
}