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<TraceCtx>>,
328}
329
330/// What the engine's trace callback carries: the sink, and the statement run it last
331/// reported, so a foreign-key action frame (which arrives as the firing statement again,
332/// with no comment of its own) is not reported as a second execution.
333#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
334struct TraceCtx {
335    f: TraceFn,
336    /// (statement handle, `SQLITE_STMTSTATUS_VM_STEP` count) of the last reported run.
337    last: std::cell::Cell<(usize, i32)>,
338}
339
340/// Install the engine's per-statement trace on a raw connection handle. rusqlite's own
341/// `trace_v2` takes a plain fn pointer, so the closure rides the C-level context instead.
342#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
343fn install_sql_trace(conn: &Connection, f: TraceFn) -> Box<TraceCtx> {
344    use rusqlite::ffi;
345    unsafe extern "C" fn cb(
346        ev: std::ffi::c_uint,
347        ctx: *mut std::ffi::c_void,
348        p: *mut std::ffi::c_void,
349        x: *mut std::ffi::c_void,
350    ) -> std::ffi::c_int {
351        if ev != ffi::SQLITE_TRACE_STMT || ctx.is_null() {
352            return 0;
353        }
354        // SAFETY: ctx is the connection's boxed trace context (returned below and stored on
355        // RusqliteConn), alive until after the connection closes; day's connections are
356        // single-threaded, so the callback never races it.
357        let ctx = unsafe { &*(ctx as *const TraceCtx) };
358        let f = &ctx.f;
359        unsafe {
360            // A trigger frame announces itself as an SQL comment (`-- TRIGGER name`) in `x`,
361            // and `p` is still the statement that fired it: expanding `p` there would report
362            // the firing statement a second time, once per trigger, which read as a row
363            // written twice. The comment is what the engine means, so it is what the sink
364            // gets.
365            let unexpanded = (!x.is_null())
366                .then(|| std::ffi::CStr::from_ptr(x.cast()).to_str().ok())
367                .flatten();
368            if let Some(comment) = unexpanded.filter(|s| s.starts_with("--")) {
369                f(comment);
370                return 0;
371            }
372            // A foreign-key action (`ON DELETE CASCADE`, `SET NULL`) is an unnamed trigger
373            // frame: the engine reports it as the firing statement again, once per parent
374            // row it cascades from, with nothing in `x` to tell it apart. One statement *run* is reported
375            // once. The VM-step counter identifies a run: the engine adds a run's steps to
376            // it only when the run returns, so every frame of one run reads the same value
377            // and the next run of the same cached statement reads a larger one.
378            let run = ffi::sqlite3_stmt_status(p.cast(), ffi::SQLITE_STMTSTATUS_VM_STEP, 0);
379            let this = (p as usize, run);
380            // A statement prepared afresh can land at the address of one just finalized, with
381            // the same zero step count; its run counter is zero too (the engine bumps it after
382            // this callback), which no sub-program frame ever shows.
383            let fresh = ffi::sqlite3_stmt_status(p.cast(), ffi::SQLITE_STMTSTATUS_RUN, 0) == 0;
384            if !fresh && ctx.last.get() == this {
385                f("-- foreign-key action");
386                return 0;
387            }
388            ctx.last.set(this);
389            let expanded = ffi::sqlite3_expanded_sql(p.cast());
390            if !expanded.is_null() {
391                if let Ok(s) = std::ffi::CStr::from_ptr(expanded).to_str() {
392                    f(s);
393                }
394                ffi::sqlite3_free(expanded.cast());
395            } else if let Some(s) = unexpanded {
396                // The engine could not expand (OOM): the unexpanded text.
397                f(s);
398            }
399        }
400        0
401    }
402    let boxed = Box::new(TraceCtx {
403        f,
404        last: std::cell::Cell::new((0, -1)),
405    });
406    let ctx = &*boxed as *const TraceCtx as *mut std::ffi::c_void;
407    // SAFETY: the handle is this connection's own; ctx points into `boxed`, whose heap slot
408    // outlives the connection via RusqliteConn::_trace.
409    unsafe {
410        ffi::sqlite3_trace_v2(conn.handle(), ffi::SQLITE_TRACE_STMT, Some(cb), ctx);
411    }
412    boxed
413}
414
415/// The web connection: in-process for `:memory:`, a worker connection id for files.
416#[cfg(all(target_family = "wasm", target_os = "unknown"))]
417enum WebConn {
418    Memory(day_sqlite_worker::Connection),
419    Remote(u32),
420}
421
422#[cfg(all(target_family = "wasm", target_os = "unknown"))]
423pub struct RusqliteConn {
424    conn: WebConn,
425}
426
427#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
428fn to_sql(v: &Value) -> rusqlite::types::Value {
429    use rusqlite::types::Value as R;
430    match v {
431        Value::Null => R::Null,
432        Value::Int(i) => R::Integer(*i),
433        Value::Real(f) => R::Real(*f),
434        Value::Text(t) => R::Text(t.clone()),
435        Value::Blob(b) => R::Blob(b.clone()),
436    }
437}
438
439#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
440fn from_sql(v: rusqlite::types::ValueRef<'_>) -> Value {
441    use rusqlite::types::ValueRef as R;
442    match v {
443        R::Null => Value::Null,
444        R::Integer(i) => Value::Int(i),
445        R::Real(f) => Value::Real(f),
446        R::Text(t) => Value::Text(String::from_utf8_lossy(t).into_owned()),
447        R::Blob(b) => Value::Blob(b.to_vec()),
448    }
449}
450
451#[cfg(all(target_family = "wasm", target_os = "unknown"))]
452impl SqliteConnection for RusqliteConn {
453    fn execute_batch(&mut self, sql: &str) -> Result<(), DbError> {
454        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
455        match &self.conn {
456            WebConn::Memory(c) => c
457                .execute_batch(sql)
458                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
459            WebConn::Remote(id) => match web::channel::call(&WReq::Batch {
460                conn: *id,
461                sql: sql.to_owned(),
462            })? {
463                WReply::Ok => Ok(()),
464                other => Err(web::unexpected(other)),
465            },
466        }
467    }
468
469    fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, DbError> {
470        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
471        match &self.conn {
472            WebConn::Memory(c) => c
473                .execute(sql, &web::to_wire(params))
474                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
475            WebConn::Remote(id) => match web::channel::call(&WReq::Exec {
476                conn: *id,
477                sql: sql.to_string(),
478                params: web::to_wire(params),
479            })? {
480                WReply::Changes(n) => Ok(n),
481                other => Err(web::unexpected(other)),
482            },
483        }
484    }
485
486    fn query(
487        &mut self,
488        sql: &str,
489        params: &[Value],
490        row: &mut dyn FnMut(&dyn Row),
491    ) -> Result<(), DbError> {
492        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
493        match &self.conn {
494            WebConn::Memory(c) => c
495                .query(sql, &web::to_wire(params), &mut |r| {
496                    let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
497                    row(&vals);
498                })
499                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
500            WebConn::Remote(id) => match web::channel::call(&WReq::Query {
501                conn: *id,
502                sql: sql.to_string(),
503                params: web::to_wire(params),
504            })? {
505                WReply::Rows(rows) => {
506                    for r in rows {
507                        let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
508                        row(&vals);
509                    }
510                    Ok(())
511                }
512                other => Err(web::unexpected(other)),
513            },
514        }
515    }
516    fn query_named(
517        &mut self,
518        sql: &str,
519        params: &[Value],
520        row: &mut dyn FnMut(&[String], &dyn Row),
521    ) -> Result<(), DbError> {
522        use day_sqlite_worker::protocol::{Reply as WReply, Req as WReq};
523        match &self.conn {
524            WebConn::Memory(c) => c
525                .query_named(sql, &web::to_wire(params), &mut |names, r| {
526                    let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
527                    row(names, &vals);
528                })
529                .map(|_| ())
530                .map_err(|e| DbError::driver(format!("{e} in `{sql}`"))),
531            WebConn::Remote(id) => match web::channel::call(&WReq::QueryNamed {
532                conn: *id,
533                sql: sql.to_owned(),
534                params: web::to_wire(params),
535            })? {
536                WReply::NamedRows { names, rows } => {
537                    for r in rows {
538                        let vals: Vec<Value> = r.into_iter().map(web::from_wire).collect();
539                        row(&names, &vals);
540                    }
541                    Ok(())
542                }
543                other => Err(web::unexpected(other)),
544            },
545        }
546    }
547}
548
549/// A dropped remote connection closes its worker side, best effort, like a file handle.
550#[cfg(all(target_family = "wasm", target_os = "unknown"))]
551impl Drop for RusqliteConn {
552    fn drop(&mut self) {
553        if let WebConn::Remote(id) = self.conn {
554            let _ = web::channel::call(&day_sqlite_worker::protocol::Req::Close { conn: id });
555        }
556    }
557}
558
559#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
560impl SqliteConnection for RusqliteConn {
561    fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, DbError> {
562        // Cached, not re-prepared: the fold emits RUNS of identical SQL (one INSERT shape per
563        // table, one DELETE, one UPDATE per changed column set), so a bulk flush would
564        // otherwise re-parse the same statement thousands of times.
565        let mut stmt = self
566            .conn
567            .prepare_cached(sql)
568            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
569        let bound = rusqlite::params_from_iter(params.iter().map(to_sql));
570        stmt.execute(bound)
571            .map(|n| n as u64)
572            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))
573    }
574
575    fn query(
576        &mut self,
577        sql: &str,
578        params: &[Value],
579        row: &mut dyn FnMut(&dyn Row),
580    ) -> Result<(), DbError> {
581        let mut stmt = self
582            .conn
583            .prepare_cached(sql)
584            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
585        let bound = rusqlite::params_from_iter(params.iter().map(to_sql));
586        let mut rows = stmt
587            .query(bound)
588            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
589        loop {
590            match rows.next() {
591                Ok(Some(r)) => {
592                    let n = r.as_ref().column_count();
593                    let vals: Vec<Value> = (0..n)
594                        .map(|i| r.get_ref(i).map(from_sql).unwrap_or(Value::Null))
595                        .collect();
596                    row(&vals);
597                }
598                Ok(None) => break,
599                Err(e) => return Err(DbError::driver(e.to_string())),
600            }
601        }
602        Ok(())
603    }
604
605    fn execute_batch(&mut self, sql: &str) -> Result<(), DbError> {
606        self.conn
607            .execute_batch(sql)
608            .map_err(|e| DbError::driver(format!("{e} in batch")))
609    }
610
611    fn query_named(
612        &mut self,
613        sql: &str,
614        params: &[Value],
615        row: &mut dyn FnMut(&[String], &dyn Row),
616    ) -> Result<(), DbError> {
617        let mut stmt = self
618            .conn
619            .prepare(sql)
620            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
621        let names: Vec<String> = stmt.column_names().iter().map(|s| s.to_string()).collect();
622        let bound = rusqlite::params_from_iter(params.iter().map(to_sql));
623        let mut rows = stmt
624            .query(bound)
625            .map_err(|e| DbError::driver(format!("{e} in `{sql}`")))?;
626        loop {
627            match rows.next() {
628                Ok(Some(r)) => {
629                    let n = r.as_ref().column_count();
630                    let vals: Vec<Value> = (0..n)
631                        .map(|i| r.get_ref(i).map(from_sql).unwrap_or(Value::Null))
632                        .collect();
633                    row(&names, &vals);
634                }
635                Ok(None) => break,
636                Err(e) => return Err(DbError::driver(e.to_string())),
637            }
638        }
639        Ok(())
640    }
641}
642
643// ---------------------------------------------------------------------------
644// The web leg (wasm32-unknown-unknown): the synchronous channel to the day-sql worker.
645//
646// OPFS's only random-access synchronous API (`createSyncAccessHandle`) exists solely in
647// dedicated workers, so the engine runs in day-sqlite-worker's day-sql worker (the same wasm
648// module, instantiated there) and this side is a proxy. Each call encodes one request in
649// day-sqlite-worker's protocol, hands it to that crate's channel, and the main thread blocks
650// the few microseconds until the worker's reply lands back through the SharedArrayBuffer.
651// Fully synchronous from Rust's point of view, fully durable at commit, one code path with
652// every other platform. The channel needs cross-origin isolation (COOP/COEP; `day launch`
653// serves it, see docs/web.md); without it File opens fail loudly and capabilities say
654// durable: false.
655// ---------------------------------------------------------------------------
656
657#[cfg(all(target_family = "wasm", target_os = "unknown"))]
658mod web {
659    use super::*;
660    use day_sqlite_worker::protocol::{self, Reply as WReply, Req as WReq, Value as WValue};
661
662    pub(super) mod channel {
663        use super::*;
664
665        pub(crate) fn ready() -> bool {
666            day_sqlite_worker::channel::ready()
667        }
668
669        /// One round trip. Worker-reported SQL errors come back as [`DbError`]s here, so
670        /// callers only ever match the success variants.
671        pub(crate) fn call(req: &WReq) -> Result<WReply, DbError> {
672            let Some(reply) = day_sqlite_worker::channel::call(&protocol::encode_req(req)) else {
673                return Err(DbError::new(
674                    DbErrorKind::Unsupported,
675                    "no SQL worker — file databases on the web need the day-sql worker, \
676                     which needs cross-origin isolation (COOP/COEP headers; docs/web.md)",
677                ));
678            };
679            match protocol::decode_reply(&reply) {
680                Ok(WReply::Err(m)) => Err(DbError::driver(m)),
681                Ok(r) => Ok(r),
682                Err(_) => Err(DbError::driver("malformed reply from the SQL worker")),
683            }
684        }
685    }
686
687    pub(super) fn unexpected(r: WReply) -> DbError {
688        DbError::driver(format!("unexpected SQL worker reply: {r:?}"))
689    }
690
691    pub(super) fn to_wire(params: &[Value]) -> Vec<WValue> {
692        params
693            .iter()
694            .map(|v| match v {
695                Value::Null => WValue::Null,
696                Value::Int(i) => WValue::Int(*i),
697                Value::Real(r) => WValue::Real(*r),
698                Value::Text(t) => WValue::Text(t.clone()),
699                Value::Blob(b) => WValue::Blob(b.clone()),
700            })
701            .collect()
702    }
703
704    pub(super) fn from_wire(v: WValue) -> Value {
705        match v {
706            WValue::Null => Value::Null,
707            WValue::Int(i) => Value::Int(i),
708            WValue::Real(r) => Value::Real(r),
709            WValue::Text(t) => Value::Text(t),
710            WValue::Blob(b) => Value::Blob(b),
711        }
712    }
713
714    /// The origin's database pool: names in, bytes out, OPFS underneath. The document
715    /// surface a file-per-document app needs on the web: numbering a fresh drawing,
716    /// importing an Open… pick, exporting a download.
717    #[derive(Clone)]
718    pub struct WebStorage;
719
720    impl WebStorage {
721        pub fn exists(&self, name: &str) -> bool {
722            matches!(
723                channel::call(&WReq::Exists {
724                    name: name.to_string()
725                }),
726                Ok(WReply::Bool(true))
727            )
728        }
729
730        /// Every database name in the pool.
731        pub fn list(&self) -> Vec<String> {
732            match channel::call(&WReq::List) {
733                Ok(WReply::Names(names)) => names,
734                _ => Vec::new(),
735            }
736        }
737
738        /// The database's bytes: a plain SQLite file image, downloadable as a file. Flush
739        /// (`ModelContainer::save`) first for an image that includes this turn's edits.
740        pub fn export_db(&self, name: &str) -> Result<Vec<u8>, DbError> {
741            match channel::call(&WReq::Export {
742                name: name.to_string(),
743            })? {
744                WReply::Bytes(b) => Ok(b),
745                other => Err(unexpected(other)),
746            }
747        }
748
749        /// Write a SQLite file image under `name` (an Open… flow's landing). A connection
750        /// still open on that name is stale afterwards; close (drop) it before importing.
751        pub fn import_db(&self, name: &str, bytes: &[u8]) -> Result<(), DbError> {
752            match channel::call(&WReq::Import {
753                name: name.to_string(),
754                bytes: bytes.to_vec(),
755            })? {
756                WReply::Ok => Ok(()),
757                other => Err(unexpected(other)),
758            }
759        }
760
761        pub fn delete_db(&self, name: &str) {
762            let _ = channel::call(&WReq::Delete {
763                name: name.to_string(),
764            });
765        }
766    }
767
768    impl Sqlite {
769        /// The pool surface, when the worker channel is up.
770        pub fn web_storage() -> Result<WebStorage, DbError> {
771            if channel::ready() {
772                Ok(WebStorage)
773            } else {
774                Err(DbError::new(
775                    DbErrorKind::Unsupported,
776                    "no SQL worker — file databases on the web need cross-origin isolation \
777                     (COOP/COEP headers; docs/web.md)",
778                ))
779            }
780        }
781    }
782}
783
784#[cfg(all(target_family = "wasm", target_os = "unknown"))]
785pub use web::WebStorage;