Skip to main content

sea_query/table/
drop.rs

1use crate::{SchemaStatementBuilder, backend::SchemaBuilder, types::*};
2
3/// Drop a table
4///
5/// # Examples
6///
7/// ```
8/// use sea_query::{tests_cfg::*, *};
9///
10/// let table = Table::drop()
11///     .table(Glyph::Table)
12///     .table(Char::Table)
13///     .to_owned();
14///
15/// assert_eq!(
16///     table.to_string(MysqlQueryBuilder),
17///     r#"DROP TABLE `glyph`, `character`"#
18/// );
19/// assert_eq!(
20///     table.to_string(PostgresQueryBuilder),
21///     r#"DROP TABLE "glyph", "character""#
22/// );
23/// assert_eq!(
24///     table.to_string(SqliteQueryBuilder),
25///     r#"DROP TABLE "glyph", "character""#
26/// );
27/// ```
28#[derive(Default, Debug, Clone)]
29pub struct TableDropStatement {
30    pub(crate) tables: Vec<TableRef>,
31    pub(crate) options: Vec<TableDropOpt>,
32    pub(crate) if_exists: bool,
33}
34
35/// All available table drop options
36#[derive(Debug, Clone)]
37#[non_exhaustive]
38pub enum TableDropOpt {
39    Restrict,
40    Cascade,
41}
42
43impl TableDropStatement {
44    /// Construct drop table statement
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Set table name
50    pub fn table<T>(&mut self, table: T) -> &mut Self
51    where
52        T: IntoTableRef,
53    {
54        self.tables.push(table.into_table_ref());
55        self
56    }
57
58    /// Drop table if exists
59    pub fn if_exists(&mut self) -> &mut Self {
60        self.if_exists = true;
61        self
62    }
63
64    /// Drop option restrict
65    pub fn restrict(&mut self) -> &mut Self {
66        self.options.push(TableDropOpt::Restrict);
67        self
68    }
69
70    /// Drop option cacade
71    pub fn cascade(&mut self) -> &mut Self {
72        self.options.push(TableDropOpt::Cascade);
73        self
74    }
75
76    pub fn take(&mut self) -> Self {
77        Self {
78            tables: std::mem::take(&mut self.tables),
79            options: std::mem::take(&mut self.options),
80            if_exists: self.if_exists,
81        }
82    }
83}
84
85impl SchemaStatementBuilder for TableDropStatement {
86    fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
87        let mut sql = String::with_capacity(256);
88        schema_builder.prepare_table_drop_statement(self, &mut sql);
89        sql
90    }
91}
92
93impl TableDropStatement {
94    pub fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
95        <Self as SchemaStatementBuilder>::build(self, schema_builder)
96    }
97
98    pub fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String {
99        <Self as SchemaStatementBuilder>::to_string(self, schema_builder)
100    }
101}