Skip to main content

oxilite_d1/
lib.rs

1//! Cloudflare D1 backend for oxilite in Rust Workers.
2//!
3//! ```ignore
4//! let store = oxilite::AsyncStore::open(oxilite_d1::D1Backend::new(env.d1("DB")?)).await?;
5//! ```
6//!
7//! Atomic requests run as one `batch()` (D1's only transaction); single reads use `raw()`.
8//! 64-bit ids travel as TEXT because D1 returns JavaScript numbers.
9//!
10// @lat: [[architecture#Backends#Cloudflare D1]]
11
12#[cfg(target_arch = "wasm32")]
13mod d1 {
14    use js_sys::{Array, Function, Promise, Reflect};
15    use oxilite_core::sql::{Capabilities, Mode, Request, Response, ResultSet, SqlValue};
16    use oxilite_core::{AsyncBackend, Error, Result};
17    use serde_json::{Map, Value};
18    use wasm_bindgen::{JsCast, JsValue};
19    use wasm_bindgen_futures::JsFuture;
20    use worker::D1Database;
21
22    /// A D1 binding used as an oxilite backend.
23    pub struct D1Backend {
24        db: D1Database,
25        caps: Capabilities,
26    }
27
28    impl D1Backend {
29        pub fn new(db: D1Database) -> Self {
30            Self::with_capabilities(db, Capabilities::d1())
31        }
32
33        pub fn with_capabilities(db: D1Database, caps: Capabilities) -> Self {
34            Self { db, caps }
35        }
36    }
37
38    fn value(v: Value) -> SqlValue {
39        match v {
40            Value::Null => SqlValue::Null,
41            Value::Bool(b) => SqlValue::Integer(i64::from(b)),
42            Value::Number(n) => match n.as_i64() {
43                Some(i) => SqlValue::Integer(i),
44                None => SqlValue::Real(n.as_f64().unwrap_or(f64::NAN)),
45            },
46            Value::String(s) => SqlValue::Text(s),
47            other => SqlValue::Text(other.to_string()),
48        }
49    }
50
51    fn err(e: worker::Error) -> Error {
52        Error::backend(e)
53    }
54
55    fn js_err(e: JsValue) -> Error {
56        let message = Reflect::get(&e, &"message".into())
57            .ok()
58            .and_then(|m| m.as_string())
59            .unwrap_or_else(|| format!("{e:?}"));
60        Error::backend(message)
61    }
62
63    impl AsyncBackend for D1Backend {
64        async fn execute(&self, request: &Request) -> Result<Response> {
65            if request.statements.is_empty() {
66                return Ok(Vec::new());
67            }
68            if request.statements.iter().any(|s| !s.params.is_empty()) {
69                return Err(Error::unsupported(
70                    "bound parameters on D1 (oxilite inlines constants)",
71                ));
72            }
73            if request.mode == Mode::Read && request.statements.len() == 1 {
74                let rows: Vec<Vec<Value>> = self
75                    .db
76                    .prepare(&request.statements[0].sql)
77                    .raw()
78                    .await
79                    .map_err(err)?;
80                return Ok(vec![ResultSet {
81                    rows: rows
82                        .into_iter()
83                        .map(|r| r.into_iter().map(value).collect())
84                        .collect(),
85                    changes: 0,
86                }]);
87            }
88            // `worker::D1Result::meta()` deserializes `last_row_id` as an i64, which fails on
89            // oxilite's 60-bit term ids (a JavaScript number above 2^53): read the batch results
90            // through js-sys instead.
91            let stmts: Array = request
92                .statements
93                .iter()
94                .map(|s| JsValue::from(self.db.prepare(&s.sql).inner().clone()))
95                .collect();
96            let db: &JsValue = self.db.as_ref();
97            let batch: Function = Reflect::get(db, &"batch".into())
98                .map_err(js_err)?
99                .unchecked_into();
100            let promise: Promise = batch.call1(db, &stmts).map_err(js_err)?.unchecked_into();
101            let results: Array = JsFuture::from(promise)
102                .await
103                .map_err(js_err)?
104                .unchecked_into();
105            results
106                .iter()
107                .map(|r| {
108                    // Column order is the object key order (serde_json preserve_order).
109                    let rows = Reflect::get(&r, &"results".into()).map_err(js_err)?;
110                    let rows: Vec<Map<String, Value>> = if rows.is_undefined() || rows.is_null() {
111                        Vec::new()
112                    } else {
113                        serde_wasm_bindgen::from_value(rows)
114                            .map_err(|e| Error::backend(e.to_string()))?
115                    };
116                    let changes = Reflect::get(&r, &"meta".into())
117                        .and_then(|m| Reflect::get(&m, &"changes".into()))
118                        .ok()
119                        .and_then(|c| c.as_f64())
120                        .unwrap_or(0.0) as u64;
121                    Ok(ResultSet {
122                        rows: rows
123                            .into_iter()
124                            .map(|m| m.into_iter().map(|(_, v)| value(v)).collect())
125                            .collect(),
126                        changes,
127                    })
128                })
129                .collect()
130        }
131
132        fn capabilities(&self) -> &Capabilities {
133            &self.caps
134        }
135    }
136}
137
138#[cfg(target_arch = "wasm32")]
139pub use d1::D1Backend;
140
141/// The oxilite schema as a D1 migration script.
142pub fn migration_sql(graph_index: bool) -> String {
143    oxilite_core::schema::schema_sql(&oxilite_core::StoreOptions {
144        graph_index,
145        ..Default::default()
146    })
147}