1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
use crate::sql::{
    dialects::{
        condition::{Condition, Where, WhereAppend},
        schema::{self, schema::Schema},
    },
    schema::table::TableSchema,
    utils::pair::Pair,
};

use super::builder::ExecuteBuilder;
use sqlx::Database;

#[derive(Debug)]
pub struct UpdateBuilder<'a> {
    table: TableSchema,
    default_schema: &'a str,
    columns: Vec<Pair>,
    wh: Option<Where>,
}

impl<'a> UpdateBuilder<'a> {
    pub fn new(table: TableSchema) -> Self {
        Self {
            table,
            default_schema: "",
            columns: vec![],
            wh: None,
        }
    }

    pub fn with_default_schema(mut self, schema: &'a str) -> Self {
        self.default_schema = schema;
        self
    }

    pub fn set(mut self, pair: Pair) -> Self {
        self.columns.push(pair);
        // self.r#where()
        self
    }
}
impl<'a> WhereAppend<Condition> for UpdateBuilder<'a> {
    fn and(mut self, cond: Condition) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.and(cond));
        } else {
            self.wh = Some(Where::new(cond));
        }
        self
    }

    fn or(mut self, cond: Condition) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.or(cond));
        } else {
            self.wh = Some(Where::new(cond));
        }
        self
    }
}

impl<'a> WhereAppend<Where> for UpdateBuilder<'a> {
    fn and(mut self, wh: Where) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.and(wh));
        } else {
            self.wh = Some(wh);
        }
        self
    }

    fn or(mut self, wh: Where) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.or(wh));
        } else {
            self.wh = Some(wh);
        }
        self
    }
}

#[cfg(feature = "postgres")]
use sqlx::Postgres;

impl<'a> ExecuteBuilder for UpdateBuilder<'a> {
    #[cfg(feature = "postgres")]
    type DB = Postgres;

    async fn execute<C>(
        &self,
        conn: &mut C,
    ) -> Result<<Self::DB as sqlx::Database>::QueryResult, sqlx::Error>
    where
        for<'e> &'e mut C: sqlx::Executor<'e, Database = Self::DB>,
    {
        let schema = schema::new(self.default_schema.to_string());

        let cols: Vec<String> = self.columns.iter().map(|c| c.name.to_string()).collect();
        let sql = schema.sql_update_columns(&self.table, &cols, self.wh.clone());

        let mut query: sqlx::query::Query<'_, Self::DB, <Self::DB as Database>::Arguments<'_>> =
            sqlx::query::<Self::DB>(&sql);

        for col in &self.columns {
            query = col.value.bind_to_query(query);
        }

        if let Some(w) = &self.wh {
            query = w.bind_to_query(query);
        }

        let result = query.execute(conn).await.map_err(|err| {
            let sets = &self
                .columns
                .iter()
                .map(|c| c.value.as_string())
                .collect::<Vec<String>>()
                .join(",");
            let wh = if let Some(w) = &self.wh {
                w.list_params()
            } else {
                "".to_string()
            };
            tracing::error!(
                "easy-sqlx: {} set [{}] where [{}]; \n{:?}", sql, sets, wh, err
            );
            err
        })?;

        #[cfg(feature = "logsql")]
        {
            let sets = &self
                .columns
                .iter()
                .map(|c| c.value.as_string())
                .collect::<Vec<String>>()
                .join(",");
            let wh = if let Some(w) = &self.wh {
                w.list_params()
            } else {
                "".to_string()
            };
            tracing::info!(
                "easy-sqlx: {sql} set [{sets}] where [{wh}]; \nrows_affected: {}",
                result.rows_affected()
            );
        }
        Ok(result)
    }
}