picovolt 2.2.0

Embedded SQL database with MVCC history and single-file deployment
Documentation
// Modified for PicoVolt 2.1.0 retrieval, 2026-09-11. See legal/COMPONENT-SCOPE-2.1.md.
//! WebAssembly / npm bindings (enabled by the `wasm` feature).
//!
//! Exposes an **in-memory** PicoVolt database to JavaScript via `wasm-bindgen`.
//! The filesystem/mmap backends don't work in a browser, so the wasm build uses
//! [`Database::open_memory`]; export with [`crate::wasm_api::Db::export`] to get
//! a `.pvdb` image.
//!
//! Build the npm package with:
//! `wasm-pack build --target web --release -- --features wasm`

use wasm_bindgen::prelude::*;

use crate::{Database, PreparedStatement as EnginePreparedStatement};

/// An in-memory PicoVolt database usable from JavaScript.
#[wasm_bindgen]
pub struct Db {
    inner: Database,
}

/// A validated, reusable SQL template for the raw WebAssembly API.
#[wasm_bindgen]
pub struct PreparedStatement {
    inner: EnginePreparedStatement,
}

#[wasm_bindgen]
impl PreparedStatement {
    /// Number of positional `?` values required by this statement.
    #[wasm_bindgen(getter, js_name = parameterCount)]
    pub fn parameter_count(&self) -> u32 {
        self.inner.parameter_count() as u32
    }

    /// Execute this statement against `db`, returning the same JSON string as
    /// [`Db::query`]. The statement can be reused with different parameters.
    pub fn execute(&self, db: &mut Db, params: JsValue) -> Result<String, JsValue> {
        let values = js_params_to_values(params)?;
        let result = self
            .inner
            .execute(&mut db.inner, &values)
            .map_err(|error| JsValue::from_str(&error.to_string()))?;
        result_to_string(&result)
    }
}

#[wasm_bindgen]
impl Db {
    /// Create a new, empty in-memory database.
    #[wasm_bindgen(constructor)]
    #[allow(clippy::new_without_default)]
    pub fn new() -> Db {
        console_error_panic_hook::set_once();
        Db {
            inner: Database::open_memory(),
        }
    }

    /// Run one SQL statement, optionally binding `?` placeholders to `params` (a
    /// JS array, e.g. `db.query("SELECT * FROM t WHERE id = ?", [1])`). Returns a
    /// **JSON string** (call `JSON.parse` in JS): `{"columns":[...],"rows":[[...]]}`
    /// for `SELECT`, `{"mutated":n}` for `INSERT`/`UPDATE`/`DELETE`, or
    /// `{"done":true}` otherwise. Throws the error message (a string) on failure.
    pub fn query(&mut self, sql: &str, params: JsValue) -> Result<String, JsValue> {
        let result = if params.is_undefined() || params.is_null() {
            self.inner.query(sql)
        } else {
            let values = js_params_to_values(params)?;
            self.inner.query_with(sql, &values)
        }
        .map_err(|e| JsValue::from_str(&e.to_string()))?;
        result_to_string(&result)
    }

    /// Bounded full-text/vector retrieval over a SELECT snapshot. Request/result are JSON.
    #[cfg(any(feature = "full-text", feature = "vector-search"))]
    pub fn retrieve(&mut self, request: &str) -> Result<String, JsValue> {
        self.inner
            .retrieve_json(request)
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Validate and retain a reusable SQL template. Preparation verifies the
    /// syntax and records the exact positional-parameter count without running
    /// the statement.
    pub fn prepare(&self, sql: &str) -> Result<PreparedStatement, JsValue> {
        self.inner
            .prepare(sql)
            .map(|inner| PreparedStatement { inner })
            .map_err(|error| JsValue::from_str(&error.to_string()))
    }

    /// Export the whole database as a `.pvdb` byte image (a `Uint8Array` in JS).
    pub fn export(&mut self) -> Result<Vec<u8>, JsValue> {
        self.inner
            .bake_to_bytes()
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Load a database from a `.pvdb` byte image (e.g. one produced by
    /// [`export`](Db::export)). Writable, with full time-travel history intact.
    #[wasm_bindgen(js_name = fromBytes)]
    pub fn from_bytes(bytes: &[u8]) -> Result<Db, JsValue> {
        console_error_panic_hook::set_once();
        Database::import_bytes(bytes)
            .map(|inner| Db { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// The most recently committed transaction id, the upper bound for a
    /// `... BEFORE tx` time-travel query.
    #[wasm_bindgen(js_name = currentTx)]
    pub fn current_tx(&self) -> u32 {
        self.inner.current_tx() as u32
    }

    /// Atomically execute an INSERT/UPDATE/DELETE for an array of parameter arrays.
    #[wasm_bindgen(js_name = executeMany)]
    pub fn execute_many(&mut self, sql: &str, rows: JsValue) -> Result<String, JsValue> {
        if !js_sys::Array::is_array(&rows) {
            return Err(JsValue::from_str(
                "executeMany expects an array of parameter arrays",
            ));
        }
        let rows = js_sys::Array::from(&rows)
            .iter()
            .map(js_params_to_values)
            .collect::<Result<Vec<_>, _>>()?;
        let count = self
            .inner
            .execute_many(sql, &rows)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(format!("{{\"mutated\":{count}}}"))
    }

    /// Begin an explicit multi-statement in-memory transaction.
    #[wasm_bindgen(js_name = beginTransaction)]
    pub fn begin_transaction(&mut self) -> Result<(), JsValue> {
        self.inner
            .begin_transaction()
            .map_err(|error| JsValue::from_str(&error.to_string()))
    }

    /// Commit the active transaction.
    #[wasm_bindgen(js_name = commitTransaction)]
    pub fn commit_transaction(&mut self) -> Result<(), JsValue> {
        self.inner
            .commit_transaction()
            .map_err(|error| JsValue::from_str(&error.to_string()))
    }

    /// Roll back the active transaction.
    #[wasm_bindgen(js_name = rollbackTransaction)]
    pub fn rollback_transaction(&mut self) -> Result<(), JsValue> {
        self.inner
            .rollback_transaction()
            .map_err(|error| JsValue::from_str(&error.to_string()))
    }

    /// Whether an explicit transaction is active.
    #[wasm_bindgen(js_name = inTransaction)]
    pub fn in_transaction(&self) -> bool {
        self.inner.in_transaction()
    }

    /// A JSON array of the table names in this database (for introspecting an
    /// uploaded `.pvdb` whose schema is unknown).
    pub fn tables(&self) -> Result<String, JsValue> {
        serde_json::to_string(&self.inner.table_names())
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Open a baked `.pvdb` served over HTTP **without downloading it whole**:
    /// `read(offset, len)` must synchronously return a `Uint8Array` of that byte
    /// range (e.g. a synchronous range request). Pages are then fetched on demand
    /// as queries touch them. `totalSize` is the image's byte length.
    #[wasm_bindgen(js_name = openRemote)]
    pub fn open_remote(read: js_sys::Function, total_size: f64) -> Result<Db, JsValue> {
        console_error_panic_hook::set_once();
        const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
        if !total_size.is_finite()
            || total_size.fract() != 0.0
            || total_size < crate::FILE_HEADER_SIZE as f64
            || total_size > MAX_SAFE_INTEGER
            || total_size > usize::MAX as f64
        {
            return Err(JsValue::from_str(
                "totalSize must be a finite, exact, platform-sized byte length",
            ));
        }
        let reader = Box::new(JsRangeReader { read });
        Database::open_streamed(reader, total_size as u64)
            .map(|inner| Db { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }
}

fn result_to_string(result: &crate::QueryResult) -> Result<String, JsValue> {
    crate::json::result_to_string(result).map_err(|error| JsValue::from_str(&error.to_string()))
}

fn js_params_to_values(params: JsValue) -> Result<Vec<crate::Value>, JsValue> {
    if params.is_undefined() || params.is_null() {
        return Ok(Vec::new());
    }
    if !js_sys::Array::is_array(&params) {
        return Err(JsValue::from_str(
            "prepared statement parameters must be an array",
        ));
    }
    js_sys::Array::from(&params)
        .iter()
        .map(|item| js_to_value(&item))
        .collect()
}

/// Bridges the engine's [`RangeReader`](crate::storage::vle::RangeReader) to a
/// JavaScript callback that returns a `Uint8Array` for a byte range.
struct JsRangeReader {
    read: js_sys::Function,
}

impl crate::storage::vle::RangeReader for JsRangeReader {
    fn read_at(&self, offset: u64, len: usize) -> crate::Result<Vec<u8>> {
        use wasm_bindgen::JsCast;
        let res = self
            .read
            .call2(
                &JsValue::NULL,
                &JsValue::from_f64(offset as f64),
                &JsValue::from_f64(len as f64),
            )
            .map_err(|e| crate::PvError::Corruption(format!("range read failed: {e:?}")))?;
        let arr: js_sys::Uint8Array = res.dyn_into().map_err(|_| {
            crate::PvError::Corruption("range reader did not return a Uint8Array".into())
        })?;
        let bytes = arr.to_vec();
        if bytes.len() != len {
            return Err(crate::PvError::Corruption(format!(
                "range reader returned {} bytes; expected {len}",
                bytes.len()
            )));
        }
        Ok(bytes)
    }
}

/// Convert a JavaScript parameter into a PicoVolt `Value`: null/undefined to
/// Null, boolean to 0/1, string to Text, an integral number to Int, and a
/// fractional number to a fixed-point decimal.
fn js_to_value(v: &JsValue) -> Result<crate::Value, JsValue> {
    use crate::Value;
    if v.is_null() || v.is_undefined() {
        Ok(Value::Null)
    } else if let Some(b) = v.as_bool() {
        Ok(Value::Int(if b { 1 } else { 0 }))
    } else if let Some(s) = v.as_string() {
        Ok(Value::Text(s))
    } else if let Some(n) = v.as_f64() {
        if n.fract() == 0.0 && n.abs() < 9.007e15 {
            Ok(Value::Int(n as i64))
        } else {
            Ok(Value::Decimal((n * 1_000_000.0).round() as i128))
        }
    } else {
        Err(JsValue::from_str("unsupported SQL parameter type"))
    }
}