From 720a884ea41b55ed9c7224c2df1e48fd92d452f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Wed, 25 Nov 2026 14:27:42 +0000 Subject: [PATCH 1/3] Fix SQLite statement ownership [skip ci] --- README.md | 6 +- .../skeleton/src/builtin/sqlite.js | 92 +- .../skeleton/src/builtin/sqlite.rs | 1291 +++++++++++------ examples/runtime/sqlite/src/sqlite.js | 164 +++ examples/runtime/sqlite/wit/sqlite.wit | 4 + tests/runtime/sqlite.rs | 64 + 6 files changed, 1184 insertions(+), 437 deletions(-) diff --git a/README.md b/README.md index 0d6b24107..1afd596a0 100644 --- a/README.md +++ b/README.md @@ -1114,11 +1114,13 @@ TCP sockets and servers built on WASI sockets. Requires the `sqlite` feature flag. Provides a synchronous SQLite database API with an embedded SQLite engine. -- `DatabaseSync` — `prepare`, `exec`, `close`, `open`, `isOpen`, `isTransaction`, `createSession`, `applyChangeset`, `enableLoadExtension`, `function`, `aggregate`, `backup` -- `StatementSync` — `run`, `get`, `all`, `iterate`, `columns`, `setReadBigInts`, `setAllowBareNamedParameters`, `sourceSQL`, `expandedSQL` +- `DatabaseSync` — `prepare`, `exec`, `close`, `open`, `isOpen`, `isTransaction`, `createSession`, `applyChangeset`, `enableLoadExtension`, `function`, `aggregate`, `backup`, `deserialize` +- `StatementSync` — `run`, `get`, `all`, `iterate`, `columns`, `close`, `Symbol.dispose`, `stat`, `resetStats`, `setReadBigInts`, `setAllowBareNamedParameters`, `sourceSQL`, `expandedSQL` - `Session` — `changeset`, `patchset`, `close` - Constants: `SQLITE_CHANGESET_OMIT`, `SQLITE_CHANGESET_REPLACE`, `SQLITE_CHANGESET_ABORT` +Statements retain their prepared SQLite handles until finalized by `close()`, disposal, garbage collection, database close, or `deserialize()`. Statistics read the actual SQLite statement counters. `deserialize()` finalizes existing statements before attempting replacement, including when that attempt fails. The separate `restoreDatabaseSync()` recovery extension preserves the connection, registered functions and idle statements; it rejects active execution or cursors before changing the database. + **Not supported:** `loadExtension()` (throws — native extensions cannot be loaded in WASM). diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.js b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.js index d94ba13bc..48be7aca2 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.js @@ -1,17 +1,20 @@ import { open_database, close_database, exec_sql, is_open, is_autocommit, - stmt_run, stmt_get, stmt_all, stmt_expanded_sql, stmt_columns, + prepare_statement, stmt_run, stmt_get, stmt_all, stmt_expanded_sql, stmt_columns, stmt_iterate_init, stmt_iterate_next, stmt_iterate_return, register_function, register_aggregate, create_session, session_changeset, session_patchset, session_close, apply_changeset, get_constants, enable_defensive, location, set_authorizer, native_backup, - serialize_database, restore_database + serialize_database, restore_database, deserialize_database, check_database_idle } from '__wasm_rquickjs_builtin/sqlite_native'; export const constants = get_constants(); const _connIdSymbol = Symbol('connId'); +const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype); +const typedArrayTag = Function.prototype.call.bind(Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag).get); +const typedArrayByteLength = Function.prototype.call.bind(Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteLength').get); function assertBoolean(value, name) { if (typeof value !== 'boolean') { @@ -144,6 +147,36 @@ class _DatabaseSyncImpl { return new Statement(_stmtSecret, this.#connId, sql, stmtOptions); } + deserialize(buffer, options) { + if (this.#connId === null) throwDbNotOpen('ERR_INVALID_STATE'); + check_database_idle(this.#connId); + if (typedArrayTag(buffer) !== 'Uint8Array') { + throw Object.assign(new TypeError('The "buffer" argument must be a Uint8Array.'), { code: 'ERR_INVALID_ARG_TYPE' }); + } + const length = typedArrayByteLength(buffer); + if (length === 0) { + throw Object.assign(new TypeError('The "buffer" argument must not be empty.'), { code: 'ERR_INVALID_ARG_VALUE' }); + } + let dbName = 'main'; + if (options !== undefined) { + if (options === null || (typeof options !== 'object' && typeof options !== 'function')) { + throw Object.assign(new TypeError('The "options" argument must be an object.'), { code: 'ERR_INVALID_ARG_TYPE' }); + } + const value = options.dbName; + if (value !== undefined) { + if (typeof value !== 'string') { + throw Object.assign(new TypeError('The "options.dbName" argument must be a string.'), { code: 'ERR_INVALID_ARG_TYPE' }); + } + dbName = value; + } + } + if (this.#connId === null) throwDbNotOpen('ERR_INVALID_STATE'); + if (typedArrayByteLength(buffer) !== length) { + throw Object.assign(new Error('The "buffer" argument was resized while reading "options"'), { code: 'ERR_INVALID_STATE' }); + } + deserialize_database(this.#connId, buffer, dbName); + } + function(name, optionsOrFn, maybeFn) { if (this.#connId === null) throwDbNotOpen('ERR_INVALID_STATE'); @@ -395,10 +428,8 @@ export class Session { const _stmtSecret = Symbol('stmtSecret'); export class Statement { - #connId; - #sql; + #handle; #options; - #lastParams = null; constructor(secret, connId, sql, options) { if (secret !== _stmtSecret) { @@ -406,8 +437,7 @@ export class Statement { err.code = 'ERR_ILLEGAL_CONSTRUCTOR'; throw err; } - this.#connId = connId; - this.#sql = sql; + this.#handle = prepare_statement(connId, sql); this.#options = options; } @@ -430,18 +460,18 @@ export class Statement { } run(...args) { + this.#handle.check(); const params = this.#processParams(args); - this.#lastParams = params; - return stmt_run(this.#connId, this.#sql, params, + return stmt_run(this.#handle, params, this.#options.allowBareNamedParameters, this.#options.allowUnknownNamedParameters, this.#options.readBigInts); } get(...args) { + this.#handle.check(); const params = this.#processParams(args); - this.#lastParams = params; - return stmt_get(this.#connId, this.#sql, params, + return stmt_get(this.#handle, params, this.#options.allowBareNamedParameters, this.#options.allowUnknownNamedParameters, this.#options.readBigInts, @@ -449,9 +479,9 @@ export class Statement { } all(...args) { + this.#handle.check(); const params = this.#processParams(args); - this.#lastParams = params; - return stmt_all(this.#connId, this.#sql, params, + return stmt_all(this.#handle, params, this.#options.allowBareNamedParameters, this.#options.allowUnknownNamedParameters, this.#options.readBigInts, @@ -459,26 +489,25 @@ export class Statement { } columns() { - return stmt_columns(this.#connId, this.#sql); + return stmt_columns(this.#handle); } iterate(...args) { + this.#handle.check(); const params = this.#processParams(args); - this.#lastParams = params; - const iterId = stmt_iterate_init(this.#connId, this.#sql, params, + const iterId = stmt_iterate_init(this.#handle, params, this.#options.allowBareNamedParameters, this.#options.allowUnknownNamedParameters); - const readBigInts = this.#options.readBigInts; - const returnArrays = this.#options.returnArrays; + const options = this.#options; return { [Symbol.iterator]() { return this; }, next() { - return stmt_iterate_next(iterId, readBigInts, returnArrays); + return stmt_iterate_next(iterId, options.readBigInts, options.returnArrays); }, return() { stmt_iterate_return(iterId); - return { value: undefined, done: true }; + return { __proto__: null, value: null, done: true }; }, toArray() { const result = []; @@ -492,30 +521,43 @@ export class Statement { } get sourceSQL() { - return this.#sql; + return this.#handle.source(); } get expandedSQL() { - if (this.#lastParams !== null && this.#lastParams !== undefined) { - return stmt_expanded_sql(this.#connId, this.#sql, this.#lastParams, - this.#options.allowBareNamedParameters); + return stmt_expanded_sql(this.#handle); + } + + close() { this.#handle.close(); } + [Symbol.dispose]() { this.#handle.dispose(); } + + stat(counter) { + this.#handle.check(); + if (typeof counter !== 'string') { + throw Object.assign(new TypeError('The "counter" argument must be a string.'), { code: 'ERR_INVALID_ARG_TYPE' }); } - return this.#sql; + return this.#handle.stat(counter); } + resetStats() { this.#handle.resetStats(); } + setReadBigInts(enabled) { + this.#handle.check(); assertBoolean(enabled, 'readBigInts'); this.#options.readBigInts = enabled; } setReturnArrays(enabled) { + this.#handle.check(); assertBoolean(enabled, 'returnArrays'); this.#options.returnArrays = enabled; } setAllowBareNamedParameters(enabled) { + this.#handle.check(); assertBoolean(enabled, 'allowBareNamedParameters'); this.#options.allowBareNamedParameters = enabled; } setAllowUnknownNamedParameters(enabled) { + this.#handle.check(); assertBoolean(enabled, 'allowUnknownNamedParameters'); this.#options.allowUnknownNamedParameters = enabled; } diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs index d455f436a..00e7244c6 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs @@ -1,7 +1,8 @@ use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::sync::{Arc, LazyLock, Mutex}; +use std::rc::{Rc, Weak as StatementWeak}; +use std::sync::{Arc, LazyLock, Mutex, Weak}; use std::time::Duration; use rquickjs::qjs; @@ -15,7 +16,7 @@ const MIN_SAFE_INTEGER: i64 = -9007199254740991; use rusqlite::ffi::sqlite3_errstr; struct ConnectionTable { - connections: HashMap, + connections: HashMap>, next_id: u32, } @@ -30,35 +31,384 @@ impl ConnectionTable { fn insert(&mut self, conn: rusqlite::Connection) -> u32 { let id = self.next_id; self.next_id += 1; - self.connections.insert(id, conn); + self.connections.insert( + id, + Arc::new(SqliteConnection { + conn, + statements: RefCell::new(Vec::new()), + in_authorizer: Cell::new(false), + mutating: Cell::new(false), + }), + ); id } } -struct IteratorState { - col_names: Vec, - values: Vec>, - position: usize, +struct SqliteConnection { + conn: rusqlite::Connection, + statements: RefCell>>, + in_authorizer: Cell, + mutating: Cell, } -struct IteratorTable { - iterators: HashMap, - next_id: u32, +// SAFETY: Like the session and JS callback tables below, this registry is only +// accessed by the single-threaded WASM runtime. No connection crosses threads. +unsafe impl Send for SqliteConnection {} +unsafe impl Sync for SqliteConnection {} + +impl std::ops::Deref for SqliteConnection { + type Target = rusqlite::Connection; + + fn deref(&self) -> &Self::Target { + &self.conn + } } -impl IteratorTable { - fn new() -> Self { - Self { - iterators: HashMap::new(), - next_id: 1, +struct StatementState { + connection: Weak, + raw: Cell<*mut rusqlite::ffi::sqlite3_stmt>, + executing: Cell, + cursor: Cell, + generation: Cell, +} + +impl StatementState { + fn pointer<'js>( + &self, + ctx: &rquickjs::Ctx<'js>, + ) -> rquickjs::Result<*mut rusqlite::ffi::sqlite3_stmt> { + let ptr = self.raw.get(); + if ptr.is_null() { + return Err(throw_coded_error( + ctx, + "Error", + "statement has been finalized", + "ERR_INVALID_STATE", + )); } + Ok(ptr) } - fn insert(&mut self, state: IteratorState) -> u32 { - let id = self.next_id; - self.next_id += 1; - self.iterators.insert(id, state); - id + fn finalize(&self) { + let ptr = self.raw.replace(std::ptr::null_mut()); + self.cursor.set(false); + if !ptr.is_null() { + // SAFETY: only this state owns the handle; the connection's weak + // registry finalizes it before dropping the connection. + unsafe { + rusqlite::ffi::sqlite3_finalize(ptr); + } + } + } +} + +impl Drop for StatementState { + fn drop(&mut self) { + // SQLite can invoke aggregate xFinal while finalizing. A GC finalizer + // must not call JS, even if collection happens inside a SQLite callback. + let _guard = JsCtxGuard::new(std::ptr::null_mut()); + self.finalize(); + } +} + +#[derive(rquickjs::class::Trace, rquickjs::JsLifetime)] +#[rquickjs::class] +pub struct NativeStatement { + #[qjs(skip_trace)] + state: Rc, +} + +#[derive(rquickjs::class::Trace, rquickjs::JsLifetime)] +#[rquickjs::class] +pub struct NativeIterator { + #[qjs(skip_trace)] + state: Rc, + generation: u64, + #[qjs(skip_trace)] + done: Cell, +} + +impl Drop for NativeIterator { + fn drop(&mut self) { + if !self.done.get() + && self.generation == self.state.generation.get() + && !self.state.raw.get().is_null() + && !self.state.executing.get() + { + let _guard = JsCtxGuard::new(std::ptr::null_mut()); + unsafe { + rusqlite::ffi::sqlite3_reset(self.state.raw.get()); + } + self.state.cursor.set(false); + } + } +} + +struct StatementGuard<'a> { + state: &'a StatementState, + conn: Arc, + _js: JsCtxGuard, +} + +struct FlagGuard<'a>(&'a Cell); +impl Drop for FlagGuard<'_> { + fn drop(&mut self) { + self.0.set(false); + } +} + +impl Drop for StatementGuard<'_> { + fn drop(&mut self) { + self.state.executing.set(false); + } +} + +impl StatementState { + fn enter<'a, 'js>(&'a self, ctx: &rquickjs::Ctx<'js>) -> rquickjs::Result> { + self.pointer(ctx)?; + let conn = self.connection.upgrade().ok_or_else(|| { + throw_coded_error( + ctx, + "Error", + "statement has been finalized", + "ERR_INVALID_STATE", + ) + })?; + if self.executing.get() || conn.in_authorizer.get() || conn.mutating.get() { + return Err(throw_coded_error( + ctx, + "Error", + if conn.in_authorizer.get() { + "database cannot be accessed from an authorizer callback" + } else { + "statement is already being executed" + }, + "ERR_INVALID_STATE", + )); + } + self.executing.set(true); + Ok(StatementGuard { + state: self, + conn, + _js: JsCtxGuard::new(ctx.as_raw().as_ptr()), + }) + } + + fn begin<'js>( + &self, + ctx: &rquickjs::Ctx<'js>, + params: &rquickjs::Value<'js>, + bare: bool, + unknown: bool, + ) -> rquickjs::Result<()> { + self.generation.set(self.generation.get().wrapping_add(1)); + self.cursor.set(false); + let rc = unsafe { rusqlite::ffi::sqlite3_reset(self.raw.get()) }; + let conn = self.connection.upgrade().unwrap(); + check_sqlite(ctx, &conn, rc)?; + bind_params(ctx, self.raw.get(), params, bare, unknown) + } + + fn step<'js>( + &self, + ctx: &rquickjs::Ctx<'js>, + conn: &SqliteConnection, + ) -> rquickjs::Result { + let rc = unsafe { rusqlite::ffi::sqlite3_step(self.raw.get()) }; + match rc { + rusqlite::ffi::SQLITE_ROW => Ok(true), + rusqlite::ffi::SQLITE_DONE => Ok(false), + _ => { + check_sqlite(ctx, conn, rc)?; + unreachable!() + } + } + } + + fn finish<'js, T>( + &self, + ctx: &rquickjs::Ctx<'js>, + conn: &SqliteConnection, + outcome: rquickjs::Result, + ) -> rquickjs::Result { + self.cursor.set(false); + let rc = unsafe { rusqlite::ffi::sqlite3_reset(self.raw.get()) }; + match outcome { + Ok(value) => { + check_sqlite(ctx, conn, rc)?; + Ok(value) + } + Err(error) => { + take_pending_js_exception(ctx); + Err(error) + } + } + } +} + +fn check_sqlite<'js>( + ctx: &rquickjs::Ctx<'js>, + conn: &SqliteConnection, + rc: i32, +) -> rquickjs::Result<()> { + if rc == rusqlite::ffi::SQLITE_OK { + return Ok(()); + } + let message = unsafe { std::ffi::CStr::from_ptr(rusqlite::ffi::sqlite3_errmsg(conn.handle())) } + .to_string_lossy() + .into_owned(); + Err(map_sqlite_or_udf_error( + ctx, + rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), Some(message)), + )) +} + +fn prepare_statement_impl<'js>( + ctx: rquickjs::Ctx<'js>, + conn_id: u32, + sql: String, +) -> rquickjs::Result { + let conn = connection(&ctx, conn_id)?; + if conn.in_authorizer.get() { + return Err(throw_coded_error( + &ctx, + "Error", + "database is busy", + "ERR_INVALID_STATE", + )); + } + let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); + let sql = std::ffi::CString::new(sql).map_err(|_| { + throw_coded_error( + &ctx, + "Error", + "SQL text contains a null byte", + "ERR_INVALID_ARG_VALUE", + ) + })?; + let mut raw = std::ptr::null_mut(); + let rc = unsafe { + rusqlite::ffi::sqlite3_prepare_v2( + conn.handle(), + sql.as_ptr(), + -1, + &mut raw, + std::ptr::null_mut(), + ) + }; + if rc != rusqlite::ffi::SQLITE_OK { + if !raw.is_null() { + unsafe { + rusqlite::ffi::sqlite3_finalize(raw); + } + } + check_sqlite(&ctx, &conn, rc)?; + } + if raw.is_null() { + return Err(throw_coded_error( + &ctx, + "Error", + "SQL text contains no statements", + "ERR_INVALID_ARG_VALUE", + )); + } + let state = Rc::new(StatementState { + connection: Arc::downgrade(&conn), + raw: Cell::new(raw), + executing: Cell::new(false), + cursor: Cell::new(false), + generation: Cell::new(0), + }); + let mut statements = conn.statements.borrow_mut(); + statements.retain(|s| s.strong_count() > 0); + statements.push(Rc::downgrade(&state)); + Ok(NativeStatement { state }) +} + +#[rquickjs::methods] +impl NativeStatement { + pub fn check<'js>(&self, ctx: rquickjs::Ctx<'js>) -> rquickjs::Result<()> { + self.state.pointer(&ctx).map(|_| ()) + } + + pub fn close<'js>(&self, ctx: rquickjs::Ctx<'js>) -> rquickjs::Result<()> { + let ptr = self.state.pointer(&ctx)?; + let conn = self.state.connection.upgrade().unwrap(); + if self.state.executing.get() || conn.mutating.get() { + return Err(throw_coded_error( + &ctx, + "Error", + "statement is already being executed", + "ERR_INVALID_STATE", + )); + } + if conn.in_authorizer.get() && unsafe { rusqlite::ffi::sqlite3_stmt_busy(ptr) } != 0 { + return Err(throw_coded_error( + &ctx, + "Error", + "database cannot be accessed from an authorizer callback", + "ERR_INVALID_STATE", + )); + } + self.state.executing.set(true); + let _guard = StatementGuard { + state: &self.state, + conn, + _js: JsCtxGuard::new(ctx.as_raw().as_ptr()), + }; + self.state.finalize(); + Ok(()) + } + + pub fn dispose<'js>(&self, ctx: rquickjs::Ctx<'js>) -> rquickjs::Result<()> { + if self.state.raw.get().is_null() { + return Ok(()); + } + self.close(ctx) + } + + pub fn source<'js>(&self, ctx: rquickjs::Ctx<'js>) -> rquickjs::Result { + let ptr = self.state.pointer(&ctx)?; + Ok( + unsafe { std::ffi::CStr::from_ptr(rusqlite::ffi::sqlite3_sql(ptr)) } + .to_string_lossy() + .into_owned(), + ) + } + + pub fn stat<'js>(&self, ctx: rquickjs::Ctx<'js>, counter: String) -> rquickjs::Result { + let ptr = self.state.pointer(&ctx)?; + let id = match counter.as_str() { + "fullscanStep" => 1, + "sort" => 2, + "autoindex" => 3, + "vmStep" => 4, + "reprepare" => 5, + "run" => 6, + "filterMiss" => 7, + "filterHit" => 8, + "memused" => 99, + _ => { + return Err(throw_coded_error( + &ctx, + "TypeError", + "The \"counter\" argument is not a valid statistic name.", + "ERR_INVALID_ARG_VALUE", + )); + } + }; + Ok(unsafe { rusqlite::ffi::sqlite3_stmt_status(ptr, id, 0) }) + } + + #[qjs(rename = "resetStats")] + pub fn reset_stats<'js>(&self, ctx: rquickjs::Ctx<'js>) -> rquickjs::Result<()> { + let ptr = self.state.pointer(&ctx)?; + for id in 1..=8 { + unsafe { + rusqlite::ffi::sqlite3_stmt_status(ptr, id, 1); + } + } + Ok(()) } } @@ -94,9 +444,6 @@ impl SessionTable { static CONN_TABLE: LazyLock> = LazyLock::new(|| Mutex::new(ConnectionTable::new())); -static ITER_TABLE: LazyLock> = - LazyLock::new(|| Mutex::new(IteratorTable::new())); - static SESSION_TABLE: LazyLock> = LazyLock::new(|| Mutex::new(SessionTable::new())); @@ -415,28 +762,59 @@ fn create_null_proto_object<'js>( fn row_to_js<'js>( ctx: &rquickjs::Ctx<'js>, - col_names: &[String], - row: &rusqlite::Row, + stmt: *mut rusqlite::ffi::sqlite3_stmt, return_arrays: bool, read_big_ints: bool, ) -> rquickjs::Result> { - if return_arrays { - let arr = rquickjs::Array::new(ctx.clone())?; - for i in 0..col_names.len() { - let val = row.get_ref(i).map_err(|e| sqlite_error(ctx, &e))?; - let js_val = sqlite_value_to_js(ctx, &val, read_big_ints, i)?; - arr.set(i, js_val)?; - } - Ok(arr.into_value()) - } else { - let obj = create_null_proto_object(ctx)?; - for (i, name) in col_names.iter().enumerate() { - let val = row.get_ref(i).map_err(|e| sqlite_error(ctx, &e))?; - let js_val = sqlite_value_to_js(ctx, &val, read_big_ints, i)?; - obj.set(name.as_str(), js_val)?; + use rusqlite::{ffi, types::Value}; + let mut names = Vec::new(); + let mut values = Vec::new(); + // SAFETY: the caller has stepped to SQLITE_ROW and holds the statement + // execution guard. Copy all SQLite bytes before any JS allocation/property + // creation can run user code or GC finalizers. + unsafe { + for i in 0..ffi::sqlite3_column_count(stmt) { + names.push( + std::ffi::CStr::from_ptr(ffi::sqlite3_column_name(stmt, i)) + .to_string_lossy() + .into_owned(), + ); + values.push(match ffi::sqlite3_column_type(stmt, i) { + ffi::SQLITE_INTEGER => Value::Integer(ffi::sqlite3_column_int64(stmt, i)), + ffi::SQLITE_FLOAT => Value::Real(ffi::sqlite3_column_double(stmt, i)), + ffi::SQLITE_TEXT => { + let ptr = ffi::sqlite3_column_text(stmt, i); + let len = ffi::sqlite3_column_bytes(stmt, i) as usize; + let bytes = if len == 0 { + &[] + } else { + std::slice::from_raw_parts(ptr, len) + }; + Value::Text( + std::str::from_utf8(bytes) + .map_err(|_| { + rquickjs::Exception::throw_message( + ctx, + "Invalid UTF-8 in SQLite TEXT value", + ) + })? + .to_string(), + ) + } + ffi::SQLITE_BLOB => { + let ptr = ffi::sqlite3_column_blob(stmt, i); + let len = ffi::sqlite3_column_bytes(stmt, i) as usize; + Value::Blob(if len == 0 { + Vec::new() + } else { + std::slice::from_raw_parts(ptr.cast::(), len).to_vec() + }) + } + _ => Value::Null, + }); } - Ok(obj.into_value()) } + owned_row_to_js(ctx, &names, &values, return_arrays, read_big_ints) } fn owned_row_to_js<'js>( @@ -471,12 +849,68 @@ fn lock_conn_table<'js>( }) } +fn connection<'js>(ctx: &rquickjs::Ctx<'js>, id: u32) -> rquickjs::Result> { + let conn = lock_conn_table(ctx)? + .connections + .get(&id) + .cloned() + .ok_or_else(|| { + throw_coded_error(ctx, "Error", "database is not open", "ERR_INVALID_STATE") + })?; + if conn.mutating.get() { + return Err(throw_coded_error( + ctx, + "Error", + "database is busy", + "ERR_INVALID_STATE", + )); + } + Ok(conn) +} + +fn check_idle_connection<'js>( + ctx: &rquickjs::Ctx<'js>, + conn: &Arc, + message: &str, +) -> rquickjs::Result<()> { + // The table and the current operation own the only strong references when + // no SQLite call is on the stack. Statements retain weak connection links. + if Arc::strong_count(conn) > 2 || conn.in_authorizer.get() { + return Err(throw_coded_error( + ctx, + "Error", + message, + "ERR_INVALID_STATE", + )); + } + Ok(()) +} + +fn finalize_statements(conn: &SqliteConnection) { + let statements: Vec<_> = conn + .statements + .borrow_mut() + .drain(..) + .filter_map(|s| s.upgrade()) + .collect(); + // No registry borrow survives sqlite3_finalize (aggregate cleanup can call JS). + for stmt in statements { + stmt.finalize(); + } +} + fn bind_params<'js>( ctx: &rquickjs::Ctx<'js>, - stmt: &mut rusqlite::Statement, + stmt: *mut rusqlite::ffi::sqlite3_stmt, params: &rquickjs::Value<'js>, allow_bare_named: bool, + allow_unknown_named: bool, ) -> rquickjs::Result<()> { + use rusqlite::ffi; + // SAFETY: the caller owns a live statement and holds its execution guard. + unsafe { + ffi::sqlite3_clear_bindings(stmt); + } if params.is_null() || params.is_undefined() { return Ok(()); } @@ -484,117 +918,104 @@ fn bind_params<'js>( if let Some(arr) = params.as_array() { for i in 0..arr.len() { let val: rquickjs::Value<'js> = arr.get(i)?; - let sql_val = js_value_to_sqlite(ctx, &val, i + 1)?; - stmt.raw_bind_parameter(i + 1, sql_val) - .map_err(|e| sqlite_error(ctx, &e))?; + bind_value(ctx, stmt, i + 1, &val)?; } } else if params.is_object() { let obj = params.as_object().ok_or_else(|| { rquickjs::Exception::throw_message(ctx, "expected object for named parameters") })?; - let count = stmt.parameter_count(); - for idx in 1..=count { - if let Some(name) = stmt.parameter_name(idx) { - let val: rquickjs::Value<'js> = obj - .get::<_, rquickjs::Value<'js>>(name) - .unwrap_or_else(|_| rquickjs::Value::new_null(ctx.clone())); - - let val = if (val.is_undefined() || val.is_null()) - && allow_bare_named - && name.len() > 1 - && matches!(name.as_bytes()[0], b':' | b'@' | b'$') - { - let bare = &name[1..]; - obj.get::<_, rquickjs::Value<'js>>(bare) - .unwrap_or_else(|_| rquickjs::Value::new_null(ctx.clone())) - } else { - val - }; - - // For named params, treat undefined as NULL (unbound) - let val = if val.is_undefined() { - rquickjs::Value::new_null(ctx.clone()) - } else { - val - }; - - let sql_val = js_value_to_sqlite(ctx, &val, idx)?; - stmt.raw_bind_parameter(idx, sql_val) - .map_err(|e| sqlite_error(ctx, &e))?; + let mut bare_names = HashMap::new(); + if allow_bare_named { + for idx in 1..=unsafe { ffi::sqlite3_bind_parameter_count(stmt) } { + let ptr = unsafe { ffi::sqlite3_bind_parameter_name(stmt, idx) }; + if ptr.is_null() { + continue; + } + let name = unsafe { std::ffi::CStr::from_ptr(ptr) } + .to_string_lossy() + .into_owned(); + let bare = name[1..].to_string(); + if let Some((other, _)) = bare_names.insert(bare.clone(), (name.clone(), idx)) { + return Err(throw_coded_error( + ctx, + "Error", + &format!( + "Cannot create bare named parameter '{}' because of conflicting names '{}' and '{}'.", + bare, other, name + ), + "ERR_INVALID_STATE", + )); + } } } - } - - Ok(()) -} - -fn validate_named_params<'js>( - ctx: &rquickjs::Ctx<'js>, - stmt: &rusqlite::Statement, - params: &rquickjs::Value<'js>, - allow_bare_named: bool, - allow_unknown_named: bool, -) -> rquickjs::Result<()> { - if params.is_null() || params.is_undefined() { - return Ok(()); - } - if params.as_array().is_some() { - return Ok(()); - } - let obj = match params.as_object() { - Some(o) => o, - None => return Ok(()), - }; - - let props = obj.props::(); - for entry in props { - let (key, _) = entry?; - - // Check if key directly matches a SQL parameter name - let direct_match = (1..=stmt.parameter_count()) - .any(|idx| stmt.parameter_name(idx).is_some_and(|name| name == key)); - if direct_match { - continue; - } - - // Check bare name matching if enabled - if allow_bare_named { - let matching_names: Vec = (1..=stmt.parameter_count()) - .filter_map(|idx| stmt.parameter_name(idx)) - .filter(|name| { - name.len() > 1 - && matches!(name.as_bytes()[0], b':' | b'@' | b'$') - && name[1..] == key - }) - .map(String::from) - .collect(); - - if matching_names.len() > 1 { + // Enumerate keys without reading values: ignored unknown keys must not + // invoke getters, and recognized getters run exactly once. + let keys: Vec = obj + .own_keys(rquickjs::object::Filter::new().string()) + .collect::>()?; + for key in keys { + let name = std::ffi::CString::new(key.as_str()).ok(); + let mut idx = name.as_ref().map_or(0, |name| unsafe { + ffi::sqlite3_bind_parameter_index(stmt, name.as_ptr()) + }); + if idx == 0 && allow_bare_named { + idx = bare_names.get(&key).map_or(0, |(_, idx)| *idx); + } + if idx == 0 { + if allow_unknown_named { + continue; + } return Err(throw_coded_error( ctx, "Error", - &format!( - "Cannot create bare named parameter '{}' because of conflicting names '{}' and '{}'.", - key, matching_names[0], matching_names[1] - ), + &format!("Unknown named parameter '{}'", key), "ERR_INVALID_STATE", )); } - - if !matching_names.is_empty() { - continue; - } + let val = obj.get(key)?; + bind_value(ctx, stmt, idx as usize, &val)?; } + } + Ok(()) +} - // No match found - if !allow_unknown_named { - return Err(throw_coded_error( - ctx, - "Error", - &format!("Unknown named parameter '{}'", key), - "ERR_INVALID_STATE", - )); +fn bind_value<'js>( + ctx: &rquickjs::Ctx<'js>, + stmt: *mut rusqlite::ffi::sqlite3_stmt, + index: usize, + val: &rquickjs::Value<'js>, +) -> rquickjs::Result<()> { + use rusqlite::{ffi, types::Value}; + let value = js_value_to_sqlite(ctx, val, index)?; + // SAFETY: handle is live/guarded; SQLite copies string/blob bytes before the + // owned Rust value is dropped, including empty blobs (a non-null slice ptr). + let rc = unsafe { + match value { + Value::Null => ffi::sqlite3_bind_null(stmt, index as i32), + Value::Integer(i) => ffi::sqlite3_bind_int64(stmt, index as i32, i), + Value::Real(f) => ffi::sqlite3_bind_double(stmt, index as i32, f), + Value::Text(s) => ffi::sqlite3_bind_text64( + stmt, + index as i32, + s.as_ptr().cast(), + s.len() as u64, + ffi::SQLITE_TRANSIENT(), + ffi::SQLITE_UTF8 as u8, + ), + Value::Blob(b) => ffi::sqlite3_bind_blob64( + stmt, + index as i32, + b.as_ptr().cast(), + b.len() as u64, + ffi::SQLITE_TRANSIENT(), + ), } + }; + if rc != ffi::SQLITE_OK { + return Err(sqlite_error( + ctx, + &rusqlite::Error::SqliteFailure(ffi::Error::new(rc), None), + )); } Ok(()) } @@ -662,6 +1083,12 @@ fn open_database_impl<'js>( } fn close_database_impl<'js>(ctx: rquickjs::Ctx<'js>, conn_id: u32) -> rquickjs::Result<()> { + let conn = connection(&ctx, conn_id)?; + check_idle_connection(&ctx, &conn, "database cannot be closed while in a callback")?; + let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); + conn.mutating.set(true); + let _mutation = FlagGuard(&conn.mutating); + finalize_statements(&conn); // Clean up sessions associated with this connection first if let Ok(mut session_table) = SESSION_TABLE.lock() { session_table @@ -681,11 +1108,15 @@ fn close_database_impl<'js>(ctx: rquickjs::Ctx<'js>, conn_id: u32) -> rquickjs:: fn exec_sql_impl<'js>(ctx: rquickjs::Ctx<'js>, conn_id: u32, sql: String) -> rquickjs::Result<()> { let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; + if conn.in_authorizer.get() { + return Err(throw_coded_error( + &ctx, + "Error", + "database is busy", + "ERR_INVALID_STATE", + )); + } conn.execute_batch(&sql) .map_err(|e| sqlite_error(&ctx, &e))?; Ok(()) @@ -708,40 +1139,22 @@ fn is_autocommit_impl(conn_id: u32) -> bool { fn stmt_run_impl<'js>( ctx: rquickjs::Ctx<'js>, - conn_id: u32, - sql: String, + stmt: &NativeStatement, params: rquickjs::Value<'js>, allow_bare_named: bool, allow_unknown_named: bool, read_big_ints: bool, ) -> rquickjs::Result> { - let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; - - { - let mut stmt = conn.prepare(&sql).map_err(|e| sqlite_error(&ctx, &e))?; - validate_named_params(&ctx, &stmt, ¶ms, allow_bare_named, allow_unknown_named)?; - bind_params(&ctx, &mut stmt, ¶ms, allow_bare_named)?; - - if stmt.column_count() > 0 { - let mut rows = stmt.raw_query(); - while rows - .next() - .map_err(|e| map_sqlite_or_udf_error(&ctx, e))? - .is_some() - {} - } else { - stmt.raw_execute() - .map_err(|e| map_sqlite_or_udf_error(&ctx, e))?; - } - } - - let changes = conn.changes(); - let last_rowid = conn.last_insert_rowid(); + let guard = stmt.state.enter(&ctx)?; + let outcome = (|| { + stmt.state + .begin(&ctx, ¶ms, allow_bare_named, allow_unknown_named)?; + while stmt.state.step(&ctx, &guard.conn)? {} + Ok(()) + })(); + stmt.state.finish(&ctx, &guard.conn, outcome)?; + let changes = guard.conn.changes(); + let last_rowid = guard.conn.last_insert_rowid(); let result = rquickjs::Object::new(ctx.clone())?; if read_big_ints { @@ -766,125 +1179,108 @@ struct StatementResultOptions { fn stmt_get_impl<'js>( ctx: rquickjs::Ctx<'js>, - conn_id: u32, - sql: String, + stmt: &NativeStatement, params: rquickjs::Value<'js>, options: StatementResultOptions, ) -> rquickjs::Result> { - let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; - - let mut stmt = conn.prepare(&sql).map_err(|e| sqlite_error(&ctx, &e))?; - validate_named_params( - &ctx, - &stmt, - ¶ms, - options.allow_bare_named, - options.allow_unknown_named, - )?; - bind_params(&ctx, &mut stmt, ¶ms, options.allow_bare_named)?; - - let col_names: Vec = stmt.column_names().into_iter().map(String::from).collect(); - let mut rows = stmt.raw_query(); - - match rows.next().map_err(|e| map_sqlite_or_udf_error(&ctx, e))? { - Some(row) => row_to_js( + let guard = stmt.state.enter(&ctx)?; + let outcome = (|| { + stmt.state.begin( &ctx, - &col_names, - row, - options.return_arrays, - options.read_big_ints, - ), - None => Ok(rquickjs::Value::new_undefined(ctx.clone())), - } + ¶ms, + options.allow_bare_named, + options.allow_unknown_named, + )?; + if stmt.state.step(&ctx, &guard.conn)? { + row_to_js( + &ctx, + stmt.state.raw.get(), + options.return_arrays, + options.read_big_ints, + ) + } else { + Ok(rquickjs::Value::new_undefined(ctx.clone())) + } + })(); + stmt.state.finish(&ctx, &guard.conn, outcome) } fn stmt_all_impl<'js>( ctx: rquickjs::Ctx<'js>, - conn_id: u32, - sql: String, + stmt: &NativeStatement, params: rquickjs::Value<'js>, options: StatementResultOptions, ) -> rquickjs::Result> { - let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; - - let mut stmt = conn.prepare(&sql).map_err(|e| sqlite_error(&ctx, &e))?; - validate_named_params( - &ctx, - &stmt, - ¶ms, - options.allow_bare_named, - options.allow_unknown_named, - )?; - bind_params(&ctx, &mut stmt, ¶ms, options.allow_bare_named)?; - - let col_names: Vec = stmt.column_names().into_iter().map(String::from).collect(); - let mut rows = stmt.raw_query(); - let result = rquickjs::Array::new(ctx.clone())?; - let mut idx = 0u32; - - while let Some(row) = rows.next().map_err(|e| map_sqlite_or_udf_error(&ctx, e))? { - let val = row_to_js( + let guard = stmt.state.enter(&ctx)?; + let outcome = (|| { + stmt.state.begin( &ctx, - &col_names, - row, - options.return_arrays, - options.read_big_ints, + ¶ms, + options.allow_bare_named, + options.allow_unknown_named, )?; - result.set(idx as usize, val)?; - idx += 1; - } - - Ok(result) + let result = rquickjs::Array::new(ctx.clone())?; + let mut idx = 0; + while stmt.state.step(&ctx, &guard.conn)? { + result.set( + idx, + row_to_js( + &ctx, + stmt.state.raw.get(), + options.return_arrays, + options.read_big_ints, + )?, + )?; + idx += 1; + } + Ok(result) + })(); + stmt.state.finish(&ctx, &guard.conn, outcome) } fn stmt_expanded_sql_impl<'js>( ctx: rquickjs::Ctx<'js>, - conn_id: u32, - sql: String, - params: rquickjs::Value<'js>, - allow_bare_named: bool, + stmt: &NativeStatement, ) -> rquickjs::Result { - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; - - let mut stmt = conn.prepare(&sql).map_err(|e| sqlite_error(&ctx, &e))?; - bind_params(&ctx, &mut stmt, ¶ms, allow_bare_named)?; - - Ok(stmt.expanded_sql().unwrap_or(sql)) + let ptr = stmt.state.pointer(&ctx)?; + let text = unsafe { rusqlite::ffi::sqlite3_expanded_sql(ptr) }; + if text.is_null() { + return Err(throw_coded_error( + &ctx, + "Error", + "Expanded SQL text would exceed configured limits", + "ERR_SQLITE_ERROR", + )); + } + let result = unsafe { std::ffi::CStr::from_ptr(text) } + .to_string_lossy() + .into_owned(); + unsafe { + rusqlite::ffi::sqlite3_free(text.cast()); + } + Ok(result) } fn stmt_columns_impl<'js>( ctx: rquickjs::Ctx<'js>, - conn_id: u32, - sql: String, + stmt: &NativeStatement, ) -> rquickjs::Result> { - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; - - let stmt = conn.prepare(&sql).map_err(|e| sqlite_error(&ctx, &e))?; - let col_count = stmt.column_count(); + let ptr = stmt.state.pointer(&ctx)?; + let col_count = unsafe { rusqlite::ffi::sqlite3_column_count(ptr) }; + // Copy all SQLite-owned strings before allocating JS objects or invoking + // inherited setters, which can finalize this statement through reentry. + let names: Vec = (0..col_count) + .map(|i| { + unsafe { std::ffi::CStr::from_ptr(rusqlite::ffi::sqlite3_column_name(ptr, i)) } + .to_string_lossy() + .into_owned() + }) + .collect(); let result = rquickjs::Array::new(ctx.clone())?; - for i in 0..col_count { + for (i, name) in names.iter().enumerate() { let info = rquickjs::Object::new(ctx.clone())?; - let name = stmt.column_name(i).map_err(|e| sqlite_error(&ctx, &e))?; - info.set("name", name)?; + info.set("name", name.as_str())?; info.set("column", rquickjs::Value::new_null(ctx.clone()))?; info.set("table", rquickjs::Value::new_null(ctx.clone()))?; info.set("database", rquickjs::Value::new_null(ctx.clone()))?; @@ -897,93 +1293,79 @@ fn stmt_columns_impl<'js>( fn stmt_iterate_init_impl<'js>( ctx: rquickjs::Ctx<'js>, - conn_id: u32, - sql: String, + stmt: &NativeStatement, params: rquickjs::Value<'js>, allow_bare_named: bool, allow_unknown_named: bool, -) -> rquickjs::Result { - let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); - - let state = { - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; - - let mut stmt = conn.prepare(&sql).map_err(|e| sqlite_error(&ctx, &e))?; - validate_named_params(&ctx, &stmt, ¶ms, allow_bare_named, allow_unknown_named)?; - bind_params(&ctx, &mut stmt, ¶ms, allow_bare_named)?; - - let col_names: Vec = stmt.column_names().into_iter().map(String::from).collect(); - let mut rows = stmt.raw_query(); - let mut all_values = Vec::new(); - - while let Some(row) = rows.next().map_err(|e| map_sqlite_or_udf_error(&ctx, e))? { - let mut row_vals = Vec::with_capacity(col_names.len()); - for i in 0..col_names.len() { - let val = row.get_ref(i).map_err(|e| sqlite_error(&ctx, &e))?; - row_vals.push(rusqlite::types::Value::from(val)); - } - all_values.push(row_vals); - } - - IteratorState { - col_names, - values: all_values, - position: 0, - } - }; - - let mut iter_table = ITER_TABLE - .lock() - .map_err(|_| rquickjs::Exception::throw_message(&ctx, "iterator table lock poisoned"))?; - let id = iter_table.insert(state); - Ok(id) +) -> rquickjs::Result { + let guard = stmt.state.enter(&ctx)?; + if let Err(error) = stmt + .state + .begin(&ctx, ¶ms, allow_bare_named, allow_unknown_named) + { + return stmt.state.finish(&ctx, &guard.conn, Err(error)); + } + stmt.state.cursor.set(true); + Ok(NativeIterator { + state: stmt.state.clone(), + generation: stmt.state.generation.get(), + done: Cell::new(false), + }) } fn stmt_iterate_next_impl<'js>( ctx: rquickjs::Ctx<'js>, - iter_id: u32, + iter: &NativeIterator, read_big_ints: bool, return_arrays: bool, ) -> rquickjs::Result> { - let mut iter_table = ITER_TABLE - .lock() - .map_err(|_| rquickjs::Exception::throw_message(&ctx, "iterator table lock poisoned"))?; - - let state = iter_table - .iterators - .get_mut(&iter_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "invalid iterator id"))?; - - let result = rquickjs::Object::new(ctx.clone())?; - if state.position < state.values.len() { - let row_val = owned_row_to_js( + iter.state.pointer(&ctx)?; + let result = create_null_proto_object(&ctx)?; + if iter.done.get() { + result.set("value", rquickjs::Value::new_null(ctx.clone()))?; + result.set("done", true)?; + return Ok(result); + } + let guard = iter.state.enter(&ctx)?; + if iter.generation != iter.state.generation.get() { + return Err(throw_coded_error( &ctx, - &state.col_names, - &state.values[state.position], - return_arrays, - read_big_ints, + "Error", + "iterator was invalidated", + "ERR_INVALID_STATE", + )); + } + if iter.state.step(&ctx, &guard.conn)? { + result.set( + "value", + row_to_js(&ctx, iter.state.raw.get(), return_arrays, read_big_ints)?, )?; - state.position += 1; - result.set("value", row_val)?; result.set("done", false)?; } else { - // Clean up exhausted iterator to prevent leaks - iter_table.iterators.remove(&iter_id); - result.set("value", rquickjs::Value::new_undefined(ctx.clone()))?; + iter.done.set(true); + iter.state.finish(&ctx, &guard.conn, Ok(()))?; + result.set("value", rquickjs::Value::new_null(ctx.clone()))?; result.set("done", true)?; } Ok(result) } -fn stmt_iterate_return_impl<'js>(ctx: rquickjs::Ctx<'js>, iter_id: u32) -> rquickjs::Result<()> { - let mut iter_table = ITER_TABLE - .lock() - .map_err(|_| rquickjs::Exception::throw_message(&ctx, "iterator table lock poisoned"))?; - iter_table.iterators.remove(&iter_id); +fn stmt_iterate_return_impl<'js>( + ctx: rquickjs::Ctx<'js>, + iter: &NativeIterator, +) -> rquickjs::Result<()> { + iter.state.pointer(&ctx)?; + if !iter.done.get() { + let _guard = iter.state.enter(&ctx)?; + // Return must not replace a pending loop-body exception with reset's + // deferred SQLite error. Invalidation still prevents next() afterwards. + unsafe { + rusqlite::ffi::sqlite3_reset(iter.state.raw.get()); + } + iter.state.cursor.set(false); + iter.done.set(true); + take_pending_js_exception(&ctx); + } Ok(()) } @@ -1126,11 +1508,7 @@ fn register_function_impl<'js>( options.num_args }; - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; conn.create_scalar_function(&*name, n_arg, flags, move |fctx| { // SAFETY: The UDF closure is called synchronously during statement @@ -1336,11 +1714,7 @@ fn register_aggregate_impl<'js>( use_big_int_args: options.use_big_int_args, }; - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; conn.create_aggregate_function(&*name, n_arg, flags, aggr) .map_err(|e| sqlite_error(&ctx, &e))?; @@ -1354,18 +1728,14 @@ fn create_session_impl<'js>( table_name: rquickjs::Value<'js>, db_name: String, ) -> rquickjs::Result { - let conn_table = lock_conn_table(&ctx)?; - let conn = conn_table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; // SAFETY: Session internally stores raw pointers, not references. The // PhantomData<&'conn Connection> lifetime is a compile-time-only constraint. // We transmute to 'static because we guarantee the connection outlives the // session by tracking conn_id and cleaning up sessions when connections close. let mut session = unsafe { - let s = rusqlite::session::Session::new_with_name(conn, db_name.as_str()) + let s = rusqlite::session::Session::new_with_name(&conn, db_name.as_str()) .map_err(|e| sqlite_error(&ctx, &e))?; std::mem::transmute::, rusqlite::session::Session<'static>>( s, @@ -1383,8 +1753,6 @@ fn create_session_impl<'js>( .map_err(|e| sqlite_error(&ctx, &e))?; } - drop(conn_table); - let state = SessionState { session, conn_id }; let mut session_table = SESSION_TABLE .lock() @@ -1463,11 +1831,7 @@ fn apply_changeset_impl<'js>( ) -> rquickjs::Result { let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); - let conn_table = lock_conn_table(&ctx)?; - let conn = conn_table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; let bytes = crate::wrappers::copy_typed_array_bytes(&changeset) .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "detached TypedArray buffer"))?; @@ -1652,11 +2016,7 @@ fn enable_defensive_impl<'js>( conn_id: u32, active: bool, ) -> rquickjs::Result<()> { - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; conn.set_db_config( rusqlite::config::DbConfig::SQLITE_DBCONFIG_DEFENSIVE, active, @@ -1688,11 +2048,15 @@ fn set_authorizer_impl<'js>( conn_id: u32, callback: rquickjs::Value<'js>, ) -> rquickjs::Result<()> { - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; + if conn.in_authorizer.get() { + return Err(throw_coded_error( + &ctx, + "Error", + "database is busy", + "ERR_INVALID_STATE", + )); + } if callback.is_null() || callback.is_undefined() { let _ = conn.authorizer( @@ -1705,9 +2069,15 @@ fn set_authorizer_impl<'js>( rquickjs::Exception::throw_message(&ctx, "callback must be a function or null") })?; let persistent_fn = SendPersistent(rquickjs::Persistent::save(&ctx, func.clone())); + let weak_connection = Arc::downgrade(&conn); let _ = conn.authorizer(Some( move |auth_ctx: rusqlite::hooks::AuthContext<'_>| -> rusqlite::hooks::Authorization { + let Some(connection) = weak_connection.upgrade() else { + return rusqlite::hooks::Authorization::Deny; + }; + connection.in_authorizer.set(true); + let _guard = FlagGuard(&connection.in_authorizer); let js_ctx = match unsafe { get_udf_js_ctx() } { Ok(ctx) => ctx, Err(_) => return rusqlite::hooks::Authorization::Deny, @@ -1866,11 +2236,7 @@ fn serialize_database_impl<'js>( ctx: rquickjs::Ctx<'js>, conn_id: u32, ) -> rquickjs::Result> { - let table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; let data = conn .serialize(rusqlite::MAIN_DB) @@ -1888,11 +2254,26 @@ fn restore_database_impl<'js>( bytes: rquickjs::TypedArray<'js, u8>, ) -> rquickjs::Result<()> { crate::internal::preinit::check("SQLite database restore", "in-memory database"); - let mut table = lock_conn_table(&ctx)?; - let conn = table - .connections - .get_mut(&conn_id) - .ok_or_else(|| rquickjs::Exception::throw_message(&ctx, "database is not open"))?; + let conn = connection(&ctx, conn_id)?; + check_idle_connection( + &ctx, + &conn, + "cannot restore database during active execution", + )?; + if conn + .statements + .borrow() + .iter() + .filter_map(StatementWeak::upgrade) + .any(|s| s.cursor.get()) + { + return Err(throw_coded_error( + &ctx, + "Error", + "cannot restore database with an active cursor", + "ERR_INVALID_STATE", + )); + } if conn .is_readonly(rusqlite::MAIN_DB) @@ -1928,13 +2309,83 @@ fn restore_database_impl<'js>( .deserialize_read_exact(rusqlite::MAIN_DB, data, data.len(), false) .map_err(|e| sqlite_error(&ctx, &e))?; - let backup = - rusqlite::backup::Backup::new(&temp_conn, conn).map_err(|e| sqlite_error(&ctx, &e))?; - backup - .run_to_completion(100, Duration::ZERO, None) - .map_err(|e| sqlite_error(&ctx, &e))?; + // SAFETY: both connections are rooted, no execution/cursor is active, and + // backup invokes no JS. Unlike deserialize this preserves idle handles and + // connection-local UDFs. SQLite expires prepared statements after backup. + unsafe { + let backup = rusqlite::ffi::sqlite3_backup_init( + conn.handle(), + c"main".as_ptr(), + temp_conn.handle(), + c"main".as_ptr(), + ); + if backup.is_null() { + return check_sqlite(&ctx, &conn, rusqlite::ffi::sqlite3_errcode(conn.handle())); + } + let rc = rusqlite::ffi::sqlite3_backup_step(backup, -1); + let finished = rusqlite::ffi::sqlite3_backup_finish(backup); + check_sqlite( + &ctx, + &conn, + if rc == rusqlite::ffi::SQLITE_DONE { + finished + } else { + rc + }, + ) + } +} - Ok(()) +fn deserialize_database_impl<'js>( + ctx: rquickjs::Ctx<'js>, + conn_id: u32, + bytes: rquickjs::TypedArray<'js, u8>, + name: String, +) -> rquickjs::Result<()> { + crate::internal::preinit::check("SQLite database deserialize", "in-memory database"); + let conn = connection(&ctx, conn_id)?; + check_idle_connection( + &ctx, + &conn, + "database cannot be deserialized while in a callback", + )?; + let name = std::ffi::CString::new(name).map_err(|_| { + throw_coded_error(&ctx, "Error", "invalid database name", "ERR_SQLITE_ERROR") + })?; + let data = unsafe { bytes.as_bytes() }.ok_or_else(|| { + throw_coded_error( + &ctx, + "Error", + "The \"buffer\" argument was resized while reading \"options\"", + "ERR_INVALID_STATE", + ) + })?; + // SQLite takes ownership only of its own allocator's copy. Finalize before + // the deserialize attempt, not before validation/allocation, as Node does. + unsafe { + let buffer = rusqlite::ffi::sqlite3_malloc64(data.len() as u64).cast::(); + if buffer.is_null() { + return Err(rquickjs::Exception::throw_message( + &ctx, + "memory allocation failed", + )); + } + std::ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len()); + let _guard = JsCtxGuard::new(ctx.as_raw().as_ptr()); + conn.mutating.set(true); + let _mutation = FlagGuard(&conn.mutating); + finalize_statements(&conn); + let rc = rusqlite::ffi::sqlite3_deserialize( + conn.handle(), + name.as_ptr(), + buffer, + data.len() as i64, + data.len() as i64, + (rusqlite::ffi::SQLITE_DESERIALIZE_FREEONCLOSE + | rusqlite::ffi::SQLITE_DESERIALIZE_RESIZEABLE) as u32, + ); + check_sqlite(&ctx, &conn, rc) + } } fn native_backup_impl<'js>( @@ -1974,7 +2425,36 @@ fn native_backup_impl<'js>( #[rquickjs::module(rename = "camelCase")] pub mod native_module { - use rquickjs::{Array, Ctx, Object, Value}; + use super::{NativeIterator, NativeStatement}; + use rquickjs::{Array, Class, Ctx, Object, Value}; + + #[rquickjs::function] + pub fn prepare_statement<'js>( + ctx: Ctx<'js>, + conn_id: u32, + sql: String, + ) -> rquickjs::Result { + super::prepare_statement_impl(ctx, conn_id, sql) + } + + #[rquickjs::function] + pub fn deserialize_database<'js>( + ctx: Ctx<'js>, + conn_id: u32, + bytes: rquickjs::TypedArray<'js, u8>, + name: String, + ) -> rquickjs::Result<()> { + super::deserialize_database_impl(ctx, conn_id, bytes, name) + } + + #[rquickjs::function] + pub fn check_database_idle<'js>(ctx: Ctx<'js>, conn_id: u32) -> rquickjs::Result<()> { + super::check_idle_connection( + &ctx, + &super::connection(&ctx, conn_id)?, + "database cannot be deserialized while in a callback", + ) + } #[rquickjs::function] pub fn open_database<'js>( @@ -2018,8 +2498,7 @@ pub mod native_module { #[rquickjs::function] pub fn stmt_run<'js>( ctx: Ctx<'js>, - conn_id: u32, - sql: String, + stmt: Class<'js, NativeStatement>, params: Value<'js>, allow_bare_named: bool, allow_unknown_named: bool, @@ -2027,8 +2506,7 @@ pub mod native_module { ) -> rquickjs::Result> { super::stmt_run_impl( ctx, - conn_id, - sql, + &stmt.borrow(), params, allow_bare_named, allow_unknown_named, @@ -2041,8 +2519,7 @@ pub mod native_module { #[rquickjs::function] pub fn stmt_get<'js>( ctx: Ctx<'js>, - conn_id: u32, - sql: String, + stmt: Class<'js, NativeStatement>, params: Value<'js>, allow_bare_named: bool, allow_unknown_named: bool, @@ -2051,8 +2528,7 @@ pub mod native_module { ) -> rquickjs::Result> { super::stmt_get_impl( ctx, - conn_id, - sql, + &stmt.borrow(), params, super::StatementResultOptions { allow_bare_named, @@ -2068,8 +2544,7 @@ pub mod native_module { #[rquickjs::function] pub fn stmt_all<'js>( ctx: Ctx<'js>, - conn_id: u32, - sql: String, + stmt: Class<'js, NativeStatement>, params: Value<'js>, allow_bare_named: bool, allow_unknown_named: bool, @@ -2078,8 +2553,7 @@ pub mod native_module { ) -> rquickjs::Result> { super::stmt_all_impl( ctx, - conn_id, - sql, + &stmt.borrow(), params, super::StatementResultOptions { allow_bare_named, @@ -2093,36 +2567,30 @@ pub mod native_module { #[rquickjs::function] pub fn stmt_expanded_sql<'js>( ctx: Ctx<'js>, - conn_id: u32, - sql: String, - params: Value<'js>, - allow_bare_named: bool, + stmt: Class<'js, NativeStatement>, ) -> rquickjs::Result { - super::stmt_expanded_sql_impl(ctx, conn_id, sql, params, allow_bare_named) + super::stmt_expanded_sql_impl(ctx, &stmt.borrow()) } #[rquickjs::function] pub fn stmt_columns<'js>( ctx: Ctx<'js>, - conn_id: u32, - sql: String, + stmt: Class<'js, NativeStatement>, ) -> rquickjs::Result> { - super::stmt_columns_impl(ctx, conn_id, sql) + super::stmt_columns_impl(ctx, &stmt.borrow()) } #[rquickjs::function] pub fn stmt_iterate_init<'js>( ctx: Ctx<'js>, - conn_id: u32, - sql: String, + stmt: Class<'js, NativeStatement>, params: Value<'js>, allow_bare_named: bool, allow_unknown_named: bool, - ) -> rquickjs::Result { + ) -> rquickjs::Result { super::stmt_iterate_init_impl( ctx, - conn_id, - sql, + &stmt.borrow(), params, allow_bare_named, allow_unknown_named, @@ -2132,16 +2600,19 @@ pub mod native_module { #[rquickjs::function] pub fn stmt_iterate_next<'js>( ctx: Ctx<'js>, - iter_id: u32, + iter: Class<'js, NativeIterator>, read_big_ints: bool, return_arrays: bool, ) -> rquickjs::Result> { - super::stmt_iterate_next_impl(ctx, iter_id, read_big_ints, return_arrays) + super::stmt_iterate_next_impl(ctx, &iter.borrow(), read_big_ints, return_arrays) } #[rquickjs::function] - pub fn stmt_iterate_return<'js>(ctx: Ctx<'js>, iter_id: u32) -> rquickjs::Result<()> { - super::stmt_iterate_return_impl(ctx, iter_id) + pub fn stmt_iterate_return<'js>( + ctx: Ctx<'js>, + iter: Class<'js, NativeIterator>, + ) -> rquickjs::Result<()> { + super::stmt_iterate_return_impl(ctx, &iter.borrow()) } // These positional arguments are the public rquickjs bridge ABI consumed by sqlite.js. diff --git a/examples/runtime/sqlite/src/sqlite.js b/examples/runtime/sqlite/src/sqlite.js index 4e5666fad..8a57acf62 100644 --- a/examples/runtime/sqlite/src/sqlite.js +++ b/examples/runtime/sqlite/src/sqlite.js @@ -374,3 +374,167 @@ export function testNumberBinding() { } return true; } + +export function testStatementLifetime() { + const db = new DatabaseSync(':memory:'); + try { + assert.throws(() => db.prepare('SELECT missing FROM absent'), { code: 'ERR_SQLITE_ERROR' }); + db.exec('CREATE TABLE entries (n); INSERT INTO entries VALUES (13), (29), (41)'); + const query = db.prepare('SELECT n FROM entries ORDER BY n'); + const iterator = query.iterate(); + assert.deepEqual(iterator.next(), { + __proto__: null, done: false, value: { __proto__: null, n: 13 }, + }); + query.get(); + assert.throws(() => iterator.next(), { code: 'ERR_INVALID_STATE', message: 'iterator was invalidated' }); + const second = query.iterate(); + assert.equal(second.next().value.n, 13); + assert.deepEqual(second.return(), { __proto__: null, done: true, value: null }); + assert.deepEqual(second.next(), { __proto__: null, done: true, value: null }); + assert.deepEqual(query.all().map(row => row.n), [13, 29, 41]); + assert.equal(query.close(), undefined); + const finalized = { code: 'ERR_INVALID_STATE', message: 'statement has been finalized' }; + for (const action of [() => query.get(), () => query.sourceSQL, () => query.expandedSQL, + () => query.close(), () => query.setReadBigInts(false), () => second.next()]) { + assert.throws(action, finalized); + } + query[Symbol.dispose](); + const beforeClose = db.prepare('SELECT 7 AS n'); + db.close(); + assert.throws(() => beforeClose.get(), finalized); + db.open(); + assert.throws(() => beforeClose.get(), finalized); + assert.equal(db.prepare('SELECT 11 AS n').get().n, 11); + } finally { + if (db.isOpen) db.close(); + } + return true; +} + +export function testStatementStatistics() { + const db = new DatabaseSync(':memory:'); + try { + db.exec('CREATE TABLE entries (id INTEGER PRIMARY KEY, value TEXT); INSERT INTO entries VALUES (13, \'pear\'), (29, \'plum\'), (41, \'pear\')'); + const scan = db.prepare('SELECT * FROM entries WHERE value = ?'); + const indexed = db.prepare('SELECT * FROM entries WHERE id = ?'); + assert.equal(scan.stat('run'), 0); + assert.equal(scan.stat('vmStep'), 0); + assert.deepEqual(scan.all('pear').map(row => row.id), [13, 41]); + assert.equal(scan.stat('run'), 1); + assert.ok(scan.stat('vmStep') > 0); + assert.ok(scan.stat('fullscanStep') > 0); + assert.equal(indexed.get(29).value, 'plum'); + assert.equal(indexed.stat('fullscanStep'), 0); + const memory = scan.stat('memused'); + assert.ok(memory > 0); + const steps = scan.stat('vmStep'); + assert.equal(scan.stat('vmStep'), steps); + scan.resetStats(); + assert.equal(scan.stat('run'), 0); + assert.equal(scan.stat('vmStep'), 0); + assert.equal(scan.stat('memused'), memory); + scan.all('plum'); + assert.equal(scan.stat('run'), 1); + assert.throws(() => scan.stat(1), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => scan.stat('unknown'), { code: 'ERR_INVALID_ARG_VALUE' }); + } finally { + db.close(); + } + return true; +} + +export function testStatementRecovery() { + const db = new DatabaseSync(':memory:'); + const source = new DatabaseSync(':memory:'); + try { + db.exec('CREATE TABLE items (old INTEGER); INSERT INTO items VALUES (13), (29)'); + source.exec("CREATE TABLE items (replacement INTEGER, label TEXT); INSERT INTO items VALUES (41, 'pear'), (53, 'plum')"); + const image = serializeDatabaseSync(source); + db.function('twice', n => n * 2); + const query = db.prepare('SELECT * FROM items WHERE $pick IS NOT NULL ORDER BY 1', { + readBigInts: true, returnArrays: true, allowBareNamedParameters: false, + allowUnknownNamedParameters: true, + }); + assert.deepEqual(query.all({ $pick: 1, ignored: 2 }), [[13n], [29n]]); + const cursor = query.iterate({ $pick: 1 }); + assert.deepEqual(cursor.next().value, [13n]); + assert.throws(() => restoreDatabaseSync(db, image), { code: 'ERR_INVALID_STATE' }); + assert.deepEqual(cursor.next().value, [29n]); + assert.deepEqual(db.prepare('SELECT old FROM items ORDER BY old').all().map(row => row.old), [13, 29]); + cursor.return(); + restoreDatabaseSync(db, image); + assert.equal(db.isOpen, true); + assert.deepEqual(query.all({ $pick: 1, ignored: 2 }), [[41n, 'pear'], [53n, 'plum']]); + assert.equal(query.get({ pick: 1 }), undefined); + query.setAllowUnknownNamedParameters(false); + assert.throws(() => query.get({ pick: 1 }), { code: 'ERR_INVALID_STATE' }); + query.setReturnArrays(false); + assert.deepEqual(query.get({ $pick: 1 }), { __proto__: null, replacement: 41n, label: 'pear' }); + assert.equal(db.prepare('SELECT twice(replacement) AS n FROM items ORDER BY replacement').get().n, 82); + // The attempted image must differ from live state, so rejection alone + // cannot hide a recovery that mutated the database before throwing. + db.exec('UPDATE items SET replacement = replacement + 100'); + let calls = 0; + db.function('try_restore', () => { + calls++; + assert.throws(() => restoreDatabaseSync(db, image), { code: 'ERR_INVALID_STATE' }); + return 7; + }); + assert.deepEqual(db.prepare('SELECT replacement, try_restore() AS n FROM items ORDER BY replacement').all() + .map(row => [row.replacement, row.n]), [[141, 7], [153, 7]]); + assert.equal(calls, 2); + assert.deepEqual(db.prepare('SELECT replacement FROM items ORDER BY replacement').all() + .map(row => row.replacement), [141, 153]); + } finally { + db.close(); + source.close(); + } + return true; +} + +export function testStatementDeserialize() { + const db = new DatabaseSync(':memory:'); + const source = new DatabaseSync(':memory:'); + try { + db.exec('CREATE TABLE items (n); INSERT INTO items VALUES (13), (29)'); + source.exec('CREATE TABLE items (n); INSERT INTO items VALUES (41), (53)'); + const image = serializeDatabaseSync(source); + let byteLengthReads = 0; + Object.defineProperty(image, 'byteLength', { get() { + byteLengthReads++; + throw new Error('deserialize must read the intrinsic byte length'); + } }); + const idle = db.prepare('SELECT n FROM items'); + const cursor = db.prepare('SELECT n FROM items').iterate(); + assert.equal(cursor.next().value.n, 13); + db.deserialize(image); + assert.equal(byteLengthReads, 0); + const finalized = { code: 'ERR_INVALID_STATE', message: 'statement has been finalized' }; + assert.throws(() => idle.get(), finalized); + assert.throws(() => cursor.next(), finalized); + assert.deepEqual(db.prepare('SELECT n FROM items ORDER BY n').all().map(row => row.n), [41, 53]); + const beforeFailure = db.prepare('SELECT 17 AS n'); + assert.throws(() => db.deserialize(image, { dbName: 'missing' }), { code: 'ERR_SQLITE_ERROR' }); + assert.throws(() => beforeFailure.get(), finalized); + let running; + const independent = db.prepare('SELECT 19 AS n'); + db.function('reenter', () => { + assert.throws(() => running.get(), { code: 'ERR_INVALID_STATE' }); + assert.throws(() => running.close(), { code: 'ERR_INVALID_STATE' }); + assert.throws(() => db.deserialize(image), { code: 'ERR_INVALID_STATE' }); + assert.throws(() => db.close(), { code: 'ERR_INVALID_STATE' }); + return independent.get().n; + }); + running = db.prepare('SELECT reenter() AS n'); + assert.equal(running.get().n, 19); + const sentinel = new Error('loop body'); + const live = independent.iterate(); + assert.throws(() => { for (const row of live) { assert.equal(row.n, 19); throw sentinel; } }, error => error === sentinel); + assert.deepEqual(live.next(), { __proto__: null, done: true, value: null }); + assert.equal(independent.get().n, 19); + } finally { + db.close(); + source.close(); + } + return true; +} diff --git a/examples/runtime/sqlite/wit/sqlite.wit b/examples/runtime/sqlite/wit/sqlite.wit index 2a9a0cefe..c4880859c 100644 --- a/examples/runtime/sqlite/wit/sqlite.wit +++ b/examples/runtime/sqlite/wit/sqlite.wit @@ -14,4 +14,8 @@ world sqlite { export test-prepare-options: func() -> bool; export test-transaction-state: func() -> bool; export test-number-binding: func() -> bool; + export test-statement-lifetime: func() -> bool; + export test-statement-statistics: func() -> bool; + export test-statement-recovery: func() -> bool; + export test-statement-deserialize: func() -> bool; } diff --git a/tests/runtime/sqlite.rs b/tests/runtime/sqlite.rs index e5234207b..66b502227 100644 --- a/tests/runtime/sqlite.rs +++ b/tests/runtime/sqlite.rs @@ -236,3 +236,67 @@ async fn sqlite_test_number_binding( assert_eq!(r?, Some(Val::Bool(true))); Ok(()) } + +#[test] +async fn sqlite_test_statement_lifetime( + #[tagged_as("sqlite")] compiled_test: &CompiledTest, +) -> anyhow::Result<()> { + let (r, output) = invoke_and_capture_output( + compiled_test.wasm_path(), + None, + "test-statement-lifetime", + &[], + ) + .await; + println!("Output:\n{}", output); + assert_eq!(r?, Some(Val::Bool(true))); + Ok(()) +} + +#[test] +async fn sqlite_test_statement_statistics( + #[tagged_as("sqlite")] compiled_test: &CompiledTest, +) -> anyhow::Result<()> { + let (r, output) = invoke_and_capture_output( + compiled_test.wasm_path(), + None, + "test-statement-statistics", + &[], + ) + .await; + println!("Output:\n{}", output); + assert_eq!(r?, Some(Val::Bool(true))); + Ok(()) +} + +#[test] +async fn sqlite_test_statement_recovery( + #[tagged_as("sqlite")] compiled_test: &CompiledTest, +) -> anyhow::Result<()> { + let (r, output) = invoke_and_capture_output( + compiled_test.wasm_path(), + None, + "test-statement-recovery", + &[], + ) + .await; + println!("Output:\n{}", output); + assert_eq!(r?, Some(Val::Bool(true))); + Ok(()) +} + +#[test] +async fn sqlite_test_statement_deserialize( + #[tagged_as("sqlite")] compiled_test: &CompiledTest, +) -> anyhow::Result<()> { + let (r, output) = invoke_and_capture_output( + compiled_test.wasm_path(), + None, + "test-statement-deserialize", + &[], + ) + .await; + println!("Output:\n{}", output); + assert_eq!(r?, Some(Val::Bool(true))); + Ok(()) +} From 4bece465c7dae6aa0b0afbe9b7d6972ba49d4c90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Wed, 25 Nov 2026 14:50:53 +0000 Subject: [PATCH 2/3] Preserve newer SQLite cursor guards [skip ci] --- .../wasm-rquickjs/skeleton/src/builtin/sqlite.rs | 6 +++++- examples/runtime/sqlite/src/sqlite.js | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs index 00e7244c6..76aa115ed 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs @@ -1362,7 +1362,11 @@ fn stmt_iterate_return_impl<'js>( unsafe { rusqlite::ffi::sqlite3_reset(iter.state.raw.get()); } - iter.state.cursor.set(false); + // Node resets even for a stale iterator, but it must not clear the + // recovery guard owned by a newer, still-live iterator. + if iter.generation == iter.state.generation.get() { + iter.state.cursor.set(false); + } iter.done.set(true); take_pending_js_exception(&ctx); } diff --git a/examples/runtime/sqlite/src/sqlite.js b/examples/runtime/sqlite/src/sqlite.js index 8a57acf62..bdd447727 100644 --- a/examples/runtime/sqlite/src/sqlite.js +++ b/examples/runtime/sqlite/src/sqlite.js @@ -456,8 +456,16 @@ export function testStatementRecovery() { allowUnknownNamedParameters: true, }); assert.deepEqual(query.all({ $pick: 1, ignored: 2 }), [[13n], [29n]]); + const stale = query.iterate({ $pick: 1 }); + assert.deepEqual(stale.next().value, [13n]); const cursor = query.iterate({ $pick: 1 }); assert.deepEqual(cursor.next().value, [13n]); + stale.return(); + // Node 26 resets the shared statement even for an older iterator's return. + // Recovery must nevertheless reject while the newer iterator remains live. + assert.throws(() => restoreDatabaseSync(db, image), { code: 'ERR_INVALID_STATE' }); + assert.deepEqual(db.prepare('SELECT old FROM items ORDER BY old').all().map(row => row.old), [13, 29]); + assert.deepEqual(cursor.next().value, [13n]); assert.throws(() => restoreDatabaseSync(db, image), { code: 'ERR_INVALID_STATE' }); assert.deepEqual(cursor.next().value, [29n]); assert.deepEqual(db.prepare('SELECT old FROM items ORDER BY old').all().map(row => row.old), [13, 29]); @@ -471,6 +479,13 @@ export function testStatementRecovery() { query.setReturnArrays(false); assert.deepEqual(query.get({ $pick: 1 }), { __proto__: null, replacement: 41n, label: 'pear' }); assert.equal(db.prepare('SELECT twice(replacement) AS n FROM items ORDER BY replacement').get().n, 82); + const completedQuery = db.prepare('SELECT replacement FROM items ORDER BY replacement'); + const older = completedQuery.iterate(); + assert.equal(older.next().value.replacement, 41); + assert.deepEqual([...completedQuery.iterate()].map(row => row.replacement), [41, 53]); + older.return(); + // A stale return must not resurrect a cursor after the newer one drained. + restoreDatabaseSync(db, image); // The attempted image must differ from live state, so rejection alone // cannot hide a recovery that mutated the database before throwing. db.exec('UPDATE items SET replacement = replacement + 100'); From 6a3310eb00851d3b7600f3f3784f3ae1177a8bc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 10:45:39 +0000 Subject: [PATCH 3/3] Fix SQLite binding errors and hidden keys --- .../skeleton/src/builtin/sqlite.rs | 20 +++++------ examples/runtime/sqlite/src/sqlite.js | 33 +++++++++++++++++++ .../generated_types_sqlite_exports.d.ts | 4 +++ 3 files changed, 45 insertions(+), 12 deletions(-) diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs index 76aa115ed..78e7c24f8 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/sqlite.rs @@ -206,7 +206,7 @@ impl StatementState { let rc = unsafe { rusqlite::ffi::sqlite3_reset(self.raw.get()) }; let conn = self.connection.upgrade().unwrap(); check_sqlite(ctx, &conn, rc)?; - bind_params(ctx, self.raw.get(), params, bare, unknown) + bind_params(ctx, &conn, self.raw.get(), params, bare, unknown) } fn step<'js>( @@ -901,6 +901,7 @@ fn finalize_statements(conn: &SqliteConnection) { fn bind_params<'js>( ctx: &rquickjs::Ctx<'js>, + conn: &SqliteConnection, stmt: *mut rusqlite::ffi::sqlite3_stmt, params: &rquickjs::Value<'js>, allow_bare_named: bool, @@ -918,7 +919,7 @@ fn bind_params<'js>( if let Some(arr) = params.as_array() { for i in 0..arr.len() { let val: rquickjs::Value<'js> = arr.get(i)?; - bind_value(ctx, stmt, i + 1, &val)?; + bind_value(ctx, conn, stmt, i + 1, &val)?; } } else if params.is_object() { let obj = params.as_object().ok_or_else(|| { @@ -951,7 +952,7 @@ fn bind_params<'js>( // Enumerate keys without reading values: ignored unknown keys must not // invoke getters, and recognized getters run exactly once. let keys: Vec = obj - .own_keys(rquickjs::object::Filter::new().string()) + .own_keys(rquickjs::object::Filter::default()) .collect::>()?; for key in keys { let name = std::ffi::CString::new(key.as_str()).ok(); @@ -973,7 +974,7 @@ fn bind_params<'js>( )); } let val = obj.get(key)?; - bind_value(ctx, stmt, idx as usize, &val)?; + bind_value(ctx, conn, stmt, idx as usize, &val)?; } } Ok(()) @@ -981,6 +982,7 @@ fn bind_params<'js>( fn bind_value<'js>( ctx: &rquickjs::Ctx<'js>, + conn: &SqliteConnection, stmt: *mut rusqlite::ffi::sqlite3_stmt, index: usize, val: &rquickjs::Value<'js>, @@ -1011,13 +1013,7 @@ fn bind_value<'js>( ), } }; - if rc != ffi::SQLITE_OK { - return Err(sqlite_error( - ctx, - &rusqlite::Error::SqliteFailure(ffi::Error::new(rc), None), - )); - } - Ok(()) + check_sqlite(ctx, conn, rc) } fn open_database_impl<'js>( @@ -1118,7 +1114,7 @@ fn exec_sql_impl<'js>(ctx: rquickjs::Ctx<'js>, conn_id: u32, sql: String) -> rqu )); } conn.execute_batch(&sql) - .map_err(|e| sqlite_error(&ctx, &e))?; + .map_err(|e| map_sqlite_or_udf_error(&ctx, e))?; Ok(()) } diff --git a/examples/runtime/sqlite/src/sqlite.js b/examples/runtime/sqlite/src/sqlite.js index 6e75fbe1c..a5c6528ef 100644 --- a/examples/runtime/sqlite/src/sqlite.js +++ b/examples/runtime/sqlite/src/sqlite.js @@ -386,6 +386,20 @@ export function testNumberBinding() { assert.deepEqual(db.prepare('SELECT ? AS n, typeof(?) AS kind', { readBigInts: true, }).get(-0, -0), { __proto__: null, n: -0, kind: 'real' }); + let reads = 0; + const params = Object.create({ $inherited: 41 }); + Object.defineProperties(params, { + $left: { get() { throw new Error('hidden matching getter must not run'); } }, + $unknown: { get() { throw new Error('hidden unknown getter must not run'); } }, + $right: { enumerable: true, get() { reads++; return 29; } }, + }); + const named = db.prepare('SELECT $left AS x, $right AS y'); + const row = { __proto__: null, x: null, y: 29 }; + assert.deepEqual(named.get(params), row); + assert.deepEqual(named.all(params), [row]); + assert.deepEqual([...named.iterate(params)], [row]); + assert.deepEqual(named.run(params), { changes: 1, lastInsertRowid: 1 }); + assert.equal(reads, 4); } finally { db.close(); } @@ -395,9 +409,28 @@ export function testNumberBinding() { export function testStatementLifetime() { const db = new DatabaseSync(':memory:'); try { + const udfError = new Error('udf sentinel'); + db.function('boom', () => { throw udfError; }); + let execError; + try { db.exec('SELECT boom()'); } catch (error) { execError = error; } + const parameter = db.prepare('SELECT ? AS n'); + assert.throws(() => parameter.get(1, 2), { + code: 'ERR_SQLITE_ERROR', message: 'column index out of range', + errcode: 25, errstr: 'column index out of range', + }); + assert.equal(parameter.get(7).n, 7); + assert.equal(execError, udfError); assert.throws(() => db.prepare('SELECT missing FROM absent'), { code: 'ERR_SQLITE_ERROR' }); db.exec('CREATE TABLE entries (n); INSERT INTO entries VALUES (13), (29), (41)'); const query = db.prepare('SELECT n FROM entries ORDER BY n'); + for (const invoke of [() => query.get(7), () => query.all(7), + () => [...query.iterate(7)], () => query.run(7)]) { + assert.throws(invoke, { + code: 'ERR_SQLITE_ERROR', message: 'column index out of range', + errcode: 25, errstr: 'column index out of range', + }); + assert.equal(query.get().n, 13); + } const iterator = query.iterate(); assert.deepEqual(iterator.next(), { __proto__: null, done: false, value: { __proto__: null, n: 13 }, diff --git a/tests/goldenfiles/generated_types_sqlite_exports.d.ts b/tests/goldenfiles/generated_types_sqlite_exports.d.ts index ad4333526..6022a49f7 100644 --- a/tests/goldenfiles/generated_types_sqlite_exports.d.ts +++ b/tests/goldenfiles/generated_types_sqlite_exports.d.ts @@ -12,4 +12,8 @@ declare module 'sqlite' { export function testPrepareOptions(): boolean; export function testTransactionState(): boolean; export function testNumberBinding(): boolean; + export function testStatementLifetime(): boolean; + export function testStatementStatistics(): boolean; + export function testStatementRecovery(): boolean; + export function testStatementDeserialize(): boolean; }