sql/grammar/statement/
create_table.rs

1use Result;
2use grammar::definition::Column;
3use grammar::{Buffer, Definition, Statement};
4
5/// A `CREATE TABLE` statement.
6#[derive(Clone, Debug, Default)]
7pub struct CreateTable {
8    name: Option<String>,
9    if_not_exists: Option<()>,
10    columns: Option<Vec<Column>>,
11}
12
13impl CreateTable {
14    /// Create a `CREATE TABLE` statement.
15    #[inline]
16    pub fn new<T: ToString>(name: T) -> Self {
17        CreateTable::default().name(name)
18    }
19
20    /// Set the name.
21    pub fn name<T: ToString>(mut self, name: T) -> Self {
22        self.name = Some(name.to_string());
23        self
24    }
25
26    /// Mark that it should be applied only if the table does not exist.
27    pub fn if_not_exists(mut self) -> Self {
28        self.if_not_exists = Some(());
29        self
30    }
31
32    /// Add a column.
33    pub fn column(mut self, name: Column) -> Self {
34        push!(self.columns, name);
35        self
36    }
37
38    /// Add multiple columns.
39    pub fn columns(mut self, names: &[Column]) -> Self {
40        for name in names {
41            push!(self.columns, name.clone());
42        }
43        self
44    }
45}
46
47impl Statement for CreateTable {
48    fn compile(&self) -> Result<String> {
49        let mut buffer = Buffer::new();
50        buffer.push("CREATE TABLE");
51        if let Some(_) = self.if_not_exists {
52             buffer.push("IF NOT EXISTS");
53        }
54        buffer.push(format!("`{}`", some!(self.name)));
55        buffer.push({
56            let mut buffer = Buffer::new();
57            for column in some!(self.columns) {
58                buffer.push(try!(column.compile()));
59            }
60            format!("({})", buffer.join(", "))
61        });
62        Ok(buffer.join(" "))
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use prelude::*;
69
70    #[test]
71    fn columns() {
72        let statement = create_table("foo").columns(&[column("bar").float(),
73                                                      column("baz").string()]);
74
75        assert_eq!(statement.compile().unwrap(), "CREATE TABLE `foo` (`bar` REAL, `baz` TEXT)");
76    }
77
78    #[test]
79    fn if_not_exists() {
80        let statement = create_table("foo").if_not_exists().column(column("bar").float());
81        assert_eq!(statement.compile().unwrap(), "CREATE TABLE IF NOT EXISTS `foo` (`bar` REAL)");
82    }
83}