sea_query/table/
drop.rs

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