lumus_sql_builder/sqlite/
create_table.rs1use super::{BuildableStatement, Column};
2use crate::errors::SqlBuilderError;
3
4#[derive(Debug)]
6pub struct CreateTable {
7 table: String,
8 columns: Vec<Column>,
9 if_not_exists: bool,
10}
11
12impl CreateTable {
13 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 pub fn if_not_exists(mut self) -> Self {
33 self.if_not_exists = true;
34 self
35 }
36
37 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
63impl BuildableStatement for CreateTable {
65 fn build(&self) -> String {
66 self.build().unwrap()
67 }
68}