lumus_sql_builder/sqlite/
create_table.rs

1use super::{BuildableStatement, Column};
2use crate::errors::SqlBuilderError;
3
4/// Represents the creation of a table with specified columns and options.
5#[derive(Debug)]
6pub struct CreateTable {
7    table: String,
8    columns: Vec<Column>,
9    if_not_exists: bool,
10}
11
12impl CreateTable {
13    /// Creates a new `CreateTable` instance with the given table name and columns.
14    /// # Example
15    /// ```
16    /// use lumus_sql_builder::sqlite::{CreateTable, Column};
17    /// let create_table = CreateTable::new("users", vec![
18    ///     Column::new("name").text().not_null().primary_key(),
19    /// ]).build().unwrap();
20    ///
21    /// assert_eq!(create_table, "CREATE TABLE users (name TEXT NOT NULL PRIMARY KEY);");
22    /// ```
23    pub fn new(table: &str, columns: Vec<Column>) -> Self {
24        Self {
25            table: table.to_string(),
26            columns,
27            if_not_exists: false,
28        }
29    }
30
31    /// Specifies that the table should be created only if it does not already exist.
32    pub fn if_not_exists(mut self) -> Self {
33        self.if_not_exists = true;
34        self
35    }
36
37    /// Builds and returns the SQL statement for creating the table.
38    pub fn build(&self) -> Result<String, SqlBuilderError> {
39        if self.table.is_empty() {
40            return Err(SqlBuilderError::EmptyTableName);
41        }
42
43        if self.columns.is_empty() {
44            return Err(SqlBuilderError::NoColumnsSpecified);
45        }
46
47        let mut statement = if self.if_not_exists {
48            format!("CREATE TABLE IF NOT EXISTS {} (", self.table)
49        } else {
50            format!("CREATE TABLE {} (", self.table)
51        };
52
53        let columns_sql: Result<Vec<String>, SqlBuilderError> =
54            self.columns.iter().map(|col| col.build()).collect();
55
56        statement.push_str(&columns_sql?.join(", "));
57        statement.push_str(");");
58
59        Ok(statement)
60    }
61}
62
63/// Implementation of the `BuildableStatement` trait for `CreateTable`, allowing it to be printed.
64impl BuildableStatement for CreateTable {
65    fn build(&self) -> String {
66        self.build().unwrap()
67    }
68}