lumus_sql_builder/sqlite/
insert.rs

1use super::BuildableStatement;
2use crate::errors::SqlBuilderError;
3
4/// Represents the creation of a INSERT with specified table and values.
5#[derive(Debug)]
6pub struct Insert {
7    pub table: String,
8    pub values: Vec<(String, String)>,
9}
10
11impl Insert {
12    /// Creates a new `Insert` instance with the given table name.
13    /// # Example
14    /// ```
15    /// use lumus_sql_builder::sqlite::Insert;
16    ///
17    /// let insert = Insert::new("metas_clientes_tb").values(vec![
18    ///     ("name", "João"),
19    ///     ("age", "30"),
20    ///     ("department", "TI"),
21    ///     ("salary", "5000.00"),
22    ///     ("hired_date", "2024-03-20"),
23    ///     ("manager_id", "1"),
24    /// ]).build().unwrap();
25    /// ```
26    /// assert_eq!(insert, "INSERT INTO metas_clientes_tb (name, age, department, salary, hired_date, manager_id) VALUES ('João', '30', 'TI', '5000.00', '2024-03-20', '1');")
27    pub fn new(table: &str) -> Self {
28        Self {
29            table: table.to_string(),
30            values: Vec::new(),
31        }
32    }
33
34    /// Sets the values to be inserted.
35    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    /// Builds and returns the SQL statement for the `INSERT` query.
44    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
77/// Implementation of the `BuildableStatement` trait for `Delete`, allowing it to be printed.
78impl BuildableStatement for Insert {
79    fn build(&self) -> String {
80        self.build().unwrap()
81    }
82}