use wasm_bindgen::prelude::*;
use crate::{Database, PreparedStatement as EnginePreparedStatement};
#[wasm_bindgen]
pub struct Db {
inner: Database,
}
#[wasm_bindgen]
pub struct PreparedStatement {
inner: EnginePreparedStatement,
}
#[wasm_bindgen]
impl PreparedStatement {
#[wasm_bindgen(getter, js_name = parameterCount)]
pub fn parameter_count(&self) -> u32 {
self.inner.parameter_count() as u32
}
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 {
#[wasm_bindgen(constructor)]
#[allow(clippy::new_without_default)]
pub fn new() -> Db {
console_error_panic_hook::set_once();
Db {
inner: Database::open_memory(),
}
}
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)
}
#[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()))
}
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()))
}
pub fn export(&mut self) -> Result<Vec<u8>, JsValue> {
self.inner
.bake_to_bytes()
.map_err(|e| JsValue::from_str(&e.to_string()))
}
#[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()))
}
#[wasm_bindgen(js_name = currentTx)]
pub fn current_tx(&self) -> u32 {
self.inner.current_tx() as u32
}
#[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}}}"))
}
#[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()))
}
#[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()))
}
#[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()))
}
#[wasm_bindgen(js_name = inTransaction)]
pub fn in_transaction(&self) -> bool {
self.inner.in_transaction()
}
pub fn tables(&self) -> Result<String, JsValue> {
serde_json::to_string(&self.inner.table_names())
.map_err(|e| JsValue::from_str(&e.to_string()))
}
#[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(¶ms) {
return Err(JsValue::from_str(
"prepared statement parameters must be an array",
));
}
js_sys::Array::from(¶ms)
.iter()
.map(|item| js_to_value(&item))
.collect()
}
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)
}
}
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"))
}
}