#sqlite #javascript #worker-thread #sqlite-wasm

sqlite-wasm-rs

Wrap sqlite-wasm, and expect to provide a usable C-like API

1 unstable release

new 0.1.3 Jan 10, 2025
0.1.2 Jan 9, 2025
0.1.1 Jan 5, 2025
0.1.0 Dec 29, 2024

#151 in WebAssembly

Download history 171/week @ 2024-12-28 319/week @ 2025-01-04

490 downloads per month

MIT license

1MB
18K SLoC

JavaScript 14K SLoC // 0.0% comments TypeScript 2.5K SLoC // 0.7% comments Rust 2K SLoC // 0.1% comments

SQLite Wasm Rust

Wrap the official sqlite-wasm, and expect to provide a usable C-like API.

Usage

use sqlite_wasm_rs::export as ffi;
use std::ffi::CString;

async fn open_db() -> anyhow::Result<()> {
    // Before using CAPI, you must initialize sqlite.
    //
    // Initializing the database is a one-time operation during
    // the life of the program.
    let sqlite = ffi::init_sqlite().await?;

    let mut db = std::ptr::null_mut();
    let filename = CString::new("mydb").unwrap();
    // Persistent Storage is supported, use opfs vfs.
    // This support is only available when sqlite is loaded from a
    // Worker thread, whether it's loaded in its own dedicated worker
    // or in a worker together with client code.
    //
    // See <https://sqlite.org/wasm/doc/trunk/persistence.md#opfs>
    let vfs = CString::new("opfs").unwrap();
    let ret = unsafe {
        ffi::sqlite3_open_v2(
            filename.as_ptr(),
            &mut db as *mut _,
            ffi::SQLITE_OPEN_READWRITE | ffi::SQLITE_OPEN_CREATE,
            // Using std::ptr::null() is a memory DB
            vfs.as_ptr(),
        )
    };
    assert_eq!(ffi::SQLITE_OK, ret);

    // support `opfs-sahpool` vfs
    //
    // See <https://sqlite.org/wasm/doc/trunk/persistence.md#vfs-opfs-sahpool>
    sqlite.install_opfs_sahpool(None).await?;

    let mut db = std::ptr::null_mut();
    let filename = CString::new("mydb").unwrap();
    let vfs = CString::new("opfs-sahpool").unwrap();
    let ret = unsafe {
        ffi::sqlite3_open_v2(
            filename.as_ptr(),
            &mut db as *mut _,
            ffi::SQLITE_OPEN_READWRITE | ffi::SQLITE_OPEN_CREATE,
            vfs.as_ptr(),
        )
    };
    assert_eq!(ffi::SQLITE_OK, ret);

    Ok(())
}

About TEST

This project was successfully used in diesel, and diesel's integration tests and unit tests all run successfully (except for a few tests that required std::fs::* ), see sqlitest.gif.

  • sqlite-wasm: SQLite Wasm conveniently wrapped as an ES Module.
  • sqlite-web-rs: A SQLite WebAssembly backend for Diesel.
  • rusqlite: Ergonomic bindings to SQLite for Rust.

Dependencies

~3–11MB
~106K SLoC