lumus_sql_builder/sqlite/
update.rs

1use super::BuildableStatement;
2use crate::errors::SqlBuilderError;
3
4/// Represents a ´UPDATE´ clause builder for SQL queries
5#[derive(Debug)]
6pub struct Update {
7    table: String,
8    pub set: Vec<(String, String)>,
9    condition: Option<String>,
10}
11
12impl Update {
13    /// Creates a new `Update` instance with the given table name.
14    /// # Example
15    /// ```
16    /// use lumus_sql_builder::sqlite::{Update, Where};
17    ///
18    /// let mut condition = Where::new();
19    /// condition.equal_to("age", "21");
20    ///
21    /// let update = Update::new("users_tb").set(vec![
22    ///     ("name", "João")
23    /// ]).condition(condition.build())
24    /// .build();
25    ///
26    /// assert_eq!("UPDATE users_tb SET name = 'João' WHERE age = '21';", update.unwrap());
27    /// ```
28    pub fn new(table: &str) -> Self {
29        Self {
30            table: table.to_string(),
31            set: Vec::new(),
32            condition: None,
33        }
34    }
35
36    /// Sets the values to be updated.
37    pub fn set<T: ToString>(mut self, set: Vec<(&str, T)>) -> Self {
38        self.set = set
39            .into_iter()
40            .map(|(col, val)| (col.to_string(), val.to_string()))
41            .collect();
42        self
43    }
44
45    /// Specifies where for `Update`.
46    pub fn condition(&mut self, condition: String) -> &mut Self {
47        self.condition = Some(condition);
48        self
49    }
50
51    pub fn build(&self) -> Result<String, SqlBuilderError> {
52        if self.table.is_empty() {
53            return Err(SqlBuilderError::EmptyTableName);
54        }
55
56        if self.set.is_empty() {
57            return Err(SqlBuilderError::EmptyColumnAndValue);
58        }
59
60        let mut sets: Vec<String> = vec![];
61
62        for (col, val) in &self.set {
63            if col.is_empty() {
64                return Err(SqlBuilderError::EmptyColumnName);
65            }
66            if val.is_empty() {
67                return Err(SqlBuilderError::EmptyValue);
68            }
69
70            sets.push(format!("{} = '{}'", col.clone(), val.clone()));
71        }
72
73        if let Some(condition) = &self.condition {
74            return Ok(format!(
75                "UPDATE {} SET {} WHERE {};",
76                self.table,
77                sets.join(", "),
78                condition
79            ));
80        }
81
82        Ok(format!("UPDATE {} SET {};", self.table, sets.join(", "),))
83    }
84}
85
86/// Implementation of the `BuildableStatement` trait for `Update`, allowing it to be printed.
87impl BuildableStatement for Update {
88    fn build(&self) -> String {
89        self.build().unwrap()
90    }
91}