Skip to main content

ngb_sqlbuilder/
update.rs

1use crate::clause::Clause;
2use crate::select::__where;
3use crate::{wrap, Condition, SqlClause, __and_cond, __and_wrap, __condition, __or_cond, __or_wrap};
4use tokio_postgres::types::ToSql;
5
6pub struct Update;
7pub struct UpdateSet;
8pub struct UpdateWhere;
9pub fn update<'q>(table: &str) -> Clause<'q, Update> {
10    let mut sql = String::from("update ");
11    sql.push_str(&wrap(table));
12    Clause::new(sql, vec![])
13}
14
15impl<'q> Clause<'q, Update> {
16    pub fn set(self, map: &[(&str, &'q (dyn ToSql + Sync + 'q))]) -> Clause<'q, UpdateSet> {
17        let (mut sql, mut params) = self.unwrap();
18        sql.push_str(" set ");
19        let mut not_first = false;
20        for (k, v) in map {
21            if not_first {
22                sql.push_str(", ");
23            } else {
24                not_first = true;
25            }
26            sql.push_str(&wrap(k));
27            sql.push_str(" = $");
28            params.push(*v);
29        }
30        Clause::new(sql, params)
31    }
32}
33
34impl<'q> Clause<'q, UpdateSet> {
35    pub fn where_col(
36        self,
37        name: &str,
38        condition: Clause<'q, Condition>,
39    ) -> Clause<'q, UpdateWhere> {
40        __where(self, name, condition)
41    }
42
43    pub fn where_cond(self, condition: Clause<'q, Condition>) -> Clause<'q, UpdateWhere> {
44        __condition(self, condition)
45    }
46}
47
48impl<'q> Clause<'q, UpdateWhere> {
49    pub fn and_cond(self, condition: Clause<'q, Condition>) -> Clause<'q, UpdateWhere> {
50        __and_cond(self, condition)
51    }
52    pub fn or_cond(self, condition: Clause<'q, Condition>) -> Clause<'q, UpdateWhere> {
53        __or_cond(self, condition)
54    }
55    pub fn and_wrap(self, condition: Clause<'q, Condition>) -> Clause<'q, UpdateWhere> {
56        __and_wrap(self, condition)
57    }
58    pub fn or_wrap(self, condition: Clause<'q, Condition>) -> Clause<'q, UpdateWhere> {
59        __or_wrap(self, condition)
60    }
61}
62
63#[cfg(test)]
64mod test {
65    use super::*;
66    use crate::*;
67    #[test]
68    fn test_update() {
69        let name = String::from("test");
70        let (sql, params) = update("Table")
71            .set(&[("Value", &1), ("Name", &name)])
72            .where_col("Id", eq(&123))
73            .build();
74        println!("{}", sql);
75        println!("{:?}", params);
76    }
77}