Skip to main content

d1_orm_query/
set.rs

1use crate::value::Value;
2
3#[derive(Clone)]
4pub enum SetField {
5    Value(String, Value),
6    Raw(String, String),
7}
8
9#[derive(Clone)]
10pub struct Set {
11    fields: Vec<SetField>,
12}
13
14impl Set {
15    pub fn new() -> Self {
16        Self { fields: vec![] }
17    }
18
19    pub fn field(mut self, col: &str, val: impl Into<Value>) -> Self {
20        self.fields.push(SetField::Value(col.into(), val.into()));
21        self
22    }
23
24    pub fn nullable_field(mut self, col: &str, val: Option<impl Into<Value>>) -> Self {
25        let v = val.map(Into::into).unwrap_or(Value::Null);
26        self.fields.push(SetField::Value(col.into(), v));
27        self
28    }
29
30    pub fn raw_expr(mut self, col: &str, expr: &str) -> Self {
31        self.fields.push(SetField::Raw(col.into(), expr.into()));
32        self
33    }
34
35    pub fn is_empty(&self) -> bool {
36        self.fields.is_empty()
37    }
38
39    pub fn build(&self, param_start: usize) -> (String, Vec<Value>, usize) {
40        let mut parts: Vec<String> = vec![];
41        let mut values: Vec<Value> = vec![];
42        let mut n = param_start;
43        for field in &self.fields {
44            match field {
45                SetField::Value(col, val) => {
46                    parts.push(format!("{} = ?{}", col, n));
47                    values.push(val.clone());
48                    n += 1;
49                }
50                SetField::Raw(col, expr) => {
51                    parts.push(format!("{} = {}", col, expr));
52                }
53            }
54        }
55        (parts.join(", "), values, n)
56    }
57}
58
59impl Default for Set {
60    fn default() -> Self { Self::new() }
61}