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