Skip to main content

sea_query/table/
rename.rs

1use crate::{SchemaStatementBuilder, backend::SchemaBuilder, types::*};
2
3/// Rename a table
4///
5/// # Examples
6///
7/// ```
8/// use sea_query::{tests_cfg::*, *};
9///
10/// let table = Table::rename().table(Font::Table, "font_new").to_owned();
11///
12/// assert_eq!(
13///     table.to_string(MysqlQueryBuilder),
14///     r#"RENAME TABLE `font` TO `font_new`"#
15/// );
16/// assert_eq!(
17///     table.to_string(PostgresQueryBuilder),
18///     r#"ALTER TABLE "font" RENAME TO "font_new""#
19/// );
20/// assert_eq!(
21///     table.to_string(SqliteQueryBuilder),
22///     r#"ALTER TABLE "font" RENAME TO "font_new""#
23/// );
24/// ```
25#[derive(Default, Debug, Clone)]
26pub struct TableRenameStatement {
27    pub(crate) from_name: Option<TableRef>,
28    pub(crate) to_name: Option<TableRef>,
29}
30
31impl TableRenameStatement {
32    /// Construct rename table statement
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    /// Set old and new table name
38    pub fn table<T, R>(&mut self, from_name: T, to_name: R) -> &mut Self
39    where
40        T: IntoTableRef,
41        R: IntoTableRef,
42    {
43        self.from_name = Some(from_name.into_table_ref());
44        self.to_name = Some(to_name.into_table_ref());
45        self
46    }
47
48    pub fn take(&mut self) -> Self {
49        Self {
50            from_name: self.from_name.take(),
51            to_name: self.to_name.take(),
52        }
53    }
54}
55
56impl SchemaStatementBuilder for TableRenameStatement {
57    fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
58        let mut sql = String::with_capacity(256);
59        schema_builder.prepare_table_rename_statement(self, &mut sql);
60        sql
61    }
62}
63
64impl TableRenameStatement {
65    pub fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
66        <Self as SchemaStatementBuilder>::build(self, schema_builder)
67    }
68
69    pub fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String {
70        <Self as SchemaStatementBuilder>::to_string(self, schema_builder)
71    }
72}