Skip to main content

day_persistence/
rusqlite_driver.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The built-in driver. On native targets the engine is rusqlite, chosen by cargo feature:
5//! `bundled` (the default), `system` (link the OS's libsqlite3), or `cipher` (SQLCipher with
6//! vendored crypto). On web-dom the engine is day-sqlite-worker: `:memory:` databases run
7//! in-process, and file databases are proxied synchronously to the day-sql worker, which
8//! holds them on real OPFS (see the web module at the end of this file). One driver type,
9//! recompiled; not a crate per engine.
10
11use std::rc::Rc;
12
13#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
14use rusqlite::Connection;
15
16#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
17type InitHook = Rc<dyn Fn(&Connection)>;
18
19use crate::{
20    Capabilities, DbError, DbErrorKind, Location, OpenOptions, Row, Secret, SqliteConnection,
21    SqliteDriver, Value,
22};
23
24/// The built-in SQLite driver. `Sqlite::at(path)` or `Sqlite::memory()`, then builder options.
25/// A statement-trace sink (`Sqlite::trace_sql`).
26type TraceFn = Rc<dyn Fn(&str)>;
27
28pub struct Sqlite {
29    opts: OpenOptions,
30    /// Runs against the raw rusqlite connection right after open, to register a custom SQL
31    /// function, load an extension, or set a PRAGMA. The framework neither knows nor cares.
32    /// Native only: the web engine lives in the day-sql worker, out of closure reach.
33    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
34    init: Option<InitHook>,
35    /// The statement-trace sink (`trace_sql`).
36    trace: Option<TraceFn>,
37}
38
39impl Sqlite {
40    fn from_opts(opts: OpenOptions) -> Self {
41        Sqlite {
42            opts,
43            #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
44            init: None,
45            trace: None,
46        }
47    }
48    pub fn at(path: impl Into<std::path::PathBuf>) -> Self {
49        Sqlite::from_opts(OpenOptions::new(Location::File(path.into())))
50    }
51    pub fn memory() -> Self {
52        Sqlite::from_opts(OpenOptions::new(Location::Memory))
53    }
54    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
55    /// The database named `name` (`"notes.db"`: `.db` by convention) in the app's data
56    /// directory, `day_spec::storage::data_dir()`, created if missing: a folder named for the app
57    /// in the platform's place for app data (Application Support, `%LOCALAPPDATA%`,
58    /// `$XDG_DATA_HOME`, the Android and HarmonyOS files directory; Day's docs/fs.md "Where files
59    /// live"), or `DAY_DATA_DIR` when a host or a test sets it. `name` is a file name, not a path.
60    /// Errs where no such directory exists (web has no
61    /// filesystem; keep a wasm build on [`Sqlite::memory`] or its own driver).
62    pub fn app_data(name: impl AsRef<str>) -> Result<Self, DbError> {
63        let name = name.as_ref();
64        if name.is_empty() || name.contains(['/', '\\']) || name.contains("..") {
65            return Err(DbError::new(
66                DbErrorKind::Unsupported,
67                format!("app_data takes a file name, not a path: {name:?}"),
68            ));
69        }
70        let dir = Self::app_data_dir()?;
71        std::fs::create_dir_all(&dir)
72            .map_err(|e| DbError::driver(format!("creating {}: {e}", dir.display())))?;
73        Ok(Sqlite::at(dir.join(name)))
74    }
75    /// The database key (feature `cipher`; other builds refuse it at open, loudly).
76    pub fn key(mut self, key: Secret) -> Self {
77        self.opts.key = Some(key);
78        self
79    }
80    /// Accept a file written by an older SQLCipher generation (`PRAGMA cipher_migrate`).
81    pub fn cipher_migrate(mut self) -> Self {
82        self.opts.cipher_migrate = true;
83        self
84    }
85    pub fn wal(mut self, on: bool) -> Self {
86        self.opts.wal = on;
87        self
88    }
89    /// The directory [`Sqlite::app_data`] resolves into, for apps that manage their document
90    /// files there (numbering "Drawing 2", importing a picked file). Created lazily by
91    /// `app_data`; this accessor only resolves it.
92    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
93    pub fn app_data_dir() -> Result<std::path::PathBuf, DbError> {
94        app_data_root()
95    }
96
97    /// A per-connection hook over the raw rusqlite connection: the escape valve for loadable
98    /// extensions, custom functions, and PRAGMAs this crate does not model. Native only.
99    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
100    pub fn with_init(mut self, f: impl Fn(&Connection) + 'static) -> Self {
101        self.init = Some(Rc::new(f));
102        self
103    }
104
105    /// Per-statement SQL tracing through the engine's own facility (`sqlite3_trace_v2` with
106    /// `SQLITE_TRACE_STMT`): `f` sees every statement this connection executes (migrations,
107    /// autosave flushes, live-query `SELECT`s, maintenance) with bound parameters expanded by
108    /// the engine itself. Wire it to a logger in debug builds:
109    ///
110    /// ```ignore
111    /// let driver = Sqlite::app_data("trips.db")?;
112    /// let driver = if cfg!(debug_assertions) {
113    ///     driver.trace_sql(|sql| log::trace!("sql: {sql}"))
114    /// } else {
115    ///     driver
116    /// };
117    /// ```
118    ///
119    /// The trace installs after any `PRAGMA key`, so a cipher key never reaches the sink. On
120    /// web-dom a file database's engine runs in the day-sql worker, out of closure reach:
121    /// there the statements log to the browser console (`[day-sql]` lines in devtools) and
122    /// `f` is not called. `:memory:` databases call `f` on every target.
123    pub fn trace_sql(mut self, f: impl Fn(&str) + 'static) -> Self {
124        self.trace = Some(Rc::new(f));
125        self
126    }
127}
128
129impl SqliteDriver for Sqlite {
130    type Connection = RusqliteConn;
131
132    /// The proxy open: `:memory:` runs in-process (no file I/O exists in that engine shape);
133    /// a file database opens inside the day-sql worker over the synchronous channel.
134    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
135    fn open(self) -> Result<RusqliteConn, DbError> {
136        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
137        if self.opts.key.is_some() {
138            return Err(DbError::new(
139                DbErrorKind::Unsupported,
140                "this build has no encryption — the web engine does not include SQLCipher",
141            ));
142        }
143        let conn = match &self.opts.location {
144            Location::Memory => {
145                let mut conn = day_sqlite_worker::Connection::open_memory()
146                    .map_err(|e| DbError::driver(e.to_string()))?;
147                if let Some(f) = &self.trace {
148                    let f = f.clone();
149                    conn.trace_stmt(Box::new(move |sql| f(sql)));
150                }
151                WebConn::Memory(conn)
152            }
153            Location::File(p) => {
154                let name = p.to_string_lossy().into_owned();
155                match web::channel::call(&WReq::Open {
156                    name,
157                    trace: self.trace.is_some(),
158                })? {
159                    WReply::Conn(id) => WebConn::Remote(id),
160                    other => return Err(web::unexpected(other)),
161                }
162            }
163        };
164        let mut conn = RusqliteConn { conn };
165        if self.opts.foreign_keys {
166            conn.execute("PRAGMA foreign_keys = ON", &[])?;
167        }
168        Ok(conn)
169    }
170
171    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
172    fn open(self) -> Result<RusqliteConn, DbError> {
173        let conn = match &self.opts.location {
174            Location::Memory => Connection::open_in_memory(),
175            Location::File(p) => Connection::open(p),
176        }
177        .map_err(|e| DbError::driver(e.to_string()))?;
178
179        if let Some(key) = &self.opts.key {
180            #[cfg(feature = "cipher")]
181            {
182                // PRAGMA key takes no bound parameter; single-quote-escape the literal.
183                let quoted = key.reveal().replace('\'', "''");
184                conn.execute_batch(&format!("PRAGMA key = '{quoted}';"))
185                    .map_err(|e| DbError::driver(e.to_string()))?;
186                if self.opts.cipher_migrate {
187                    let _ = conn.execute_batch("PRAGMA cipher_migrate;");
188                }
189            }
190            #[cfg(not(feature = "cipher"))]
191            {
192                let _ = key;
193                return Err(DbError::new(
194                    DbErrorKind::Unsupported,
195                    "this build has no encryption — enable the `cipher` feature",
196                ));
197            }
198        }
199
200        // A wrong (or missing) key surfaces on the first real read, not at PRAGMA time. Probe
201        // now so the caller gets BadKey at open instead of a raw engine error later. Only the
202        // cipher build maps the failure to BadKey; a plaintext build's unreadable file is
203        // corruption, not a key problem.
204        #[cfg(feature = "cipher")]
205        if conn
206            .prepare("SELECT count(*) FROM sqlite_master")
207            .and_then(|mut s| s.query_row([], |_| Ok(())))
208            .is_err()
209        {
210            return Err(DbError::new(
211                DbErrorKind::BadKey,
212                "the database would not open with this key",
213            ));
214        }
215
216        // Trace after the key PRAGMA above (a cipher key must never reach the sink) and
217        // before everything else, so the remaining setup PRAGMAs log too.
218        let trace = self
219            .trace
220            .as_ref()
221            .map(|f| install_sql_trace(&conn, f.clone()));
222
223        // `day_fold`: Rust's full-Unicode `to_lowercase` as a scalar SQL function, so
224        // case-insensitive predicates compile to SQL that selects exactly the rows the
225        // in-memory fold would (SQLite's own `lower()` folds ASCII only). Deterministic, so
226        // the planner may hoist and index it.
227        {
228            use rusqlite::functions::FunctionFlags;
229            conn.create_scalar_function(
230                "day_fold",
231                1,
232                FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
233                |ctx| {
234                    let folded = match ctx.get_raw(0) {
235                        rusqlite::types::ValueRef::Text(t) => {
236                            Some(String::from_utf8_lossy(t).to_lowercase())
237                        }
238                        _ => None,
239                    };
240                    Ok(folded)
241                },
242            )
243            .map_err(|e| DbError::driver(format!("registering day_fold: {e}")))?;
244        }
245
246        conn.busy_timeout(std::time::Duration::from_millis(
247            self.opts.busy_timeout_ms as u64,
248        ))
249        .map_err(|e| DbError::driver(e.to_string()))?;
250        if self.opts.foreign_keys {
251            conn.execute_batch("PRAGMA foreign_keys = ON;")
252                .map_err(|e| DbError::driver(e.to_string()))?;
253        }
254        #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
255        if self.opts.wal && matches!(self.opts.location, Location::File(_)) {
256            conn.execute_batch("PRAGMA journal_mode = WAL;")
257                .map_err(|e| DbError::driver(e.to_string()))?;
258        }
259        if let Some(init) = &self.init {
260            init(&conn);
261        }
262        Ok(RusqliteConn {
263            conn,
264            _trace: trace,
265        })
266    }
267
268    fn capabilities(&self) -> Capabilities {
269        #[cfg(all(target_family = "wasm", target_os = "unknown"))]
270        {
271            Capabilities {
272                // A file database is durable when the day-sql worker holds it on OPFS: the
273                // worker fsyncs before each reply, so a commit that returned has landed. No
274                // channel (a host serving without cross-origin isolation) = no file databases
275                // at all: reported here, refused loudly at open.
276                durable: matches!(self.opts.location, Location::File(_)) && web::channel::ready(),
277                encryption: false,
278                wal: false,
279                // day-sqlite-worker pins FTS5 and R*Tree into its build.
280                full_text_search: true,
281                rtree: true,
282                external_changes: false,
283                // The web engine runs in the day-sql worker, out of reach of a Rust closure
284                // registration, so folded predicates take the exact fallback path instead.
285                unicode_fold: false,
286            }
287        }
288        #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
289        {
290            Capabilities {
291                durable: matches!(self.opts.location, Location::File(_)),
292                encryption: cfg!(feature = "cipher"),
293                wal: true,
294                // The bundled builds compile FTS5/R*Tree in; a system libsqlite3 may or may
295                // not, and claiming what we have not verified would be a lie the schema layer
296                // acts on.
297                full_text_search: cfg!(any(feature = "bundled", feature = "cipher")),
298                rtree: cfg!(any(feature = "bundled", feature = "cipher")),
299                // `PRAGMA data_version` is core SQLite: another connection's committed writes
300                // are detectable on any file database. A memory database has no second
301                // connection to detect.
302                external_changes: matches!(self.opts.location, Location::File(_)),
303                // `day_fold` registers at open on every native connection.
304                unicode_fold: true,
305            }
306        }
307    }
308}
309
310/// The app's data directory (`day_spec::storage::data_dir()`), shared with day-part-filesystem
311/// (whose files keep to its `day-fs/` leaf) and everything else of the app's.
312#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
313fn app_data_root() -> Result<std::path::PathBuf, DbError> {
314    day_spec::storage::data_dir().ok_or_else(|| {
315        DbError::new(
316            DbErrorKind::Unsupported,
317            "no per-app data directory on this target",
318        )
319    })
320}
321
322#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
323pub struct RusqliteConn {
324    conn: Connection,
325    /// Keeps the installed trace closure alive as long as the engine may call it (the box's
326    /// heap address is what `sqlite3_trace_v2` holds). Dropped after `conn` closes.
327    _trace: Option<Box<TraceFn>>,
328}
329
330/// Install the engine's per-statement trace on a raw connection handle. rusqlite's own
331/// `trace_v2` takes a plain fn pointer, so the closure rides the C-level context instead.
332#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
333fn install_sql_trace(conn: &Connection, f: TraceFn) -> Box<TraceFn> {
334    use rusqlite::ffi;
335    unsafe extern "C" fn cb(
336        ev: std::ffi::c_uint,
337        ctx: *mut std::ffi::c_void,
338        p: *mut std::ffi::c_void,
339        x: *mut std::ffi::c_void,
340    ) -> std::ffi::c_int {
341        if ev != ffi::SQLITE_TRACE_STMT || ctx.is_null() {
342            return 0;
343        }
344        // SAFETY: ctx is the connection's boxed trace closure (returned below and stored on
345        // RusqliteConn), alive until after the connection closes; day's connections are
346        // single-threaded, so the callback never races the closure.
347        let f = unsafe { &*(ctx as *const TraceFn) };
348        unsafe {
349            let expanded = ffi::sqlite3_expanded_sql(p.cast());
350            if !expanded.is_null() {
351                if let Ok(s) = std::ffi::CStr::from_ptr(expanded).to_str() {
352                    f(s);
353                }
354                ffi::sqlite3_free(expanded.cast());
355            } else if !x.is_null() {
356                // The engine could not expand (OOM, or a trigger frame): unexpanded text.
357                if let Ok(s) = std::ffi::CStr::from_ptr(x.cast()).to_str() {
358                    f(s);
359                }
360            }
361        }
362        0
363    }
364    let boxed = Box::new(f);
365    let ctx = &*boxed as *const TraceFn as *mut std::ffi::c_void;
366    // SAFETY: the handle is this connection's own; ctx points into `boxed`, whose heap slot
367    // outlives the connection via RusqliteConn::_trace.
368    unsafe {
369        ffi::sqlite3_trace_v2(conn.handle(), ffi::SQLITE_TRACE_STMT, Some(cb), ctx);
370    }
371    boxed
372}
373
374/// The web connection: in-process for `:memory:`, a worker connection id for files.
375#[cfg(all(target_family = "wasm", target_os = "unknown"))]
376enum WebConn {
377    Memory(day_sqlite_worker::Connection),
378    Remote(u32),
379}
380
381#[cfg(all(target_family = "wasm", target_os = "unknown"))]
382pub struct RusqliteConn {
383    conn: WebConn,
384}
385
386#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
387fn to_sql(v: &Value) -> rusqlite::types::Value {
388    use rusqlite::types::Value as R;
389    match v {
390        Value::Null => R::Null,
391        Value::Int(i) => R::Integer(*i),
392        Value::Real(f) => R::Real(*f),
393        Value::Text(t) => R::Text(t.clone()),
394        Value::Blob(b) => R::Blob(b.clone()),
395    }
396}
397
398#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
399fn from_sql(v: rusqlite::types::ValueRef<'_>) -> Value {
400    use rusqlite::types::ValueRef as R;
401    match v {
402        R::Null => Value::Null,
403        R::Integer(i) => Value::Int(i),
404        R::Real(f) => Value::Real(f),
405        R::Text(t) => Value::Text(String::from_utf8_lossy(t).into_owned()),
406        R::Blob(b) => Value::Blob(b.to_vec()),
407    }
408}
409
410#[cfg(all(target_family = "wasm", target_os = "unknown"))]
411impl SqliteConnection for RusqliteConn {
412    fn execute_batch(&mut self, sql: &str) -> Result<(), DbError> {
413        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
414        match &self.conn {
415            WebConn::Memory(c) => c
416                .execute_batch(sql)
417                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
418            WebConn::Remote(id) => match web::channel::call(&WReq::Batch {
419                conn: *id,
420                sql: sql.to_owned(),
421            })? {
422                WReply::Ok => Ok(()),
423                other => Err(web::unexpected(other)),
424            },
425        }
426    }
427
428    fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, DbError> {
429        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
430        match &self.conn {
431            WebConn::Memory(c) => c
432                .execute(sql, &web::to_wire(params))
433                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
434            WebConn::Remote(id) => match web::channel::call(&WReq::Exec {
435                conn: *id,
436                sql: sql.to_string(),
437                params: web::to_wire(params),
438            })? {
439                WReply::Changes(n) => Ok(n),
440                other => Err(web::unexpected(other)),
441            },
442        }
443    }
444
445    fn query(
446        &mut self,
447        sql: &str,
448        params: &[Value],
449        row: &mut dyn FnMut(&dyn Row),
450    ) -> Result<(), DbError> {
451        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
452        match &self.conn {
453            WebConn::Memory(c) => c
454                .query(sql, &web::to_wire(params), &mut |r| {
455                    let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
456                    row(&vals);
457                })
458                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
459            WebConn::Remote(id) => match web::channel::call(&WReq::Query {
460                conn: *id,
461                sql: sql.to_string(),
462                params: web::to_wire(params),
463            })? {
464                WReply::Rows(rows) => {
465                    for r in rows {
466                        let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
467                        row(&vals);
468                    }
469                    Ok(())
470                }
471                other => Err(web::unexpected(other)),
472            },
473        }
474    }
475    fn query_named(
476        &mut self,
477        sql: &str,
478        params: &[Value],
479        row: &mut dyn FnMut(&[String], &dyn Row),
480    ) -> Result<(), DbError> {
481        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
482        match &self.conn {
483            WebConn::Memory(c) => c
484                .query_named(sql, &web::to_wire(params), &mut |names, r| {
485                    let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
486                    row(names, &vals);
487                })
488                .map(|_| ())
489                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
490            WebConn::Remote(id) => match web::channel::call(&WReq::QueryNamed {
491                conn: *id,
492                sql: sql.to_owned(),
493                params: web::to_wire(params),
494            })? {
495                WReply::NamedRows { names, rows } => {
496                    for r in rows {
497                        let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
498                        row(&names, &vals);
499                    }
500                    Ok(())
501                }
502                other => Err(web::unexpected(other)),
503            },
504        }
505    }
506}
507
508/// A dropped remote connection closes its worker side, best effort, like a file handle.
509#[cfg(all(target_family = "wasm", target_os = "unknown"))]
510impl Drop for RusqliteConn {
511    fn drop(&mut self) {
512        if let WebConn::Remote(id) = self.conn {
513            let _ = web::channel::call(&day_sqlite_worker::protocol::Req::Close { conn: id });
514        }
515    }
516}
517
518#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
519impl SqliteConnection for RusqliteConn {
520    fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, DbError> {
521        // Cached, not re-prepared: the fold emits RUNS of identical SQL (one INSERT shape per
522        // table, one DELETE, one UPDATE per changed column set), so a bulk flush would
523        // otherwise re-parse the same statement thousands of times.
524        let mut stmt = self
525            .conn
526            .prepare_cached(sql)
527            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
528        let bound = rusqlite::params_from_iter(params.iter().map(to_sql));
529        stmt.execute(bound)
530            .map(|n| n as u64)
531            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))
532    }
533
534    fn query(
535        &mut self,
536        sql: &str,
537        params: &[Value],
538        row: &mut dyn FnMut(&dyn Row),
539    ) -> Result<(), DbError> {
540        let mut stmt = self
541            .conn
542            .prepare_cached(sql)
543            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
544        let bound = rusqlite::params_from_iter(params.iter().map(to_sql));
545        let mut rows = stmt
546            .query(bound)
547            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
548        loop {
549            match rows.next() {
550                Ok(Some(r)) => {
551                    let n = r.as_ref().column_count();
552                    let vals: Vec<Value> = (0..n)
553                        .map(|i| r.get_ref(i).map(from_sql).unwrap_or(Value::Null))
554                        .collect();
555                    row(&vals);
556                }
557                Ok(None) => break,
558                Err(e) => return Err(DbError::driver(e.to_string())),
559            }
560        }
561        Ok(())
562    }
563
564    fn execute_batch(&mut self, sql: &str) -> Result<(), DbError> {
565        self.conn
566            .execute_batch(sql)
567            .map_err(|e| DbError::driver(format!("{e} in batch")))
568    }
569
570    fn query_named(
571        &mut self,
572        sql: &str,
573        params: &[Value],
574        row: &mut dyn FnMut(&[String], &dyn Row),
575    ) -> Result<(), DbError> {
576        let mut stmt = self
577            .conn
578            .prepare(sql)
579            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
580        let names: Vec<String> = stmt.column_names().iter().map(|s| s.to_string()).collect();
581        let bound = rusqlite::params_from_iter(params.iter().map(to_sql));
582        let mut rows = stmt
583            .query(bound)
584            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
585        loop {
586            match rows.next() {
587                Ok(Some(r)) => {
588                    let n = r.as_ref().column_count();
589                    let vals: Vec<Value> = (0..n)
590                        .map(|i| r.get_ref(i).map(from_sql).unwrap_or(Value::Null))
591                        .collect();
592                    row(&names, &vals);
593                }
594                Ok(None) => break,
595                Err(e) => return Err(DbError::driver(e.to_string())),
596            }
597        }
598        Ok(())
599    }
600}
601
602// ---------------------------------------------------------------------------
603// The web leg (wasm32-unknown-unknown): the synchronous channel to the day-sql worker.
604//
605// OPFS's only random-access synchronous API (`createSyncAccessHandle`) exists solely in
606// dedicated workers, so the engine runs in day-sqlite-worker's day-sql worker (the same wasm
607// module, instantiated there) and this side is a proxy. Each call encodes one request in
608// day-sqlite-worker's protocol, hands it to that crate's channel, and the main thread blocks
609// the few microseconds until the worker's reply lands back through the SharedArrayBuffer.
610// Fully synchronous from Rust's point of view, fully durable at commit, one code path with
611// every other platform. The channel needs cross-origin isolation (COOP/COEP; `day launch`
612// serves it, see docs/web.md); without it File opens fail loudly and capabilities say
613// durable: false.
614// ---------------------------------------------------------------------------
615
616#[cfg(all(target_family = "wasm", target_os = "unknown"))]
617mod web {
618    use super::*;
619    use day_sqlite_worker::protocol::{self, Reply as WReply, Req as WReq, Value as WValue};
620
621    pub(super) mod channel {
622        use super::*;
623
624        pub(crate) fn ready() -> bool {
625            day_sqlite_worker::channel::ready()
626        }
627
628        /// One round trip. Worker-reported SQL errors come back as [`DbError`]s here, so
629        /// callers only ever match the success variants.
630        pub(crate) fn call(req: &WReq) -> Result<WReply, DbError> {
631            let Some(reply) = day_sqlite_worker::channel::call(&protocol::encode_req(req)) else {
632                return Err(DbError::new(
633                    DbErrorKind::Unsupported,
634                    "no SQL worker — file databases on the web need the day-sql worker, \
635                     which needs cross-origin isolation (COOP/COEP headers; docs/web.md)",
636                ));
637            };
638            match protocol::decode_reply(&reply) {
639                Ok(WReply::Err(m)) => Err(DbError::driver(m)),
640                Ok(r) => Ok(r),
641                Err(_) => Err(DbError::driver("malformed reply from the SQL worker")),
642            }
643        }
644    }
645
646    pub(super) fn unexpected(r: WReply) -> DbError {
647        DbError::driver(format!("unexpected SQL worker reply: {r:?}"))
648    }
649
650    pub(super) fn to_wire(params: &[Value]) -> Vec<WValue> {
651        params
652            .iter()
653            .map(|v| match v {
654                Value::Null => WValue::Null,
655                Value::Int(i) => WValue::Int(*i),
656                Value::Real(r) => WValue::Real(*r),
657                Value::Text(t) => WValue::Text(t.clone()),
658                Value::Blob(b) => WValue::Blob(b.clone()),
659            })
660            .collect()
661    }
662
663    pub(super) fn from_wire(v: WValue) -> Value {
664        match v {
665            WValue::Null => Value::Null,
666            WValue::Int(i) => Value::Int(i),
667            WValue::Real(r) => Value::Real(r),
668            WValue::Text(t) => Value::Text(t),
669            WValue::Blob(b) => Value::Blob(b),
670        }
671    }
672
673    /// The origin's database pool: names in, bytes out, OPFS underneath. The document
674    /// surface a file-per-document app needs on the web: numbering a fresh drawing,
675    /// importing an Open… pick, exporting a download.
676    #[derive(Clone)]
677    pub struct WebStorage;
678
679    impl WebStorage {
680        pub fn exists(&self, name: &str) -> bool {
681            matches!(
682                channel::call(&WReq::Exists {
683                    name: name.to_string()
684                }),
685                Ok(WReply::Bool(true))
686            )
687        }
688
689        /// Every database name in the pool.
690        pub fn list(&self) -> Vec<String> {
691            match channel::call(&WReq::List) {
692                Ok(WReply::Names(names)) => names,
693                _ => Vec::new(),
694            }
695        }
696
697        /// The database's bytes: a plain SQLite file image, downloadable as a file. Flush
698        /// (`ModelContainer::save`) first for an image that includes this turn's edits.
699        pub fn export_db(&self, name: &str) -> Result<Vec<u8>, DbError> {
700            match channel::call(&WReq::Export {
701                name: name.to_string(),
702            })? {
703                WReply::Bytes(b) => Ok(b),
704                other => Err(unexpected(other)),
705            }
706        }
707
708        /// Write a SQLite file image under `name` (an Open… flow's landing). A connection
709        /// still open on that name is stale afterwards; close (drop) it before importing.
710        pub fn import_db(&self, name: &str, bytes: &[u8]) -> Result<(), DbError> {
711            match channel::call(&WReq::Import {
712                name: name.to_string(),
713                bytes: bytes.to_vec(),
714            })? {
715                WReply::Ok => Ok(()),
716                other => Err(unexpected(other)),
717            }
718        }
719
720        pub fn delete_db(&self, name: &str) {
721            let _ = channel::call(&WReq::Delete {
722                name: name.to_string(),
723            });
724        }
725    }
726
727    impl Sqlite {
728        /// The pool surface, when the worker channel is up.
729        pub fn web_storage() -> Result<WebStorage, DbError> {
730            if channel::ready() {
731                Ok(WebStorage)
732            } else {
733                Err(DbError::new(
734                    DbErrorKind::Unsupported,
735                    "no SQL worker — file databases on the web need cross-origin isolation \
736                     (COOP/COEP headers; docs/web.md)",
737                ))
738            }
739        }
740    }
741}
742
743#[cfg(all(target_family = "wasm", target_os = "unknown"))]
744pub use web::WebStorage;