lumus_sql_builder/sqlite/
update.rs1use super::BuildableStatement;
2use crate::errors::SqlBuilderError;
3
4#[derive(Debug)]
6pub struct Update {
7 table: String,
8 pub set: Vec<(String, String)>,
9 condition: Option<String>,
10}
11
12impl Update {
13 pub fn new(table: &str) -> Self {
29 Self {
30 table: table.to_string(),
31 set: Vec::new(),
32 condition: None,
33 }
34 }
35
36 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 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
86impl BuildableStatement for Update {
88 fn build(&self) -> String {
89 self.build().unwrap()
90 }
91}