1#[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
51mod 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 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 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#[cfg(all(target_family = "wasm", target_os = "unknown"))]
111pub mod channel {
112 #[link(wasm_import_module = "env")]
113 unsafe extern "C" {
114 fn day_sql_ready() -> i32;
116 fn day_sql_call(req: *const u8, len: usize) -> f64;
118 fn day_sql_reply(dst: *mut u8);
120 }
121
122 pub fn ready() -> bool {
125 unsafe { day_sql_ready() == 1 }
126 }
127
128 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
141const ALIGN: usize = core::mem::size_of::<usize>() * 2;
147
148#[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#[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#[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#[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#[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#[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#[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#[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
270fn 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#[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#[no_mangle]
330pub unsafe extern "C" fn sqlite3_os_init() -> c_int {
331 vfs::register_all()
332}
333
334#[no_mangle]
337pub unsafe extern "C" fn sqlite3_os_end() -> c_int {
338 b::SQLITE_OK
339}
340
341#[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
367pub type TraceFn = Box<dyn Fn(&str)>;
371
372pub struct Connection {
373 db: *mut b::sqlite3,
374 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 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 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 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 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 pub fn open_memory() -> Result<Connection, SqlError> {
452 Self::open_with(":memory:", None)
453 }
454
455 pub fn open_opfs(name: &str) -> Result<Connection, SqlError> {
461 Self::open_with(name, Some(vfs::OPFS_VFS))
462 }
463
464 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; };
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 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 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 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 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 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
646struct 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
692thread_local! {
697 static CONNS: RefCell<HashMap<u32, Connection>> = RefCell::new(HashMap::new());
698 static NEXT_CONN: Cell<u32> = const { Cell::new(1) };
699 static REPLY: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
702}
703
704pub 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, ¶ms).map(Reply::Changes))
738 }
739 Req::Query { conn, sql, params } => with_conn(conn, |c| {
740 let mut rows = Vec::new();
741 c.query(&sql, ¶ms, &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, ¶ms, &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 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#[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#[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 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 (?, ?, ?, ?, ?)", ¶ms)
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 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); 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 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 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 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}