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