### Setup sqlite3_module with options Source: https://sqlite.org/wasm/doc/trunk/vtab.md Use setupModule to initialize an sqlite3_module object for installation into databases. It requires a methods object and supports exception handling and optional struct/version settings. ```javascript sqlite3_module setupModule(options) ``` -------------------------------- ### Clone and Install Emscripten SDK Source: https://sqlite.org/wasm/doc/trunk/emscripten.md Initial setup for the Emscripten SDK on Linux. This involves cloning the repository, installing the latest SDK tools, and activating them for the current user. ```bash # Clone the emscripten repository: sudo apt install git git clone https://github.com/emscripten-core/emsdk.git cd emsdk # Download and install the latest SDK tools: ./emsdk install latest # Make the "latest" SDK "active" for the current user: ./emsdk activate latest ``` -------------------------------- ### Install OPFS SAHPool VFS (Async) Source: https://sqlite.org/wasm/doc/trunk/persistence.md Asynchronously installs the OPFS SAHPool VFS. This is the simplest way to enable the VFS. ```javascript await sqlite3.installOpfsSAHPoolVfs(); ``` -------------------------------- ### Install and Deploy Custom Skin Source: https://sqlite.org/wasm/doc/trunk/doc-maintenance.md Commands to install the skin into the local repository and then deploy it to the remote repository, requiring administrator rights for the latter. ```bash $ make skin $ make push # or: $ fossil config push skin ``` -------------------------------- ### Example Fossil Site Menu Configuration Source: https://sqlite.org/wasm/doc/trunk/doc-maintenance.md An example configuration for the Fossil site's main menu, demonstrating conditional links for developers and casual users. ```fossil Home /doc/ckout/index.md L {} Home /doc/trunk/index.md !L {} {API Index} /doc/ckout/api-index.md L {} {API Index} /doc/trunk/api-index.md !L {} Timeline /timeline * {} Files /dir L {} Admin /setup {a s} {} Login /login !L {} Account /login L {} ``` -------------------------------- ### Setting up wasi-sdk Source: https://sqlite.org/wasm/doc/trunk/building.md Steps to clone, build, and install the wasi-sdk on an Ubuntu-style Linux system. This process can be time-consuming. ```bash $ git clone --recursive https://github.com/WebAssembly/wasi-sdk.git $ cd wasi-sdk $ sudo apt install ninja-build cmake clang $ NINJA_FLAGS=-v make package # ^^^^ go order a pizza, wait for it to arrive, eat it, and # check back. Maybe it'll be done by then. Maybe. As of this writing, # it has to compile more than 3000 C++ files. $ sudo ln -s $PWD/build/wasi-sdk-* /opt/wasi-sdk # ^^^^^^^ /opt/wasi-sdk is a magic path name for these tools ``` -------------------------------- ### Install OPFS SAHPool VFS with Promise Handling Source: https://sqlite.org/wasm/doc/trunk/persistence.md Installs the OPFS SAHPool VFS using a Promise, providing access to pool management utilities upon successful installation. ```javascript sqlite3.installOpfsSAHPoolVfs().then((poolUtil)=>{ // poolUtil contains utilities for managing the pool, described below. // VFS "opfs-sahpool" is now available, and poolUtil.OpfsSAHPoolDb // is a subclass of sqlite3.oo1.DB to simplify usage with // the oo1 API. }).catch(...); ``` -------------------------------- ### Test Demo App Locally Source: https://sqlite.org/wasm/doc/trunk/doc-maintenance.md Starts a local web server to test the demo application, requiring a browser window to open for verification. ```bash $ make ui ``` -------------------------------- ### Configuring and Building with wasi-sdk Source: https://sqlite.org/wasm/doc/trunk/building.md Commands to configure the SQLite source tree to use the installed wasi-sdk and then build the project. ```bash ./configure --with-wasi-sdk=/opt/wasi-sdk $ make ``` -------------------------------- ### setupModule() Source: https://sqlite.org/wasm/doc/trunk/vtab.md Sets up and initializes an sqlite3_module() object for installation into SQLite databases. It takes an options object that defines methods, exception handling, and optional struct or version information. ```APIDOC ## setupModule() ### Description Sets up this module object. A helper to initialize and set up an sqlite3_module() object for later installation into individual databases using `sqlite3_create_module()`. ### Method Signature `sqlite3_module setupModule(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (object) - Required - An object with the following properties: * **methods** (object) - Required - A mapping of properties with C-side names (e.g., xCreate, xBestIndex) to JS implementations. * **catchExceptions** (boolean) - Optional (default=false) - If true, exceptions are wrapped and translated into SQLITE_ERROR or SQLITE_NOMEM result codes. For xConnect and xCreate, the error string is also set. * **struct** (sqlite3_module) - Optional - An existing `sqlite3_module` instance. If not set, one will be created. If `this` is an `sqlite3_module`, it is used. * **iVersion** (integer) - Optional - An integer value assigned to the `$iVersion` member of the struct object. If not set, a value is derived from the methods. ### Special Method Handling * If `methods.xConnect` is `true`, `methods.xCreate` is used in its place, and vice versa. * If `methods.xDisconnect` is `true`, `methods.xDestroy` is used in its place, and vice versa. ### Return Value * **sqlite3_module** - On success, returns the configured `sqlite3_module` object (`this`, `opt.struct`, or a new instance). ### Throws Throws on error. ``` -------------------------------- ### Install SQLite WASM via npm Source: https://sqlite.org/wasm/doc/trunk/npm.md Use this command to install the @sqlite.org/sqlite-wasm package from npm. ```bash $ npm install @sqlite.org/sqlite-wasm ``` -------------------------------- ### Launch Local Fossil UI with Custom Skin Source: https://sqlite.org/wasm/doc/trunk/doc-maintenance.md Starts the Fossil UI command with a specified local skin directory for development and testing. ```bash $ fossil ui --skin $PWD/assets/skin # Which can be abbreviated to: $ make ui ``` -------------------------------- ### Promiser v2 Initialization with Async/Await Source: https://sqlite.org/wasm/doc/trunk/api-worker1.md Example of initializing Promiser v2 using async/await, where the initialization function returns a Promise. ```javascript const factory = await sqlite3Worker1Promiser.v2(/*optional config*/); ``` -------------------------------- ### SQLite WASM C API: Installing Auto-Extension Handler Source: https://sqlite.org/wasm/doc/trunk/api-c-style.md Demonstrates how to install an auto-extension handler using a JavaScript function, which is automatically converted to a WASM function. For manual management, use `wasm.installFunction()`. ```javascript wasm.installFunction("i(ppp)") ``` -------------------------------- ### Promiser v2 ESM Module Initialization Source: https://sqlite.org/wasm/doc/trunk/api-worker1.md Example of loading Promiser v2 as an ESM module, demonstrating how to import and initialize it. ```javascript import { default as promiserFactory } from "./jswasm/sqlite3-worker1-promiser.mjs"; const promiser = await promiserFactory(/* optional config */) .then(func){ // func == the promiser factory function (same as `promiser` will resolve to). // Do any necessary client-side pre-work here, if needed, then... return func; // ensure that the promise resolves to the proper value }); ``` -------------------------------- ### installOpfsSAHPoolVfs Source: https://sqlite.org/wasm/doc/trunk/persistence.md Installs and returns a utility object for managing the OPFS SAH Pool VFS. Subsequent calls with the same name return the same utility object. ```APIDOC ## installOpfsSAHPoolVfs() ### Description Installs the OPFS SAH Pool VFS and returns a utility object for its administration. This function is idempotent when called with the same `name` option. ### Method `installOpfsSAHPoolVfs()` ### Returns A Promise resolving to a `PoolUtil` object for VFS administration. ``` -------------------------------- ### sqlite3.kvvfs.reserve() Source: https://sqlite.org/wasm/doc/trunk/kvvfs.md Installs a new kvvfs storage object if it does not exist, or increases the reference count of an existing one. ```APIDOC ## `sqlite3.kvvfs.reserve()` ### Description Installs a new kvvfs storage object if it does not exist, or increases the reference count of an existing one, ensuring it is not freed prematurely. ### Usage `sqlite3.kvvfs.reserve(storageName)` ### Parameters #### Path Parameters (Not applicable for this method) #### Query Parameters (Not applicable for this method) #### Arguments * **storageName** (string) - Required. The name of the kvvfs storage to reserve. ### Throws Throws if the name is not valid for a new storage object. ### Notes The built-in storage objects are preinstalled with high reference counts. ``` -------------------------------- ### 64-bit Build Pointer Arithmetic Example (Fails) Source: https://sqlite.org/wasm/doc/trunk/building.md Illustrates a common pointer arithmetic pattern that will fail in a 64-bit WASM build due to mixing BigInt and Number types. ```javascript let ptr = wasm.alloc(16); let ptr2 = ptr + 8; // Cannot mix BigInt/Number math ``` -------------------------------- ### Configure Fossil CGI Wrapper for Custom Skin Source: https://sqlite.org/wasm/doc/trunk/doc-maintenance.md Example CGI wrapper script configuration for Fossil SCM to pin a specific repository and use its default skin. ```fossil #!/usr/bin/fossil repository: /fossil/wasmdocs.fossil jsmode: bundled skin: ``` -------------------------------- ### Promiser v1 Initialization Source: https://sqlite.org/wasm/doc/trunk/api-worker1.md Example of initializing the Promiser v1 API, which uses an onready handler to signal completion. ```javascript // v1: const factory = sqlite3Worker1Promiser({ onready: function(f){ /** The promiser factory (f) is now ready for use. f is the same function which is returned from sqlite3Worker1Promiser(). */ } }); // Equivalent: // const factory = sqlite3Worker1Promiser(function(f){...}); ``` -------------------------------- ### Initialize SQLite WASM Module Source: https://sqlite.org/wasm/doc/trunk/api-index.md Initialize the WASM file and activate the API after loading. This function is installed by Emscripten. ```javascript self.sqlite3InitModule().then((sqlite3)=>{ ... do something with sqlite3 ... }); ``` -------------------------------- ### Execute SQL Query Source: https://sqlite.org/wasm/doc/trunk/gotchas.md An example of executing a simple SQL query. This can sometimes throw inexplicable errors, such as SQL syntax errors, if the WASM heap has been corrupted. ```javascript myDb.exec("SELECT 1"); ``` -------------------------------- ### Install a single method into a StructBinder Source: https://sqlite.org/wasm/doc/trunk/c-structs.md Use `installMethod` to bind a JavaScript function to a struct member. It handles WASM proxy creation and cleanup. Consider `applyArgcCheck` for development-time argument validation. ```javascript function installMethod(name, func, applyArgcCheck = false) ``` ```javascript structTypeInstance installMethod(methodsObject, applyArgcCheck = false) ``` -------------------------------- ### Get Library Version String Source: https://sqlite.org/wasm/doc/trunk/api-c-style.md Shows how a C-style string returned from a WASM-bound C API is automatically converted to a JavaScript string. ```javascript console.log(capi.sqlite3_libversion()); ``` -------------------------------- ### Output Pointer Handling with PStack Allocator Source: https://sqlite.org/wasm/doc/trunk/api-wasm.md This example utilizes the `pstack` allocator for efficient handling of output pointers, providing a faster alternative for specific use cases while ensuring proper memory restoration. ```javascript const stack = wasm.pstack.pointer; try { const ppOut = wasm.pstack.allocPtr(); // "alloc" and zero memory const rc = some_c_function( ..., ppOut ); const pOut = wasm.peekPtr(ppOut); if(0===rc) { ... success ... } else { ... error ... } }finally{ wasm.pstack.restore(stack); } ``` -------------------------------- ### sqlite3_set_authorizer() Source: https://sqlite.org/wasm/doc/trunk/api-c-style.md Installs an authorizer callback. When a JavaScript function is provided, it's wrapped in a proxy that converts C-string arguments to JavaScript strings and handles exceptions. Non-function arguments are passed directly. ```APIDOC ## `sqlite3_set_authorizer()` ### Description Installs an authorizer callback. If a JavaScript function is provided as the second argument, a proxy is installed to convert C-string arguments to JavaScript strings before calling the provided function. Exceptions thrown by the JS function are caught and translated to database errors. Non-function arguments are passed directly to the underlying binding. ### Method `int sqlite3_set_authorizer(sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*));` ### JavaScript Wrapper When a JS function is passed: - C-string arguments are converted to JS strings. - The JS function is called with the signature: `int func(void*, int, string, string, string, string)`. - A falsy return value from the JS function is coerced to integer 0. - Exceptions thrown by the JS function are caught and translated to a db-level error. ### Direct WASM Pointer Usage To receive C-style string arguments directly, use `wasm.installFunction()` to create a function pointer and pass that pointer to `sqlite3_set_authorizer()`. In this case, no type conversion or exception handling proxy is installed. Be aware that memory allocation failures might trigger `sqlite3.WasmAllocError`. ``` -------------------------------- ### Install multiple methods into a StructBinder Source: https://sqlite.org/wasm/doc/trunk/c-structs.md Use `installMethods` to bind multiple JavaScript functions from an object to struct members. It optimizes by reusing function pointers for identical functions, particularly for `sqlite3_module` methods. ```javascript structBinderInstance installMethods(methods, applyArgcCheck = false) ``` -------------------------------- ### sqlite3_exec() with C-style Callback via WASM Source: https://sqlite.org/wasm/doc/trunk/api-c-style.md Illustrates how to use sqlite3_exec() with a C-style callback by manually installing a function into WASM and passing its pointer. This allows for direct manipulation of C-style arguments within the callback. ```APIDOC ## `sqlite3_exec()` with C-style Callback via WASM ### Description This advanced usage demonstrates how to invoke `sqlite3_exec()` with a C-style callback. It involves installing a JavaScript function into the WASM environment and passing its pointer. This method provides finer control over argument conversion. ### Method `sqlite3_capi.sqlite3_exec()` ### Parameters - **db** (object) - The SQLite database object. - **sql** (string) - The SQL statement to execute. - **callbackPointer** (number) - The pointer to the WASM-installed C-style callback function. - **callbackArg** (number) - A pointer to user data, passed to the callback. - **errorPointer** (number) - A pointer to store error information. ### Request Example ```javascript const pCb = wasm.installFunction('i(pipp)', function(pVoid, nCols, aVals, aCols) { // wasm.cArgvToJs() can be used to convert aVals and aCols to arrays: const vals = wasm.cArgvToJs(nCols, aVals); // Alternately, individual name and value columns can be converted // to JS strings like: const strAt = (ndx) => { return (ndx >= 0 && ndx < nCols) ? wasm.cstrToJs( wasm.peekPtr(wasm.ptr.add(aVals, ndx * wasm.ptr.size)) ) : undefined; }; const val0 = strAt(0), val1 = strAt(1), val2 = strAt(2); // To coerce them to numbers, simply prefix the JS strings with a plus // sign, e.g. +strAt(...). return 0; }); try { let rc = capi.sqlite3_exec(db, "select a, a*2 from foo", pCb, 0, 0); // ... handle rc ... } finally { // If the callback will be used repeatedly, skip this part: wasm.uninstallFunction(pCb); } ``` ### Response #### Success Response (200) - **rc** (number) - The return code from `sqlite3_exec()`. ``` -------------------------------- ### Update Emscripten SDK Source: https://sqlite.org/wasm/doc/trunk/emscripten.md Steps to update an existing Emscripten SDK installation to the latest version. This includes pulling changes, installing, and reactivating the SDK. ```bash git pull ./emsdk install latest ./emsdk activate latest ``` -------------------------------- ### Install function scoped to allocation scope Source: https://sqlite.org/wasm/doc/trunk/api-wasm.md Installs a JavaScript function into the WASM function table, scoped to the current allocation scope. The function is automatically uninstalled when the scope is popped. ```javascript pointer scopedInstallFunction(funcSignature, function) ``` ```javascript pointer scopedInstallFunction(function, funcSignature) ``` -------------------------------- ### scopedInstallFunction() Source: https://sqlite.org/wasm/doc/trunk/api-wasm.md Installs a JavaScript function into the WASM function table with a given signature. The installation is scoped to the current allocation scope and is automatically uninstalled when the scope is popped. Throws if no allocation scope is active. ```APIDOC ## `scopedInstallFunction()` ### Description This works exactly like `installFunction()` except that the installation is scoped to the current allocation scope and is uninstalled when the current allocation scope is popped. It will throw if no allocation scope is active. ### Method `pointer scopedInstallFunction(funcSignature, function)` `pointer scopedInstallFunction(function, funcSignature)` ``` -------------------------------- ### Initialize OpfsDb Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Create an OpfsDb instance for OPFS VFS support. The constructor can take a filename and flags, or an options object. Directory parts will be created if the 'c' flag is used. Throws if the database cannot be opened. ```javascript const db = new sqlite3.oo1.OpfsDb('/path/to/my/db','c'); // Or: new sqlite3.oo1.OpfsDb({filename: ..., flags: 'c'}); ``` -------------------------------- ### Open Database with Directory Creation (OPFS) Source: https://sqlite.org/wasm/doc/trunk/persistence.md Open an OPFS database, automatically creating leading directory parts if the 'c' (create) flag is used. ```javascript const db = new sqlite3.oo1.OpfsDb('/path/to/my.db','c'); ``` -------------------------------- ### Install WASM Function Source: https://sqlite.org/wasm/doc/trunk/api-wasm.md Installs a JavaScript function into the WASM function table, returning its index (pointer). This is necessary when passing JavaScript callbacks to C APIs. The function signature must match the expected WASM signature. ```javascript pointer installFunction(funcSignature, function) pointer installFunction(function, funcSignature) ``` -------------------------------- ### getString() Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Equivalent to `get(ndx)` but specifically coerces the result to a string. ```APIDOC ## `getString()` ### Description Equivalent to `get(ndx)` but coerces the result to a string. ### Method Signature `string|null getString(ndx)` ### Parameters * **ndx** (number) - The 0-based column index. ``` -------------------------------- ### getBlob() Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Equivalent to `get(ndx)` but specifically coerces the result to a Uint8Array. ```APIDOC ## `getBlob()` ### Description Equivalent to `get(ndx)` but coerces the result to a Uint8Array. ### Method Signature `Uint8Array|null getBlob(ndx)` ### Parameters * **ndx** (number) - The 0-based column index. ``` -------------------------------- ### Build SEE-capable WASM with Custom sqlite3.c Source: https://sqlite.org/wasm/doc/trunk/see.md Invoke the make command, specifying the absolute path to the sqlite3-see.c file to create an SEE-capable WASM build. Ensure the path is absolute. ```bash $ make sqlite3.c=/path/to/sqlite3-see.c # needs to be an absolute path ``` -------------------------------- ### getInt() Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Equivalent to `get(ndx)` but specifically coerces the result to a number (integer). ```APIDOC ## `getInt()` ### Description Equivalent to `get(ndx)` but coerces the result to a number. ### Method Signature `number|null getInt(ndx)` ### Parameters * **ndx** (number) - The 0-based column index. ``` -------------------------------- ### Instantiate OpfsSAHPoolDb Source: https://sqlite.org/wasm/doc/trunk/persistence.md Instantiates the `PoolUtil.OpfsSAHPoolDb` class, which uses the OPFS VFS. All paths provided to this VFS must be absolute. ```javascript const db = new PoolUtil.OpfsSAHPoolDb('/filename'); // ^^^ all paths for this VFS must be absolute! ``` -------------------------------- ### getFloat() Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Equivalent to `get(ndx)` but specifically coerces the result to a number (float). ```APIDOC ## `getFloat()` ### Description Equivalent to `get(ndx)` but coerces the result to a number. ### Method Signature `number|null getFloat(ndx)` ### Parameters * **ndx** (number) - The 0-based column index. ``` -------------------------------- ### Using kvvfs with localStorage and sessionStorage Source: https://sqlite.org/wasm/doc/trunk/persistence.md Demonstrates how to open a database using the 'kvvfs' VFS with either localStorage or sessionStorage. The file name must be 'local' or 'session' (or their aliases). ```javascript let db = new sqlite3.oo1.DB(); db.exec("create table t(a); insert into t values(1),(2),(3)"); db.exec("VACUUM INTO 'file:local?vfs=kvvfs'"); // Will fail if there's already a localStorage kvvfs: // sqlite3.js:14022 sqlite3_step() rc= 1 SQLITE_ERROR SQL = VACUUM INTO 'file:local?vfs=kvvfs' // But we can fix that by clearing the storage: sqlite3.capi.sqlite3_js_kvvfs_clear('local'); // Then: db.exec("VACUUM INTO 'file:local?vfs=kvvfs'"); db.close(); let ldb = new sqlite3.oo1.JsStorageDb('local'); ldb.selectValues('select a from t order by a'); // ==> [1,2,3] ``` -------------------------------- ### Basic Canonical Build Source: https://sqlite.org/wasm/doc/trunk/building.md Perform a basic canonical build of sqlite3.c and then navigate to the wasm extension directory to build the target. ```bash $ ./configure --enable-all $ make sqlite3.c $ cd ext/wasm $ make TARGET ``` -------------------------------- ### DB Class: Basic Usage with Exec and Close Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Illustrates the basic instantiation of the DB class, executing SQL commands, and closing the database connection. It's recommended to use a try...finally block to ensure the database is always closed. ```javascript const db = new sqlite3.oo1.DB(); try { db.exec([ "create table t(a);", "insert into t(a) ", "values(10),(20),(30)" ]); } finally { db.close(); } ``` -------------------------------- ### DB Constructor with Options Object Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Use this form for more flexible database opening, including options for filename, flags, VFS, and encryption keys. ```javascript { filename: db filename, flags: open-mode flags, vfs: name of the sqlite3_vfs to use, (SEE flag - see below (added in v3.46)) } ``` -------------------------------- ### Basic sqlite3 Build with Emscripten Source: https://sqlite.org/wasm/doc/trunk/emscripten.md The simplest command sequence to build sqlite3 with Emscripten. This assumes a checked-out copy of the sqlite3 source tree and uses standard make commands. ```bash $ ./configure --enable-all $ make sqlite3.c $ cd ext/wasm $ make ``` -------------------------------- ### Get Number of Changes Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Retrieves the number of database rows modified, inserted, or deleted. Supports total changes and 64-bit integers if available. ```javascript const changes = db.changes(false, false); const totalChanges = db.changes(true, false); const changes64 = db.changes(false, true); const totalChanges64 = db.changes(true, true); ``` -------------------------------- ### Initializing and Communicating with Worker1 Source: https://sqlite.org/wasm/doc/trunk/api-worker1.md This snippet shows how to create a Worker instance, set up an onmessage handler to receive initialization status, and handle subsequent messages. ```javascript const W = new Worker('sqlite3-worker1.js'); // or equivalent W.onmessage = function(event){ event = event.data; switch(event.type){ case 'sqlite3-api': if('worker1-ready' === event.result){ // The worker is now ready to accept messages } ... } }; ``` -------------------------------- ### prepare() Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Compiles the provided SQL string into a prepared statement object. Throws an error if the SQL is invalid or empty. ```APIDOC ## prepare(SQL) ### Description Compiles the given SQL and returns a prepared Stmt. This is the only way to create new Stmt objects. Throws on error. The SQL argument may be any type described for flexible-string conversions. If the SQL contains no statements, an SQLite3Error is thrown. The C API permits empty SQL, reporting it as a 0 result code and a NULL stmt pointer. Supporting that case here would cause extra work for all clients: any use of the Stmt API on such a statement will necessarily throw, so clients would be required to check `stmt.pointer` after calling `prepare()` in order to determine whether the Stmt instance is empty or not. Long-time practice with other sqlite3 script bindings suggests that the empty-prepare case is sufficiently rare that supporting it here would simply hurt overall usability. ### Method N/A (Method of DB handle object) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Stmt** (object) - A prepared statement object. #### Response Example N/A ``` -------------------------------- ### Manage Transactions with Callback Source: https://sqlite.org/wasm/doc/trunk/api-oo1.md Starts a transaction, executes a callback, and automatically commits or rolls back based on the callback's outcome. Transactions cannot be nested. ```javascript const stmt = myDb.prepare("..."); try { ... use the stmt object ... } finally { stmt.finalize(); } ``` -------------------------------- ### Verify SEE Build Output Source: https://sqlite.org/wasm/doc/trunk/see.md Check the build output for a line indicating an 'SEE build' or equivalent. This confirms the build is SEE-capable. Alternatively, grep the resulting JS file for 'sqlite3_key_v2'. ```bash $ make sqlite3.c=... # see above using emcc version [4.0.12] This is an SEE build. ... ``` ```bash $ grep -w sqlite3_key_v2 jswasm/sqlite3.js ``` -------------------------------- ### Build with 64-bit WASM Support Source: https://sqlite.org/wasm/doc/trunk/building.md Create a 64-bit WASM build by enabling the '64bit' target after configuring and building sqlite3.c. ```bash $ ./configure ... $ make sqlite3.c $ cd ext/wasm $ make -j4 64bit ``` -------------------------------- ### Getting a WASM Exported Function (xGet) Source: https://sqlite.org/wasm/doc/trunk/api-wasm.md Use `xGet` to retrieve a WASM-exported function by its name. It returns the function object or throws an error if the function is not found. ```javascript Function xGet(functionName) ``` -------------------------------- ### Fetch Database from URL Source: https://sqlite.org/wasm/doc/trunk/cookbook.md Demonstrates how to use the fetch API to load a database file from a URL, returning its content as an ArrayBuffer. ```javascript fetch( '...url to the db...' ) .then(res=>res.arrayBuffer) .then(function(arrayBuffer){ // the database's bytes are in arrayBuffer }); ``` -------------------------------- ### Get KVVFS Storage Size (Version 2) Source: https://sqlite.org/wasm/doc/trunk/kvvfs.md Estimates the number of bytes used by the KVVFS database, including its keys and values. Similar arguments to clear(). ```javascript sqlite3.kvvfs.size(which) ``` -------------------------------- ### Using sqlite3_index_info Wrapper in xBestIndex Source: https://sqlite.org/wasm/doc/trunk/vtab.md This snippet demonstrates how to use the sqlite3.capi.sqlite3_index_info wrapper object within an xBestIndex implementation. It shows the instantiation of the wrapper and the importance of calling dispose() to prevent memory leaks. ```javascript const xBestIndex = function(pVtab, pIdxInfo){ const vtab = sqlite3.vtab.xVtab.get(pVtab); // documented above const sii = new sqlite3.capi.sqlite3_index_info(pIdxInfo); ... sii.dispose(); // see notes below return 0; }; ``` -------------------------------- ### Get KVVFS Storage Size (Version 1) Source: https://sqlite.org/wasm/doc/trunk/kvvfs.md Estimates the number of bytes used by the KVVFS database, including its keys and values. Similar arguments to clear(). ```javascript sqlite3_js_kvvfs_size(which = "") ``` -------------------------------- ### Get UTF-8 Byte Length of JS String with jstrlen Source: https://sqlite.org/wasm/doc/trunk/api-wasm.md Calculates the UTF-8 byte length of a JavaScript string. Returns null if the input is not a string. This operation can be computationally expensive. ```javascript int jstrlen(jsString) ``` -------------------------------- ### Promiser v2 Initialization with .then() Source: https://sqlite.org/wasm/doc/trunk/api-worker1.md Alternative initialization for Promiser v2 using the .then() method on the returned Promise. ```javascript sqlite3Worker1Promiser.v2(/*optional config*/) .then(f=>{ // f is the function which the resulting Promise resolves to doSomeWork(f); }); ``` -------------------------------- ### Get String Representation of SQLite Result Code Source: https://sqlite.org/wasm/doc/trunk/api-c-style.md Converts a numerical SQLite result code (e.g., SQLITE_ERROR) into its string equivalent. Returns undefined for unused or unknown codes. ```javascript string sqlite3_js_rc_str(int) ``` ```javascript sqlite3_js_rc_str(sqlite3.capi.SQLITE_ERROR); ```