Skip to main content

day_sqlite_worker/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The SQLite engine behind day-persistence on web-dom (docs/persistence.md).
5//!
6//! The vendored amalgamation compiles with no libc and no wasm-bindgen: `vendor/shim` renames
7//! every libc symbol it needs onto the freestanding C subset compiled beside it, and the
8//! handful of Rust-side shims in this file (allocator, UTC localtime, entropy, abort). The
9//! only imports the wasm module gains are `day_sql_*`: time, entropy and a log line, the
10//! three channel calls, and, for the worker instance, the ten `day_sql_fs_*` OPFS primitives.
11//!
12//! The browser half ships with the crate, so nothing in the Day host page knows about SQL.
13//! `[package.metadata.day.web]` (docs/web.md) declares `web/day-sql.js`, a web module the
14//! page imports before it instantiates the app: it supplies those imports and boots
15//! `web/day-sql-worker.js` beside it. The module instantiates in Day's raw-wasm pipeline.
16//!
17//! One wasm, two instantiations. The **app instance** may use [`Connection::open_memory`]
18//! in-process (`:memory:` engines never touch a file) and reaches file databases through
19//! `channel`. The **worker instance** services the `SharedArrayBuffer` channel: the worker
20//! page copies each request into wasm memory and calls [`day_sql_exec`], which runs it
21//! against real OPFS files through the day-opfs VFS and returns the reply bytes. The
22//! [`protocol`] module is the wire format both sides share.
23//!
24//! Everything (VFS, connection layer, worker loop) compiles and unit-tests on native hosts
25//! against an in-memory OPFS fake; only the browser glue is wasm-specific.
26//!
27//! The C tree under `vendor/` and the shim recipe come from sqlite-wasm-rs (MIT, see
28//! `vendor/LICENSE`); SQLite itself is public domain.
29
30#[allow(
31    non_upper_case_globals,
32    non_camel_case_types,
33    non_snake_case,
34    dead_code,
35    improper_ctypes,
36    clippy::all,
37    clippy::pedantic
38)]
39#[rustfmt::skip]
40mod bindings;
41pub mod protocol;
42mod vfs;
43
44use core::ffi::{c_char, c_int, c_long, c_void};
45use std::cell::{Cell, RefCell};
46use std::collections::HashMap;
47
48use bindings as b;
49use protocol::{Reply, Req, Value};
50
51// -------------------------------------------------------------------------------------------
52// Host services: time and entropy
53// -------------------------------------------------------------------------------------------
54
55mod os {
56    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
57    mod imp {
58        #[link(wasm_import_module = "env")]
59        unsafe extern "C" {
60            fn day_sql_now_ms() -> f64;
61            fn day_sql_entropy(buf: *mut u8, len: usize);
62            fn day_sql_log(msg: *const u8, len: usize);
63        }
64        pub fn now_ms() -> f64 {
65            unsafe { day_sql_now_ms() }
66        }
67        pub fn entropy(buf: &mut [u8]) {
68            unsafe { day_sql_entropy(buf.as_mut_ptr(), buf.len()) }
69        }
70        /// A traced statement, to the worker page's console (`[day-sql]` lines in devtools).
71        pub fn log_line(s: &str) {
72            unsafe { day_sql_log(s.as_ptr(), s.len()) }
73        }
74    }
75
76    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
77    mod imp {
78        pub fn now_ms() -> f64 {
79            std::time::SystemTime::now()
80                .duration_since(std::time::UNIX_EPOCH)
81                .map_or(0.0, |d| d.as_millis() as f64)
82        }
83        pub fn log_line(s: &str) {
84            log::warn!("[day-sql] {s}");
85        }
86        pub fn entropy(buf: &mut [u8]) {
87            // SQLite wants seed material, not key material. RandomState is std's OS-seeded
88            // hasher, enough for temp names and PRNG seeding in the native test build.
89            use std::hash::{BuildHasher, Hasher};
90            let state = std::collections::hash_map::RandomState::new();
91            for (i, chunk) in buf.chunks_mut(8).enumerate() {
92                let mut h = state.build_hasher();
93                h.write_usize(i);
94                let bytes = h.finish().to_le_bytes();
95                chunk.copy_from_slice(&bytes[..chunk.len()]);
96            }
97        }
98    }
99
100    pub(crate) use imp::*;
101}
102
103// -------------------------------------------------------------------------------------------
104// The page side of the channel (web/day-sql.js)
105// -------------------------------------------------------------------------------------------
106
107/// The app instance's end of the SharedArrayBuffer channel: one synchronous round trip of
108/// [`protocol`] bytes to the worker instance. Implemented by `web/day-sql.js`, the web module
109/// this crate ships; a driver encodes a [`protocol::Req`], calls, and decodes the reply.
110#[cfg(all(target_family = "wasm", target_os = "unknown"))]
111pub mod channel {
112    #[link(wasm_import_module = "env")]
113    unsafe extern "C" {
114        /// 1 while the day-sql worker is up and the SharedArrayBuffer channel is live.
115        fn day_sql_ready() -> i32;
116        /// Send one request; answers the reply's byte length, or -1 with no channel.
117        fn day_sql_call(req: *const u8, len: usize) -> f64;
118        /// Copy the staged reply (`day_sql_call`'s length) into `dst`.
119        fn day_sql_reply(dst: *mut u8);
120    }
121
122    /// Whether the worker is up. False without cross-origin isolation (COOP/COEP), where the
123    /// page cannot share memory with a worker at all.
124    pub fn ready() -> bool {
125        unsafe { day_sql_ready() == 1 }
126    }
127
128    /// One round trip: the encoded request in, the encoded reply out. `None` when there is no
129    /// channel, or when the worker stopped answering.
130    pub fn call(req: &[u8]) -> Option<Vec<u8>> {
131        let len = unsafe { day_sql_call(req.as_ptr(), req.len()) };
132        if len < 0.0 {
133            return None;
134        }
135        let mut reply = vec![0u8; len as usize];
136        unsafe { day_sql_reply(reply.as_mut_ptr()) };
137        Some(reply)
138    }
139}
140
141// -------------------------------------------------------------------------------------------
142// The C shims (vendor/shim/wasm-shim.h renames; recipe from sqlite-wasm-rs, MIT)
143// -------------------------------------------------------------------------------------------
144
145// dlmalloc's alignment: enough for every SQLite allocation.
146const ALIGN: usize = core::mem::size_of::<usize>() * 2;
147
148/// # Safety
149/// C `malloc` contract; the size is stored ahead of the returned block for `free`/`realloc`.
150#[no_mangle]
151#[expect(
152    clippy::cast_ptr_alignment,
153    reason = "the block comes from the allocator with `ALIGN` alignment"
154)]
155pub unsafe extern "C" fn rust_sqlite_wasm_malloc(size: usize) -> *mut c_void {
156    let layout = core::alloc::Layout::from_size_align_unchecked(size + ALIGN, ALIGN);
157    let ptr = std::alloc::alloc(layout);
158    if ptr.is_null() {
159        return core::ptr::null_mut();
160    }
161    *ptr.cast::<usize>() = size;
162    ptr.add(ALIGN).cast()
163}
164
165/// # Safety
166/// Only pointers from `rust_sqlite_wasm_malloc`/`realloc`.
167#[no_mangle]
168#[expect(
169    clippy::cast_ptr_alignment,
170    reason = "the block comes from the allocator with `ALIGN` alignment"
171)]
172pub unsafe extern "C" fn rust_sqlite_wasm_free(ptr: *mut c_void) {
173    let ptr: *mut u8 = ptr.sub(ALIGN).cast();
174    let size = *(ptr.cast::<usize>());
175    let layout = core::alloc::Layout::from_size_align_unchecked(size + ALIGN, ALIGN);
176    std::alloc::dealloc(ptr, layout);
177}
178
179/// # Safety
180/// Only pointers from `rust_sqlite_wasm_malloc`/`realloc`.
181#[no_mangle]
182#[expect(
183    clippy::cast_ptr_alignment,
184    reason = "the block comes from the allocator with `ALIGN` alignment"
185)]
186pub unsafe extern "C" fn rust_sqlite_wasm_realloc(
187    ptr: *mut c_void,
188    new_size: usize,
189) -> *mut c_void {
190    let ptr: *mut u8 = ptr.sub(ALIGN).cast();
191    let size = *(ptr.cast::<usize>());
192    let layout = core::alloc::Layout::from_size_align_unchecked(size + ALIGN, ALIGN);
193    let ptr = std::alloc::realloc(ptr, layout, new_size + ALIGN);
194    if ptr.is_null() {
195        return core::ptr::null_mut();
196    }
197    *ptr.cast::<usize>() = new_size;
198    ptr.add(ALIGN).cast()
199}
200
201/// # Safety
202/// C `calloc` contract.
203#[no_mangle]
204pub unsafe extern "C" fn rust_sqlite_wasm_calloc(num: usize, size: usize) -> *mut c_void {
205    let Some(total) = num.checked_mul(size) else {
206        return core::ptr::null_mut();
207    };
208    let ptr: *mut u8 = rust_sqlite_wasm_malloc(total).cast();
209    if !ptr.is_null() {
210        core::ptr::write_bytes(ptr, 0, total);
211    }
212    ptr.cast()
213}
214
215/// # Safety
216/// wasi `getentropy` contract: fills `buf_len` bytes.
217#[no_mangle]
218pub unsafe extern "C" fn rust_sqlite_wasm_getentropy(buf: *mut u8, buf_len: usize) -> u16 {
219    os::entropy(core::slice::from_raw_parts_mut(buf, buf_len));
220    0
221}
222
223/// # Safety
224/// C `__assert_fail` contract; an assertion in the C tree is a bug worth stopping on.
225///
226/// # Panics
227/// Always: it reports the failed assertion.
228#[no_mangle]
229pub unsafe extern "C" fn rust_sqlite_wasm_assert_fail(
230    expr: *const c_char,
231    file: *const c_char,
232    line: c_int,
233    _func: *const c_char,
234) {
235    let expr = core::ffi::CStr::from_ptr(expr).to_string_lossy();
236    let file = core::ffi::CStr::from_ptr(file).to_string_lossy();
237    panic!("sqlite assertion failed: {expr} ({file}:{line})");
238}
239
240/// # Safety
241/// C `abort` contract.
242#[no_mangle]
243pub unsafe extern "C" fn rust_sqlite_wasm_abort() -> ! {
244    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
245    core::arch::wasm32::unreachable();
246    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
247    std::process::abort();
248}
249
250/// musl's `struct tm` (what `<time.h>` in the vendored headers declares).
251#[repr(C)]
252#[expect(
253    clippy::struct_field_names,
254    reason = "the fields carry the names of C `struct tm`"
255)]
256pub struct Tm {
257    tm_sec: c_int,
258    tm_min: c_int,
259    tm_hour: c_int,
260    tm_mday: c_int,
261    tm_mon: c_int,
262    tm_year: c_int,
263    tm_wday: c_int,
264    tm_yday: c_int,
265    tm_isdst: c_int,
266    tm_gmtoff: c_long,
267    tm_zone: *mut c_char,
268}
269
270/// UTC civil breakdown for `t` (Howard Hinnant's `civil_from_days`). No timezone database
271/// exists in the browser sandbox, so SQLite's `'localtime'` modifier resolves to UTC here;
272/// apps that need the viewer's zone format in the UI layer, where the platform knows it.
273fn utc_breakdown(t: i64) -> Tm {
274    const CUM: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
275    let days = t.div_euclid(86_400);
276    let secs = t.rem_euclid(86_400);
277    let z = days + 719_468;
278    let era = z.div_euclid(146_097);
279    let doe = z - era * 146_097;
280    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
281    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
282    let mp = (5 * doy + 2) / 153;
283    let d = doy - (153 * mp + 2) / 5 + 1;
284    let m = if mp < 10 { mp + 3 } else { mp - 9 };
285    let y = yoe + era * 400 + i64::from(m <= 2);
286    let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
287    let yday = CUM[(m - 1) as usize] + i64::from(leap && m > 2) + d - 1;
288    Tm {
289        tm_sec: (secs % 60) as c_int,
290        tm_min: ((secs / 60) % 60) as c_int,
291        tm_hour: (secs / 3600) as c_int,
292        tm_mday: d as c_int,
293        tm_mon: (m - 1) as c_int,
294        tm_year: (y - 1900) as c_int,
295        tm_wday: (days + 4).rem_euclid(7) as c_int,
296        tm_yday: yday as c_int,
297        tm_isdst: 0,
298        tm_gmtoff: 0,
299        tm_zone: core::ptr::null_mut(),
300    }
301}
302
303/// # Safety
304/// C `localtime` contract: returns a shared static buffer, single-threaded callers only,
305/// which this engine is by construction (`SQLITE_THREADSAFE=0`).
306#[no_mangle]
307pub unsafe extern "C" fn rust_sqlite_wasm_localtime(t: *const i64) -> *mut Tm {
308    static mut TM: Tm = Tm {
309        tm_sec: 0,
310        tm_min: 0,
311        tm_hour: 0,
312        tm_mday: 0,
313        tm_mon: 0,
314        tm_year: 0,
315        tm_wday: 0,
316        tm_yday: 0,
317        tm_isdst: 0,
318        tm_gmtoff: 0,
319        tm_zone: core::ptr::null_mut(),
320    };
321    let tm = core::ptr::addr_of_mut!(TM);
322    *tm = utc_breakdown(*t);
323    tm
324}
325
326/// # Safety
327/// Called once by `sqlite3_initialize` (`SQLITE_OS_OTHER` contract): registers day-mem
328/// (default) and day-opfs.
329#[no_mangle]
330pub unsafe extern "C" fn sqlite3_os_init() -> c_int {
331    vfs::register_all()
332}
333
334/// # Safety
335/// `sqlite3_shutdown` counterpart; nothing to unwind.
336#[no_mangle]
337pub unsafe extern "C" fn sqlite3_os_end() -> c_int {
338    b::SQLITE_OK
339}
340
341// -------------------------------------------------------------------------------------------
342// The connection layer
343// -------------------------------------------------------------------------------------------
344
345/// An engine failure: SQLite's result code and its message.
346#[derive(Clone, Debug, PartialEq)]
347pub struct SqlError {
348    pub code: i32,
349    pub message: String,
350}
351
352impl std::fmt::Display for SqlError {
353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354        write!(f, "{} (sqlite code {})", self.message, self.code)
355    }
356}
357
358impl std::error::Error for SqlError {}
359
360fn err(code: c_int, message: impl Into<String>) -> SqlError {
361    SqlError {
362        code,
363        message: message.into(),
364    }
365}
366
367/// One open database. `open_memory` works in any instance (no file I/O at all);
368/// `open_opfs` routes through the day-opfs VFS and is the worker's shape.
369/// A statement-trace sink (`Connection::trace_stmt`).
370pub type TraceFn = Box<dyn Fn(&str)>;
371
372pub struct Connection {
373    db: *mut b::sqlite3,
374    /// The installed statement-trace closure (`trace_stmt`), heap-boxed so the pointer the
375    /// engine holds stays put while the Connection moves; dropped after `db` closes.
376    trace: Option<Box<TraceFn>>,
377}
378
379unsafe extern "C" fn sql_trace_cb(
380    ev: core::ffi::c_uint,
381    ctx: *mut core::ffi::c_void,
382    p: *mut core::ffi::c_void,
383    x: *mut core::ffi::c_void,
384) -> c_int {
385    if ev != b::SQLITE_TRACE_STMT || ctx.is_null() {
386        return 0;
387    }
388    // SAFETY: ctx is the connection's boxed trace closure, alive until after sqlite3_close
389    // (field order in Connection); SQLITE_THREADSAFE=0 means no concurrent invocation.
390    let f = unsafe { &*(ctx as *const TraceFn) };
391    unsafe {
392        let expanded = b::sqlite3_expanded_sql(p.cast());
393        if !expanded.is_null() {
394            if let Ok(s) = core::ffi::CStr::from_ptr(expanded).to_str() {
395                f(s);
396            }
397            b::sqlite3_free(expanded.cast());
398        } else if !x.is_null() {
399            // The engine could not expand (OOM, or a trigger frame): the unexpanded text.
400            if let Ok(s) = core::ffi::CStr::from_ptr(x.cast()).to_str() {
401                f(s);
402            }
403        }
404    }
405    0
406}
407
408impl Connection {
409    fn open_with(path: &str, vfs: Option<&core::ffi::CStr>) -> Result<Connection, SqlError> {
410        let path = std::ffi::CString::new(path).map_err(|_| err(1, "NUL in database name"))?;
411        let mut db: *mut b::sqlite3 = core::ptr::null_mut();
412        let flags = b::SQLITE_OPEN_READWRITE | b::SQLITE_OPEN_CREATE;
413        let rc = unsafe {
414            b::sqlite3_open_v2(
415                path.as_ptr(),
416                &raw mut db,
417                flags,
418                vfs.map_or(core::ptr::null(), std::ffi::CStr::as_ptr),
419            )
420        };
421        if rc != b::SQLITE_OK {
422            let message = if db.is_null() {
423                "out of memory opening database".to_string()
424            } else {
425                let m = unsafe { errmsg(db) };
426                unsafe { b::sqlite3_close(db) };
427                m
428            };
429            return Err(err(rc, message));
430        }
431        Ok(Connection { db, trace: None })
432    }
433
434    /// Install the engine's per-statement trace (`sqlite3_trace_v2`, `SQLITE_TRACE_STMT)`: `f`
435    /// sees every statement this connection executes, with bound parameters expanded.
436    pub fn trace_stmt(&mut self, f: TraceFn) {
437        let boxed: Box<TraceFn> = Box::new(f);
438        let ctx = &raw const *boxed as *mut core::ffi::c_void;
439        // SAFETY: ctx points into `boxed`, stored on self below, so it is stable while the
440        // engine holds it, and cleared implicitly when the connection closes.
441        unsafe {
442            b::sqlite3_trace_v2(self.db, b::SQLITE_TRACE_STMT, Some(sql_trace_cb), ctx);
443        }
444        self.trace = Some(boxed);
445    }
446
447    /// A private in-memory database, the only kind the main-thread app instance may open.
448    ///
449    /// # Errors
450    /// Returns the engine error when the database cannot be opened.
451    pub fn open_memory() -> Result<Connection, SqlError> {
452        Self::open_with(":memory:", None)
453    }
454
455    /// A named database through the day-opfs VFS (real OPFS in the worker, the in-memory
456    /// fake in native tests).
457    ///
458    /// # Errors
459    /// Returns the engine error when the database cannot be opened.
460    pub fn open_opfs(name: &str) -> Result<Connection, SqlError> {
461        Self::open_with(name, Some(vfs::OPFS_VFS))
462    }
463
464    /// Run semicolon-separated statements with no parameters and no rows.
465    ///
466    /// # Errors
467    /// Returns the engine error of the first statement that fails to prepare or run.
468    pub fn execute_batch(&self, sql: &str) -> Result<(), SqlError> {
469        let mut rest = sql.as_bytes();
470        while !rest.is_empty() {
471            let (stmt, tail) = self.prepare(rest)?;
472            let Some(stmt) = stmt else {
473                rest = tail;
474                continue; // whitespace / comments
475            };
476            let rc = loop {
477                match unsafe { b::sqlite3_step(stmt.0) } {
478                    b::SQLITE_ROW => {}
479                    code => break code,
480                }
481            };
482            if rc != b::SQLITE_DONE {
483                return Err(err(rc, unsafe { errmsg(self.db) }));
484            }
485            drop(stmt);
486            rest = tail;
487        }
488        Ok(())
489    }
490
491    /// Run one statement; the count of changed rows comes back.
492    ///
493    /// # Errors
494    /// Returns the engine error when the statement is empty, or fails to prepare, bind or run.
495    pub fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, SqlError> {
496        let (stmt, _) = self.prepare(sql.as_bytes())?;
497        let stmt = stmt.ok_or_else(|| err(1, "empty statement"))?;
498        self.bind(&stmt, params)?;
499        match unsafe { b::sqlite3_step(stmt.0) } {
500            b::SQLITE_DONE | b::SQLITE_ROW => Ok(unsafe { b::sqlite3_changes(self.db) } as u64),
501            rc => Err(err(rc, unsafe { errmsg(self.db) })),
502        }
503    }
504
505    /// Run one statement, delivering each row to `f`.
506    ///
507    /// # Errors
508    /// Returns the engine error when the statement is empty, or fails to prepare, bind or run.
509    pub fn query(
510        &self,
511        sql: &str,
512        params: &[Value],
513        f: &mut dyn FnMut(Vec<Value>),
514    ) -> Result<(), SqlError> {
515        self.query_impl(sql, params, false, &mut |_, row| f(row))
516            .map(|_| ())
517    }
518
519    /// Query with result column names, including aliases. Names are returned even for no rows.
520    ///
521    /// # Errors
522    /// Returns the engine error when the statement is empty, or fails to prepare, bind or run.
523    pub fn query_named(
524        &self,
525        sql: &str,
526        params: &[Value],
527        f: &mut dyn FnMut(&[String], Vec<Value>),
528    ) -> Result<Vec<String>, SqlError> {
529        self.query_impl(sql, params, true, f)
530    }
531
532    fn query_impl(
533        &self,
534        sql: &str,
535        params: &[Value],
536        named: bool,
537        f: &mut dyn FnMut(&[String], Vec<Value>),
538    ) -> Result<Vec<String>, SqlError> {
539        let (stmt, _) = self.prepare(sql.as_bytes())?;
540        let stmt = stmt.ok_or_else(|| err(1, "empty statement"))?;
541        self.bind(&stmt, params)?;
542        // Step before reading metadata: SQLite may automatically reprepare on schema changes.
543        let mut rc = unsafe { b::sqlite3_step(stmt.0) };
544        let n = unsafe { b::sqlite3_column_count(stmt.0) };
545        let names = if named {
546            (0..n)
547                .map(|i| {
548                    let ptr = unsafe { b::sqlite3_column_name(stmt.0, i) };
549                    if ptr.is_null() {
550                        Err(err(
551                            b::SQLITE_NOMEM,
552                            "SQLite could not allocate a column name",
553                        ))
554                    } else {
555                        Ok(unsafe { core::ffi::CStr::from_ptr(ptr) }
556                            .to_string_lossy()
557                            .into_owned())
558                    }
559                })
560                .collect::<Result<Vec<_>, _>>()?
561        } else {
562            Vec::new()
563        };
564        loop {
565            match rc {
566                b::SQLITE_ROW => {
567                    let mut row = Vec::with_capacity(n as usize);
568                    for i in 0..n {
569                        row.push(unsafe { column_value(stmt.0, i) });
570                    }
571                    f(&names, row);
572                }
573                b::SQLITE_DONE => return Ok(names),
574                rc => return Err(err(rc, unsafe { errmsg(self.db) })),
575            }
576            rc = unsafe { b::sqlite3_step(stmt.0) };
577        }
578    }
579
580    fn prepare<'a>(&self, sql: &'a [u8]) -> Result<(Option<Stmt>, &'a [u8]), SqlError> {
581        let mut stmt: *mut b::sqlite3_stmt = core::ptr::null_mut();
582        let mut tail: *const c_char = core::ptr::null();
583        let rc = unsafe {
584            b::sqlite3_prepare_v2(
585                self.db,
586                sql.as_ptr().cast(),
587                sql.len() as c_int,
588                &raw mut stmt,
589                &raw mut tail,
590            )
591        };
592        if rc != b::SQLITE_OK {
593            return Err(err(rc, unsafe { errmsg(self.db) }));
594        }
595        let consumed = if tail.is_null() {
596            sql.len()
597        } else {
598            unsafe { tail.offset_from(sql.as_ptr().cast()) as usize }
599        };
600        Ok((
601            (!stmt.is_null()).then_some(Stmt(stmt)),
602            &sql[consumed.min(sql.len())..],
603        ))
604    }
605
606    fn bind(&self, stmt: &Stmt, params: &[Value]) -> Result<(), SqlError> {
607        // SQLITE_TRANSIENT: SQLite copies the buffer before the call returns.
608        let transient: b::sqlite3_destructor_type = unsafe { core::mem::transmute(-1isize) };
609        for (i, v) in params.iter().enumerate() {
610            let i = i as c_int + 1;
611            let rc = unsafe {
612                match v {
613                    Value::Null => b::sqlite3_bind_null(stmt.0, i),
614                    Value::Int(n) => b::sqlite3_bind_int64(stmt.0, i, *n),
615                    Value::Real(r) => b::sqlite3_bind_double(stmt.0, i, *r),
616                    Value::Text(t) => b::sqlite3_bind_text(
617                        stmt.0,
618                        i,
619                        t.as_ptr().cast(),
620                        t.len() as c_int,
621                        transient,
622                    ),
623                    Value::Blob(bl) => b::sqlite3_bind_blob(
624                        stmt.0,
625                        i,
626                        bl.as_ptr().cast(),
627                        bl.len() as c_int,
628                        transient,
629                    ),
630                }
631            };
632            if rc != b::SQLITE_OK {
633                return Err(err(rc, unsafe { errmsg(self.db) }));
634            }
635        }
636        Ok(())
637    }
638}
639
640impl Drop for Connection {
641    fn drop(&mut self) {
642        unsafe { b::sqlite3_close(self.db) };
643    }
644}
645
646/// Finalized on drop, so every prepare path cleans up.
647struct Stmt(*mut b::sqlite3_stmt);
648
649impl Drop for Stmt {
650    fn drop(&mut self) {
651        unsafe { b::sqlite3_finalize(self.0) };
652    }
653}
654
655unsafe fn errmsg(db: *mut b::sqlite3) -> String {
656    let p = b::sqlite3_errmsg(db);
657    if p.is_null() {
658        "unknown sqlite error".to_string()
659    } else {
660        core::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
661    }
662}
663
664unsafe fn column_value(stmt: *mut b::sqlite3_stmt, i: c_int) -> Value {
665    match b::sqlite3_column_type(stmt, i) {
666        b::SQLITE_INTEGER => Value::Int(b::sqlite3_column_int64(stmt, i)),
667        b::SQLITE_FLOAT => Value::Real(b::sqlite3_column_double(stmt, i)),
668        b::SQLITE_TEXT => {
669            let p = b::sqlite3_column_text(stmt, i);
670            let n = b::sqlite3_column_bytes(stmt, i) as usize;
671            let bytes = if p.is_null() {
672                &[][..]
673            } else {
674                core::slice::from_raw_parts(p, n)
675            };
676            Value::Text(String::from_utf8_lossy(bytes).into_owned())
677        }
678        b::SQLITE_BLOB => {
679            let p = b::sqlite3_column_blob(stmt, i);
680            let n = b::sqlite3_column_bytes(stmt, i) as usize;
681            let bytes = if p.is_null() {
682                &[][..]
683            } else {
684                core::slice::from_raw_parts(p.cast::<u8>(), n)
685            };
686            Value::Blob(bytes.to_vec())
687        }
688        _ => Value::Null,
689    }
690}
691
692// -------------------------------------------------------------------------------------------
693// The worker loop
694// -------------------------------------------------------------------------------------------
695
696thread_local! {
697    static CONNS: RefCell<HashMap<u32, Connection>> = RefCell::new(HashMap::new());
698    static NEXT_CONN: Cell<u32> = const { Cell::new(1) };
699    /// The staged reply `day_sql_exec` hands the worker page: `[len: u32 LE][bytes]`. Lives
700    /// until the next request; the channel is strictly one request at a time.
701    static REPLY: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
702}
703
704/// Service one request: the worker loop's whole body, and the entry point the native tests
705/// drive.
706pub fn handle_request(req: &[u8]) -> Vec<u8> {
707    let reply = match protocol::decode_req(req) {
708        Err(_) => Reply::Err("malformed request".to_string()),
709        Ok(req) => dispatch(req),
710    };
711    protocol::encode_reply(&reply)
712}
713
714fn dispatch(req: Req) -> Reply {
715    match req {
716        Req::Open { name, trace } => match Connection::open_opfs(&name) {
717            Ok(mut conn) => {
718                if trace {
719                    conn.trace_stmt(Box::new(os::log_line));
720                }
721                let id = NEXT_CONN.with(|n| {
722                    let id = n.get();
723                    n.set(id.wrapping_add(1).max(1));
724                    id
725                });
726                CONNS.with(|c| c.borrow_mut().insert(id, conn));
727                Reply::Conn(id)
728            }
729            Err(e) => Reply::Err(e.to_string()),
730        },
731        Req::Close { conn } => {
732            CONNS.with(|c| c.borrow_mut().remove(&conn));
733            Reply::Ok
734        }
735        Req::Batch { conn, sql } => with_conn(conn, |c| c.execute_batch(&sql).map(|()| Reply::Ok)),
736        Req::Exec { conn, sql, params } => {
737            with_conn(conn, |c| c.execute(&sql, &params).map(Reply::Changes))
738        }
739        Req::Query { conn, sql, params } => with_conn(conn, |c| {
740            let mut rows = Vec::new();
741            c.query(&sql, &params, &mut |row| rows.push(row))
742                .map(|()| Reply::Rows(rows))
743        }),
744        Req::QueryNamed { conn, sql, params } => with_conn(conn, |c| {
745            let mut rows = Vec::new();
746            c.query_named(&sql, &params, &mut |_, row| rows.push(row))
747                .map(|names| Reply::NamedRows { names, rows })
748        }),
749        Req::Exists { name } => Reply::Bool(vfs::fsx::exists(&name)),
750        Req::List => Reply::Names(vfs::fsx::list()),
751        Req::Delete { name } => {
752            vfs::fsx::delete(&name);
753            Reply::Ok
754        }
755        Req::Export { name } => match vfs::fsx::read_all(&name) {
756            Some(bytes) => Reply::Bytes(bytes),
757            None => Reply::Err(format!("no database named {name:?}")),
758        },
759        Req::Import { name, bytes } => {
760            if vfs::fsx::write_all(&name, &bytes) {
761                Reply::Ok
762            } else {
763                Reply::Err(format!("could not write {name:?}"))
764            }
765        }
766    }
767}
768
769fn with_conn(id: u32, f: impl FnOnce(&Connection) -> Result<Reply, SqlError>) -> Reply {
770    CONNS.with(|c| {
771        // Take the connection out for the call: statement callbacks must not find the
772        // registry borrowed.
773        let Some(conn) = c.borrow_mut().remove(&id) else {
774            return Reply::Err(format!("no connection {id}"));
775        };
776        let reply = match f(&conn) {
777            Ok(r) => r,
778            Err(e) => Reply::Err(e.to_string()),
779        };
780        c.borrow_mut().insert(id, conn);
781        reply
782    })
783}
784
785/// Allocate `len` bytes for the worker page to write a request into (consumed by
786/// [`day_sql_exec`]).
787#[no_mangle]
788pub extern "C" fn day_sql_alloc(len: usize) -> *mut u8 {
789    let mut v = Vec::<u8>::with_capacity(len);
790    let ptr = v.as_mut_ptr();
791    core::mem::forget(v);
792    ptr
793}
794
795/// # Safety
796/// `ptr` must be a `day_sql_alloc(len)` buffer holding a complete request; ownership
797/// transfers here. Returns a pointer to `[reply_len: u32 LE][reply bytes]`, valid until the
798/// next call.
799#[no_mangle]
800#[expect(
801    clippy::same_length_and_capacity,
802    reason = "`day_sql_alloc(len)` allocates exactly `len` bytes, which the page then fills"
803)]
804pub unsafe extern "C" fn day_sql_exec(ptr: *mut u8, len: usize) -> *const u8 {
805    let req = Vec::from_raw_parts(ptr, len, len);
806    let reply = handle_request(&req);
807    REPLY.with(|r| {
808        let mut r = r.borrow_mut();
809        r.clear();
810        r.extend_from_slice(&(reply.len() as u32).to_le_bytes());
811        r.extend_from_slice(&reply);
812        r.as_ptr()
813    })
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819
820    /// The engine is compiled `SQLITE_THREADSAFE=0`, correct for the single-threaded worker,
821    /// but the test harness runs on parallel threads, and concurrent first-opens race
822    /// `sqlite3_initialize`'s unsynchronized VFS registration (a test then nondeterministically
823    /// fails with "no such vfs: day-opfs"; first caught on the Linux CI leg). Every test takes
824    /// this lock so the engine is only ever entered from one thread at a time, matching the
825    /// worker's contract. Poisoning is ignored: one failing test must not cascade.
826    static ENGINE: std::sync::Mutex<()> = std::sync::Mutex::new(());
827
828    fn engine() -> std::sync::MutexGuard<'static, ()> {
829        ENGINE
830            .lock()
831            .unwrap_or_else(std::sync::PoisonError::into_inner)
832    }
833
834    #[expect(
835        clippy::needless_pass_by_value,
836        reason = "every test builds its request in the call"
837    )]
838    fn ask(req: Req) -> Reply {
839        protocol::decode_reply(&handle_request(&protocol::encode_req(&req))).expect("well-formed")
840    }
841
842    fn open(name: &str) -> u32 {
843        match ask(Req::Open {
844            name: name.into(),
845            trace: false,
846        }) {
847            Reply::Conn(id) => id,
848            other => panic!("open {name}: {other:?}"),
849        }
850    }
851
852    #[test]
853    fn memory_connection_round_trips_every_value_kind() {
854        let _engine = engine();
855        let conn = Connection::open_memory().expect("open");
856        conn.execute_batch("CREATE TABLE t (a, b, c, d, e)")
857            .expect("create");
858        let params = vec![
859            Value::Null,
860            Value::Int(i64::MIN),
861            Value::Real(2.5),
862            Value::Text("héllo — quote' and \u{1f}".into()),
863            Value::Blob(vec![0, 1, 255, 0]),
864        ];
865        let n = conn
866            .execute("INSERT INTO t VALUES (?, ?, ?, ?, ?)", &params)
867            .expect("insert");
868        assert_eq!(n, 1);
869        let mut rows = Vec::new();
870        conn.query("SELECT a, b, c, d, e FROM t", &[], &mut |r| rows.push(r))
871            .expect("select");
872        assert_eq!(rows, vec![params]);
873    }
874
875    #[test]
876    fn batch_runs_multiple_statements_and_reports_the_failing_one() {
877        let _engine = engine();
878        let conn = Connection::open_memory().expect("open");
879        conn.execute_batch(
880            "CREATE TABLE a (x); -- comment\nCREATE TABLE b (y);\nINSERT INTO a VALUES (1);",
881        )
882        .expect("batch");
883        let mut count = Vec::new();
884        conn.query("SELECT count(*) FROM a", &[], &mut |r| count.push(r))
885            .expect("count");
886        assert_eq!(count, vec![vec![Value::Int(1)]]);
887
888        let e = conn
889            .execute_batch("INSERT INTO a VALUES (2); INSERT INTO nope VALUES (3);")
890            .expect_err("second statement is bad");
891        assert!(e.message.contains("nope"), "{e}");
892    }
893
894    #[test]
895    fn transactions_roll_back() {
896        let _engine = engine();
897        let conn = Connection::open_memory().expect("open");
898        conn.execute_batch("CREATE TABLE t (x); BEGIN; INSERT INTO t VALUES (1); ROLLBACK;")
899            .expect("batch");
900        let mut n = Vec::new();
901        conn.query("SELECT count(*) FROM t", &[], &mut |r| n.push(r))
902            .expect("count");
903        assert_eq!(n, vec![vec![Value::Int(0)]]);
904    }
905
906    #[test]
907    fn fts5_and_rtree_are_compiled_in() {
908        let _engine = engine();
909        let conn = Connection::open_memory().expect("open");
910        conn.execute_batch(
911            "CREATE VIRTUAL TABLE ft USING fts5(body);\
912             CREATE VIRTUAL TABLE geo USING rtree(id, minx, maxx, miny, maxy);",
913        )
914        .expect("both engines present");
915        conn.execute(
916            "INSERT INTO ft VALUES (?)",
917            &[Value::Text("golden harbor light".into())],
918        )
919        .expect("insert");
920        let mut hits = Vec::new();
921        conn.query(
922            "SELECT count(*) FROM ft WHERE ft MATCH ?",
923            &[Value::Text("harbor".into())],
924            &mut |r| hits.push(r),
925        )
926        .expect("match");
927        assert_eq!(hits, vec![vec![Value::Int(1)]]);
928    }
929
930    #[test]
931    fn dates_work_without_a_timezone_database() {
932        let _engine = engine();
933        let conn = Connection::open_memory().expect("open");
934        let mut out = Vec::new();
935        conn.query(
936            "SELECT datetime(0, 'unixepoch'), date('now'), datetime(86400, 'unixepoch', 'localtime')",
937            &[],
938            &mut |r| out.push(r),
939        )
940        .expect("dates");
941        let row = &out[0];
942        assert_eq!(row[0], Value::Text("1970-01-01 00:00:00".into()));
943        let Value::Text(today) = &row[1] else {
944            panic!("date('now'): {row:?}")
945        };
946        assert!(today.starts_with("20"), "sane current year: {today}");
947        // 'localtime' is UTC here (no tz database in the sandbox).
948        assert_eq!(row[2], Value::Text("1970-01-02 00:00:00".into()));
949    }
950
951    #[test]
952    fn utc_breakdown_matches_known_dates() {
953        let _engine = engine();
954        let tm = utc_breakdown(1_787_616_000); // 2026-08-25 00:00:00 UTC, a Tuesday
955        assert_eq!(
956            (tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_wday, tm.tm_yday),
957            (126, 7, 25, 2, 236)
958        );
959        let tm = utc_breakdown(0);
960        assert_eq!(
961            (tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_wday, tm.tm_yday),
962            (70, 0, 1, 4, 0)
963        );
964        // Leap-year boundary: 2024-12-31 is yday 365.
965        let tm = utc_breakdown(1_735_603_200);
966        assert_eq!(
967            (tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_yday),
968            (124, 11, 31, 365)
969        );
970    }
971
972    #[test]
973    fn opfs_database_persists_across_close_and_reopen() {
974        let _engine = engine();
975        let conn = Connection::open_opfs("persist.db").expect("open");
976        conn.execute_batch("CREATE TABLE t (x)").expect("create");
977        for i in 0..100 {
978            conn.execute("INSERT INTO t VALUES (?)", &[Value::Int(i)])
979                .expect("insert");
980        }
981        drop(conn);
982
983        let conn = Connection::open_opfs("persist.db").expect("reopen");
984        let mut n = Vec::new();
985        conn.query("SELECT count(*), sum(x) FROM t", &[], &mut |r| n.push(r))
986            .expect("count");
987        assert_eq!(n, vec![vec![Value::Int(100), Value::Int(4950)]]);
988        drop(conn);
989        vfs::fsx::delete("persist.db");
990    }
991
992    #[test]
993    fn commits_leave_no_journal_behind() {
994        let _engine = engine();
995        let conn = Connection::open_opfs("clean.db").expect("open");
996        conn.execute_batch("CREATE TABLE t (x); BEGIN; INSERT INTO t VALUES (1); COMMIT;")
997            .expect("batch");
998        drop(conn);
999        let names = vfs::fsx::list();
1000        assert!(
1001            names.iter().any(|n| n == "clean.db"),
1002            "database listed: {names:?}"
1003        );
1004        assert!(
1005            !names.iter().any(|n| n.contains("journal")),
1006            "journal deleted after commit: {names:?}"
1007        );
1008        vfs::fsx::delete("clean.db");
1009    }
1010
1011    #[test]
1012    fn worker_batch_migration_is_atomic_and_survives_reopen() {
1013        let _engine = engine();
1014        let conn = open("migration.db");
1015        assert_eq!(ask(Req::Batch { conn, sql: "CREATE TABLE old_books(id TEXT PRIMARY KEY, title TEXT); INSERT INTO old_books VALUES ('fixture', 'Preserved');".into() }), Reply::Ok);
1016        assert_eq!(
1017            ask(Req::Exec {
1018                conn,
1019                sql: "BEGIN".into(),
1020                params: vec![]
1021            }),
1022            Reply::Changes(1)
1023        );
1024        let failed = ask(Req::Batch {
1025            conn,
1026            sql: "ALTER TABLE old_books RENAME TO books; INSERT INTO missing VALUES (1);".into(),
1027        });
1028        std::assert_matches!(failed, Reply::Err(_));
1029        std::assert_matches!(
1030            ask(Req::Exec {
1031                conn,
1032                sql: "ROLLBACK".into(),
1033                params: vec![]
1034            }),
1035            Reply::Changes(_)
1036        );
1037        assert_eq!(
1038            ask(Req::Query {
1039                conn,
1040                sql: "SELECT title FROM old_books".into(),
1041                params: vec![]
1042            }),
1043            Reply::Rows(vec![vec![Value::Text("Preserved".into())]])
1044        );
1045        assert_eq!(ask(Req::Batch { conn, sql: "BEGIN; CREATE TABLE books(id TEXT PRIMARY KEY, title TEXT, opened INTEGER NOT NULL DEFAULT 0); INSERT INTO books(id, title) SELECT id, title FROM old_books; DROP TABLE old_books; COMMIT;".into() }), Reply::Ok);
1046        assert_eq!(ask(Req::Close { conn }), Reply::Ok);
1047        let conn = open("migration.db");
1048        assert_eq!(
1049            ask(Req::Query {
1050                conn,
1051                sql: "SELECT id, title, opened FROM books".into(),
1052                params: vec![]
1053            }),
1054            Reply::Rows(vec![vec![
1055                Value::Text("fixture".into()),
1056                Value::Text("Preserved".into()),
1057                Value::Int(0)
1058            ]])
1059        );
1060        assert_eq!(ask(Req::Close { conn }), Reply::Ok);
1061        vfs::fsx::delete("migration.db");
1062    }
1063
1064    #[test]
1065    fn worker_protocol_full_round_trip() {
1066        let _engine = engine();
1067        let conn = open("proto.db");
1068        assert_eq!(
1069            ask(Req::Batch {
1070                conn,
1071                sql: "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)".into()
1072            }),
1073            Reply::Ok
1074        );
1075        assert_eq!(
1076            ask(Req::Exec {
1077                conn,
1078                sql: "INSERT INTO notes (id, body) VALUES (?, ?)".into(),
1079                params: vec![Value::Int(1), Value::Text("rain later".into())],
1080            }),
1081            Reply::Changes(1)
1082        );
1083        assert_eq!(
1084            ask(Req::Query {
1085                conn,
1086                sql: "SELECT id, body FROM notes".into(),
1087                params: vec![],
1088            }),
1089            Reply::Rows(vec![vec![Value::Int(1), Value::Text("rain later".into())]])
1090        );
1091        assert_eq!(
1092            ask(Req::QueryNamed {
1093                conn,
1094                sql: "SELECT id AS key, body AS title FROM notes WHERE id=?".into(),
1095                params: vec![Value::Int(1)]
1096            }),
1097            Reply::NamedRows {
1098                names: vec!["key".into(), "title".into()],
1099                rows: vec![vec![Value::Int(1), Value::Text("rain later".into())]]
1100            }
1101        );
1102        assert_eq!(
1103            ask(Req::QueryNamed {
1104                conn,
1105                sql: "SELECT body AS title FROM notes WHERE id=?".into(),
1106                params: vec![Value::Int(99)]
1107            }),
1108            Reply::NamedRows {
1109                names: vec!["title".into()],
1110                rows: vec![]
1111            }
1112        );
1113        // Errors carry SQLite's message, and the connection survives them.
1114        let Reply::Err(msg) = ask(Req::Query {
1115            conn,
1116            sql: "SELECT nope FROM notes".into(),
1117            params: vec![],
1118        }) else {
1119            panic!("bad column must error")
1120        };
1121        assert!(msg.contains("nope"), "{msg}");
1122        assert_eq!(
1123            ask(Req::Query {
1124                conn,
1125                sql: "SELECT count(*) FROM notes".into(),
1126                params: vec![],
1127            }),
1128            Reply::Rows(vec![vec![Value::Int(1)]])
1129        );
1130        assert_eq!(ask(Req::Close { conn }), Reply::Ok);
1131        let Reply::Err(gone) = ask(Req::Exec {
1132            conn,
1133            sql: "INSERT INTO notes (id) VALUES (2)".into(),
1134            params: vec![],
1135        }) else {
1136            panic!("closed connection must error")
1137        };
1138        assert!(gone.contains("no connection"), "{gone}");
1139        assert_eq!(
1140            ask(Req::Delete {
1141                name: "proto.db".into()
1142            }),
1143            Reply::Ok
1144        );
1145    }
1146
1147    #[test]
1148    fn pool_verbs_export_import_and_list() {
1149        let _engine = engine();
1150        let conn = open("source.db");
1151        assert_eq!(
1152            ask(Req::Batch {
1153                conn,
1154                sql: "CREATE TABLE t (x); INSERT INTO t VALUES (42);".into()
1155            }),
1156            Reply::Ok
1157        );
1158        assert_eq!(ask(Req::Close { conn }), Reply::Ok);
1159
1160        assert_eq!(
1161            ask(Req::Exists {
1162                name: "source.db".into()
1163            }),
1164            Reply::Bool(true)
1165        );
1166        assert_eq!(
1167            ask(Req::Exists {
1168                name: "nope.db".into()
1169            }),
1170            Reply::Bool(false)
1171        );
1172
1173        let Reply::Bytes(image) = ask(Req::Export {
1174            name: "source.db".into(),
1175        }) else {
1176            panic!("export must answer bytes")
1177        };
1178        assert!(
1179            image.starts_with(b"SQLite format 3\0"),
1180            "a real SQLite file image"
1181        );
1182
1183        assert_eq!(
1184            ask(Req::Import {
1185                name: "copy.db".into(),
1186                bytes: image
1187            }),
1188            Reply::Ok
1189        );
1190        let copy = open("copy.db");
1191        assert_eq!(
1192            ask(Req::Query {
1193                conn: copy,
1194                sql: "SELECT x FROM t".into(),
1195                params: vec![],
1196            }),
1197            Reply::Rows(vec![vec![Value::Int(42)]])
1198        );
1199        assert_eq!(ask(Req::Close { conn: copy }), Reply::Ok);
1200
1201        let Reply::Names(names) = ask(Req::List) else {
1202            panic!("list must answer names")
1203        };
1204        assert!(names.contains(&"source.db".to_string()), "{names:?}");
1205        assert!(names.contains(&"copy.db".to_string()), "{names:?}");
1206
1207        assert_eq!(
1208            ask(Req::Delete {
1209                name: "source.db".into()
1210            }),
1211            Reply::Ok
1212        );
1213        assert_eq!(
1214            ask(Req::Delete {
1215                name: "copy.db".into()
1216            }),
1217            Reply::Ok
1218        );
1219        assert_eq!(
1220            ask(Req::Exists {
1221                name: "source.db".into()
1222            }),
1223            Reply::Bool(false)
1224        );
1225    }
1226
1227    #[test]
1228    fn two_databases_are_independent() {
1229        let _engine = engine();
1230        let a = open("ind-a.db");
1231        let bconn = open("ind-b.db");
1232        assert_eq!(
1233            ask(Req::Batch {
1234                conn: a,
1235                sql: "CREATE TABLE only_a (x)".into()
1236            }),
1237            Reply::Ok
1238        );
1239        let Reply::Err(msg) = ask(Req::Query {
1240            conn: bconn,
1241            sql: "SELECT * FROM only_a".into(),
1242            params: vec![],
1243        }) else {
1244            panic!("b must not see a's table")
1245        };
1246        assert!(msg.contains("only_a"), "{msg}");
1247        assert_eq!(ask(Req::Close { conn: a }), Reply::Ok);
1248        assert_eq!(ask(Req::Close { conn: bconn }), Reply::Ok);
1249        assert_eq!(
1250            ask(Req::Delete {
1251                name: "ind-a.db".into()
1252            }),
1253            Reply::Ok
1254        );
1255        assert_eq!(
1256            ask(Req::Delete {
1257                name: "ind-b.db".into()
1258            }),
1259            Reply::Ok
1260        );
1261    }
1262
1263    #[test]
1264    fn trace_stmt_sees_every_statement_with_parameters_expanded() {
1265        use std::cell::RefCell;
1266        use std::rc::Rc;
1267        let _engine = engine();
1268        let seen: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
1269        let sink = seen.clone();
1270        let mut conn = Connection::open_memory().expect("open");
1271        conn.trace_stmt(Box::new(move |s| sink.borrow_mut().push(s.to_string())));
1272        conn.execute_batch("CREATE TABLE t (a, b)").expect("create");
1273        conn.execute(
1274            "INSERT INTO t VALUES (?, ?)",
1275            &[Value::Int(7), Value::Text("rain later".into())],
1276        )
1277        .expect("insert");
1278        let mut n = Vec::new();
1279        conn.query("SELECT count(*) FROM t", &[], &mut |r| n.push(r))
1280            .expect("count");
1281        let log = seen.borrow();
1282        assert!(log.iter().any(|s| s.contains("CREATE TABLE t")), "{log:?}");
1283        assert!(
1284            log.iter()
1285                .any(|s| s.contains("INSERT INTO t VALUES (7, 'rain later')")),
1286            "parameters expand: {log:?}"
1287        );
1288        assert!(log.iter().any(|s| s.contains("SELECT count(*)")), "{log:?}");
1289    }
1290
1291    #[test]
1292    fn malformed_requests_answer_an_error() {
1293        let _engine = engine();
1294        let reply = protocol::decode_reply(&handle_request(&[9, 9, 9])).expect("well-formed");
1295        assert_eq!(reply, Reply::Err("malformed request".to_string()));
1296    }
1297
1298    #[test]
1299    fn day_sql_exec_stages_a_length_prefixed_reply() {
1300        let _engine = engine();
1301        let req = protocol::encode_req(&Req::List);
1302        let ptr = day_sql_alloc(req.len());
1303        // SAFETY: writing exactly len bytes into a day_sql_alloc(len) buffer, then handing
1304        // ownership to day_sql_exec, its documented contract.
1305        let reply = unsafe {
1306            core::ptr::copy_nonoverlapping(req.as_ptr(), ptr, req.len());
1307            let out = day_sql_exec(ptr, req.len());
1308            let len = u32::from_le_bytes(core::slice::from_raw_parts(out, 4).try_into().unwrap());
1309            core::slice::from_raw_parts(out.add(4), len as usize).to_vec()
1310        };
1311        std::assert_matches!(protocol::decode_reply(&reply), Ok(Reply::Names(_)));
1312    }
1313}