Skip to main content

sea_query/foreign_key/
drop.rs

1use crate::{SchemaStatementBuilder, TableForeignKey, backend::SchemaBuilder, types::*};
2
3/// Drop a foreign key constraint for an existing table
4///
5/// # Examples
6///
7/// ```
8/// use sea_query::{tests_cfg::*, *};
9///
10/// let foreign_key = ForeignKey::drop()
11///     .name("FK_character_font")
12///     .table(Char::Table)
13///     .to_owned();
14///
15/// assert_eq!(
16///     foreign_key.to_string(MysqlQueryBuilder),
17///     r#"ALTER TABLE `character` DROP FOREIGN KEY `FK_character_font`"#
18/// );
19/// assert_eq!(
20///     foreign_key.to_string(PostgresQueryBuilder),
21///     r#"ALTER TABLE "character" DROP CONSTRAINT "FK_character_font""#
22/// );
23/// // Sqlite does not support modification of foreign key constraints to existing tables
24/// ```
25#[derive(Default, Debug, Clone)]
26pub struct ForeignKeyDropStatement {
27    pub(crate) foreign_key: TableForeignKey,
28    pub(crate) table: Option<TableRef>,
29}
30
31impl ForeignKeyDropStatement {
32    /// Construct a new [`ForeignKeyDropStatement`]
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    /// Set foreign key name
38    pub fn name<T>(&mut self, name: T) -> &mut Self
39    where
40        T: Into<String>,
41    {
42        self.foreign_key.name(name);
43        self
44    }
45
46    /// Set key table and referencing table
47    pub fn table<T>(&mut self, table: T) -> &mut Self
48    where
49        T: IntoTableRef,
50    {
51        self.table = Some(table.into_table_ref());
52        self
53    }
54}
55
56impl SchemaStatementBuilder for ForeignKeyDropStatement {
57    fn build<T>(&self, schema_builder: T) -> String
58    where
59        T: SchemaBuilder,
60    {
61        let mut sql = String::with_capacity(256);
62        schema_builder.prepare_foreign_key_drop_statement(self, &mut sql);
63        sql
64    }
65}
66
67impl ForeignKeyDropStatement {
68    pub fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
69        <Self as SchemaStatementBuilder>::build(self, schema_builder)
70    }
71
72    pub fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String {
73        <Self as SchemaStatementBuilder>::to_string(self, schema_builder)
74    }
75}