rust-d1-orm 0.0.1

Query builder / ORM for Cloudflare D1, targeting wasm32-unknown-unknown
Documentation
use worker::wasm_bindgen::JsValue;

pub struct Set {
    fields: Vec<(String, JsValue)>,
}

impl Set {
    pub fn new() -> Self {
        Self { fields: vec![] }
    }

    pub fn field(mut self, col: &str, val: impl Into<JsValue>) -> Self {
        self.fields.push((col.to_string(), val.into()));
        self
    }

    pub fn nullable_field(mut self, col: &str, val: Option<impl Into<JsValue>>) -> Self {
        let js = val.map(Into::into).unwrap_or(JsValue::NULL);
        self.fields.push((col.to_string(), js));
        self
    }

    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    pub(crate) fn build(&self, param_start: usize) -> (String, Vec<JsValue>, usize) {
        let mut parts: Vec<String> = vec![];
        let mut values: Vec<JsValue> = vec![];
        let mut n = param_start;
        for (col, val) in &self.fields {
            parts.push(format!("{} = ?{}", col, n));
            values.push(val.clone());
            n += 1;
        }
        (parts.join(", "), values, n)
    }
}

impl Default for Set {
    fn default() -> Self { Self::new() }
}