lumus_sql_builder/sqlite/
insert.rs1use super::BuildableStatement;
2use crate::errors::SqlBuilderError;
3
4#[derive(Debug)]
6pub struct Insert {
7 pub table: String,
8 pub values: Vec<(String, String)>,
9}
10
11impl Insert {
12 pub fn new(table: &str) -> Self {
28 Self {
29 table: table.to_string(),
30 values: Vec::new(),
31 }
32 }
33
34 pub fn values(mut self, values: Vec<(&str, &str)>) -> Self {
36 self.values = values
37 .into_iter()
38 .map(|(col, val)| (col.to_string(), val.to_string()))
39 .collect();
40 self
41 }
42
43 pub fn build(&self) -> Result<String, SqlBuilderError> {
45 if self.table.is_empty() {
46 return Err(SqlBuilderError::EmptyTableName);
47 }
48
49 if self.values.is_empty() {
50 return Err(SqlBuilderError::EmptyColumnAndValue);
51 }
52
53 let mut columns: Vec<String> = vec![];
54 let mut values: Vec<String> = vec![];
55
56 for (col, val) in &self.values {
57 if col.is_empty() {
58 return Err(SqlBuilderError::EmptyColumnName);
59 }
60 if val.is_empty() {
61 return Err(SqlBuilderError::EmptyValue);
62 }
63
64 columns.push(col.clone());
65 values.push(format!("'{}'", val.clone()));
66 }
67
68 Ok(format!(
69 "INSERT INTO {} ({}) VALUES ({});",
70 self.table,
71 columns.join(", "),
72 values.join(", ")
73 ))
74 }
75}
76
77impl BuildableStatement for Insert {
79 fn build(&self) -> String {
80 self.build().unwrap()
81 }
82}