### Install SQLite Wasm Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Install the SQLite Wasm package using npm. This is the initial setup step for using the library. ```bash npm install @sqlite.org/sqlite-wasm ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Installs the necessary Node.js dependencies for the project, including development and testing tools. ```bash npm install ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Installs the required browser binaries for Playwright, which is used for running browser-based tests. This command ensures that the necessary environments for testing are available. ```bash npx playwright install chromium --with-deps --no-shell ``` -------------------------------- ### Install and Use SAH Pool VFS for OPFS Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Initializes and configures the SAH Pool VFS for improved OPFS performance. Use this to pre-allocate file handles and manage database operations within a worker. Ensure the directory exists before installation. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule(); // Install SAH Pool VFS const poolUtil = await sqlite3.installOpfsSAHPoolVfs({ name: 'opfs-sahpool', directory: '/myapp-data', initialCapacity: 6, }); console.log('VFS name:', poolUtil.vfsName); console.log('Pool capacity:', poolUtil.getCapacity()); // Increase capacity if needed await poolUtil.reserveMinimumCapacity(10); // Create database using the pool const db = new poolUtil.OpfsSAHPoolDb('/myapp-data/app.db'); try { db.exec('CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, data BLOB, expires INTEGER)'); // Import an existing database // const dbBytes = await fetch('/backup.db').then(r => r.arrayBuffer()); // await poolUtil.importDb('/myapp-data/restored.db', new Uint8Array(dbBytes)); // Export a database const exported = await poolUtil.exportFile('/myapp-data/app.db'); console.log('Exported database size:', exported.length); // List files in pool console.log('Files in pool:', poolUtil.getFileNames()); } finally { db.close(); } // Cleanup (removes VFS and all data) // await poolUtil.removeVfs(); ``` -------------------------------- ### Execute SQL with exec() and Callbacks Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Executes SQL statements using the `exec()` method. This example shows creating a table, inserting multiple rows, querying with a `WHERE` clause and a callback for row processing, and retrieving all results as an array of objects. Supports various `rowMode` options. ```javascript const db = new sqlite3.oo1.DB(':memory:'); // Create table and insert multiple rows db.exec('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)'); for (let i = 1; i <= 5; i++) { db.exec({ sql: 'INSERT INTO products (name, price) VALUES (?, ?)', bind: [`Product ${i}`, i * 10.99], }); } // Query with callback db.exec({ sql: 'SELECT * FROM products WHERE price > ?', bind: [25], rowMode: 'object', callback: (row) => { console.log(`${row.name}: $${row.price}`); }, }); // Output: // Product 3: $32.97 // Product 4: $43.96 // Product 5: $54.95 // Get all results as array of objects const allProducts = db.exec({ sql: 'SELECT name, price FROM products ORDER BY price DESC LIMIT 3', rowMode: 'object', returnValue: 'resultRows', }); console.log(allProducts); // Output: [{ name: 'Product 5', price: 54.95 }, ...] db.close(); ``` -------------------------------- ### Node.js In-Memory Database Usage Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Demonstrates using SQLite Wasm in a Node.js environment for in-memory databases. Import from the node-specific entry point for proper WASM loading. This example creates a table, inserts data, and queries it. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule({ print: console.log, printErr: console.error, }); console.log('Running SQLite', sqlite3.version.libVersion, 'in Node.js'); const db = new sqlite3.oo1.DB(':memory:'); try { db.exec(` CREATE TABLE items (id INTEGER PRIMARY KEY, data JSON); INSERT INTO items (data) VALUES ('{"name": "Widget", "qty": 100}'); INSERT INTO items (data) VALUES ('{"name": "Gadget", "qty": 50}'); `); const items = db.selectObjects("SELECT id, json_extract(data, '$.name') as name FROM items"); console.log(items); // Output: [{ id: 1, name: 'Widget' }, { id: 2, name: 'Gadget' }] } finally { db.close(); } ``` -------------------------------- ### Use Prepared Statements for Insertion and Query Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Demonstrates using prepared statements for efficient data insertion and retrieval. It shows how to prepare, bind parameters, step through results, and importantly, finalize statements in a `finally` block to prevent resource leaks. Use prepared statements for repeated queries. ```javascript const db = new sqlite3.oo1.DB(':memory:'); db.exec('CREATE TABLE logs (id INTEGER PRIMARY KEY, message TEXT, timestamp INTEGER)'); // Insert with prepared statement const insertStmt = db.prepare('INSERT INTO logs (message, timestamp) VALUES (?, ?)'); try { for (let i = 0; i < 100; i++) { insertStmt.bind([`Log entry ${i}`, Date.now()]).stepReset(); } } finally { insertStmt.finalize(); } // Query with prepared statement const selectStmt = db.prepare('SELECT id, message FROM logs WHERE id > ? LIMIT 5'); try { selectStmt.bind([95]); while (selectStmt.step()) { const id = selectStmt.get(0); const message = selectStmt.getString(1); console.log(`${id}: ${message}`); } } finally { selectStmt.finalize(); } db.close(); ``` -------------------------------- ### Initializing SQLite Module Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Asynchronously loads and initializes the SQLite WebAssembly module. It returns a Promise that resolves to the sqlite3 namespace object containing all APIs and database classes. ```APIDOC ## Initializing SQLite Module The `sqlite3InitModule` function asynchronously loads and initializes the SQLite WebAssembly module. It returns a Promise that resolves to the sqlite3 namespace object containing all APIs and database classes. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule({ print: console.log, printErr: console.error, }); console.log('SQLite version:', sqlite3.version.libVersion); // Output: SQLite version: 3.51.2 ``` ``` -------------------------------- ### Initialize SQLite Module Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Asynchronously loads and initializes the SQLite WebAssembly module. It returns a Promise that resolves to the sqlite3 namespace object containing all APIs and database classes. Use this before interacting with any SQLite functionality. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule({ print: console.log, printErr: console.error, }); console.log('SQLite version:', sqlite3.version.libVersion); // Output: SQLite version: 3.51.2 ``` -------------------------------- ### Create In-Memory Database and Execute SQL Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Creates an in-memory database connection using `sqlite3.oo1.DB(':memory:')`. Demonstrates creating a table, inserting data with parameterized queries, and selecting data with different return modes. Always close the database connection when finished. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule(); const db = new sqlite3.oo1.DB(':memory:'); try { db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)'); db.exec({ sql: 'INSERT INTO users (name, email) VALUES (?, ?)', bind: ['Alice', 'alice@example.com'], }); const results = db.exec({ sql: 'SELECT * FROM users', rowMode: 'object', returnValue: 'resultRows', }); console.log(results); // Output: [{ id: 1, name: 'Alice', email: 'alice@example.com' }] } finally { db.close(); } ``` -------------------------------- ### Run SQLite Wasm Build on Windows Command Prompt Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Executes the Docker build command on Windows using the Command Prompt. Mounts local directories for output and source binaries. SQLITE_REF specifies the SQLite version to build. ```cmd docker run --rm ^ -e SQLITE_REF="master" ^ -v "%cd%/out:/out" ^ -v "%cd%/src/bin:/src/bin" ^ sqlite-wasm-builder:env build ``` -------------------------------- ### Creating an In-Memory Database Source: https://context7.com/sqlite/sqlite-wasm/llms.txt The `sqlite3.oo1.DB` class creates a database connection. Pass `':memory:'` for an in-memory database or a filename with the `'c'` flag to create a persistent file. Always close databases when finished. ```APIDOC ## Creating an In-Memory Database The `sqlite3.oo1.DB` class creates a database connection. Pass `':memory:'` for an in-memory database or a filename with the `'c'` flag to create a persistent file. Always close databases when finished. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule(); const db = new sqlite3.oo1.DB(':memory:'); try { db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)'); db.exec({ sql: 'INSERT INTO users (name, email) VALUES (?, ?)', bind: ['Alice', 'alice@example.com'], }); const results = db.exec({ sql: 'SELECT * FROM users', rowMode: 'object', returnValue: 'resultRows', }); console.log(results); // Output: [{ id: 1, name: 'Alice', email: 'alice@example.com' }] } finally { db.close(); } ``` ``` -------------------------------- ### Run SQLite Wasm Build on Unix Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Executes the Docker build command on Unix-like systems (Linux/macOS). Mounts local directories for output and source binaries. SQLITE_REF specifies the SQLite version to build. ```bash docker run --rm \ -e SQLITE_REF="master" \ -v "$(pwd)/out":/out \ -v "$(pwd)/src/bin":/src/bin \ sqlite-wasm-builder:env build ``` -------------------------------- ### Build Docker Image for SQLite Wasm Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Builds the Docker image required for compiling SQLite Wasm. Ensure you are in the project's root directory. ```bash docker build -t sqlite-wasm-builder:env . ``` -------------------------------- ### Initialize SQLite Wasm in Main Thread Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md This code snippet shows how to initialize the SQLite Wasm module directly in the main thread. It creates a transient database and logs the SQLite version. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const start = (sqlite3) => { log('Running SQLite3 version', sqlite3.version.libVersion); const db = new sqlite3.oo1.DB('/mydb.sqlite3', 'ct'); // Your SQLite code here. }; const initializeSQLite = async () => { try { console.log('Loading and initializing SQLite3 module...'); const sqlite3 = await sqlite3InitModule(); console.log('Done initializing. Running demo...'); start(sqlite3); } catch (err) { console.error('Initialization error:', err.name, err.message); } }; initializeSQLite(); ``` -------------------------------- ### Run SQLite Wasm Build on Windows PowerShell Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Executes the Docker build command on Windows using PowerShell. Mounts local directories for output and source binaries. SQLITE_REF specifies the SQLite version to build. ```powershell docker run --rm ` -e SQLITE_REF="master" ` -v "${PWD}/out:/out" ` -v "${PWD}/src/bin:/src/bin" ` sqlite-wasm-builder:env build ``` -------------------------------- ### Run All Tests Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Executes the entire test suite for the SQLite Wasm project, including both Node.js and browser-based tests. ```bash npm test ``` -------------------------------- ### Create Worker Instance Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md This code snippet shows how to create a new Web Worker instance in the main thread, specifying the worker script and module type. ```javascript // In `main.js`. const worker = new Worker('worker.js', { type: 'module' }); ``` -------------------------------- ### Convenience Select Methods Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Provides methods for common query patterns like selecting a single value, a single row as an array or object, multiple rows as objects, or all values from a column. ```APIDOC ## Convenience Select Methods The Database class provides convenience methods for common query patterns: `selectValue()` for a single value, `selectArray()`/`selectObject()` for a single row, and `selectArrays()`/`selectObjects()` for multiple rows. ```javascript const db = new sqlite3.oo1.DB(':memory:'); db.exec(` CREATE TABLE employees (id INTEGER PRIMARY KEY, name TEXT, department TEXT, salary REAL); INSERT INTO employees VALUES (1, 'John', 'Engineering', 85000); INSERT INTO employees VALUES (2, 'Jane', 'Marketing', 75000); INSERT INTO employees VALUES (3, 'Bob', 'Engineering', 90000); `); // Get single value const count = db.selectValue('SELECT COUNT(*) FROM employees'); console.log('Total employees:', count); // Output: Total employees: 3 // Get single row as array const topEarner = db.selectArray('SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 1'); console.log('Top earner:', topEarner); // Output: Top earner: ['Bob', 90000] // Get single row as object const employee = db.selectObject('SELECT * FROM employees WHERE id = ?', [1]); console.log(employee); // Output: { id: 1, name: 'John', department: 'Engineering', salary: 85000 } // Get all rows as objects const engineers = db.selectObjects('SELECT name, salary FROM employees WHERE department = ?', ['Engineering']); console.log(engineers); // Output: [{ name: 'John', salary: 85000 }, { name: 'Bob', salary: 90000 }] // Get column values as array const names = db.selectValues('SELECT name FROM employees ORDER BY name'); console.log(names); // Output: ['Bob', 'Jane', 'John'] db.close(); ``` ``` -------------------------------- ### Creating User-Defined Functions Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Allows registration of custom SQL functions, including scalar, aggregate, and window functions, with support for options like determinism. ```APIDOC ## Creating User-Defined Functions The `createFunction()` method registers custom SQL functions. Support includes scalar functions, aggregate functions with xStep/xFinal callbacks, and window functions with additional xValue/xInverse callbacks. ```javascript const db = new sqlite3.oo1.DB(':memory:'); // Scalar function db.createFunction('double', (ctxPtr, value) => value * 2); // Scalar function with options db.createFunction('greet', { xFunc: (ctxPtr, name) => `Hello, ${name}!`, deterministic: true, }); // Aggregate function (sum of squares) db.createFunction('sum_squares', { xStep: (ctxPtr, value) => { const current = sqlite3.capi.sqlite3_aggregate_context(ctxPtr, 8) || 0; sqlite3.wasm.poke64(current, (sqlite3.wasm.peek64(current) || 0) + value * value); }, xFinal: (ctxPtr) => { const ptr = sqlite3.capi.sqlite3_aggregate_context(ctxPtr, 0); return ptr ? sqlite3.wasm.peek64(ptr) : 0; }, }); db.exec('CREATE TABLE numbers (n INTEGER)'); db.exec('INSERT INTO numbers VALUES (1), (2), (3), (4), (5)'); console.log(db.selectValue('SELECT double(10)')); // Output: 20 console.log(db.selectValue("SELECT greet('World')")); // Output: Hello, World! console.log(db.selectValue('SELECT SUM(double(n)) FROM numbers')); // Output: 30 db.close(); ``` ``` -------------------------------- ### Using Prepared Statements Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Prepared statements offer better performance for repeated queries and fine-grained control over result fetching. Always finalize statements in a try/finally block to prevent resource leaks. ```APIDOC ## Using Prepared Statements Prepared statements offer better performance for repeated queries and fine-grained control over result fetching. Always finalize statements in a try/finally block to prevent resource leaks. ```javascript const db = new sqlite3.oo1.DB(':memory:'); db.exec('CREATE TABLE logs (id INTEGER PRIMARY KEY, message TEXT, timestamp INTEGER)'); // Insert with prepared statement const insertStmt = db.prepare('INSERT INTO logs (message, timestamp) VALUES (?, ?)'); try { for (let i = 0; i < 100; i++) { insertStmt.bind([`Log entry ${i}`, Date.now()]).stepReset(); } } finally { insertStmt.finalize(); } // Query with prepared statement const selectStmt = db.prepare('SELECT id, message FROM logs WHERE id > ? LIMIT 5'); try { selectStmt.bind([95]); while (selectStmt.step()) { const id = selectStmt.get(0); const message = selectStmt.getString(1); console.log(`${id}: ${message}`); } } finally { selectStmt.finalize(); } db.close(); ``` ``` -------------------------------- ### Worker with OPFS Persistence (OpfsDb) Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Use this snippet in a Web Worker to persist databases to the Origin Private File System. Ensure COOP/COEP headers are set for OPFS access. This provides true file-system persistence across browser sessions. ```javascript // worker.js - Must run in a Web Worker import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule(); if ('opfs' in sqlite3) { const db = new sqlite3.oo1.OpfsDb('/myapp/data.sqlite3'); try { db.exec(` CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT); INSERT OR REPLACE INTO settings VALUES ('theme', 'dark'); INSERT OR REPLACE INTO settings VALUES ('language', 'en'); `); const settings = db.selectObjects('SELECT * FROM settings'); postMessage({ type: 'settings', data: settings }); // Output: [{ key: 'theme', value: 'dark' }, { key: 'language', value: 'en' }] } finally { db.close(); } } else { console.error('OPFS not available'); } ``` -------------------------------- ### Vite Configuration for SQLite Wasm Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md Configure Vite to correctly serve SQLite Wasm by setting necessary Cross-Origin Isolation headers and excluding the package from dependency optimization. ```javascript import { defineConfig } from 'vite'; export default defineConfig({ server: { headers: { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp', }, }, optimizeDeps: { exclude: ['@sqlite.org/sqlite-wasm'], }, }); ``` -------------------------------- ### Initialize SQLite Wasm in a Worker Source: https://github.com/sqlite/sqlite-wasm/blob/main/README.md This code snippet demonstrates how to initialize the SQLite Wasm module within a web worker. It handles both OPFS-available and non-available scenarios, logging the database type used. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const start = (sqlite3) => { console.log('Running SQLite3 version', sqlite3.version.libVersion); const db = 'opfs' in sqlite3 ? new sqlite3.oo1.OpfsDb('/mydb.sqlite3') : new sqlite3.oo1.DB('/mydb.sqlite3', 'ct'); console.log( 'opfs' in sqlite3 ? `OPFS is available, created persisted database at ${db.filename}` : `OPFS is not available, created transient database ${db.filename}`, ); // Your SQLite code here. }; const initializeSQLite = async () => { try { console.log('Loading and initializing SQLite3 module...'); const sqlite3 = await sqlite3InitModule(); console.log('Done initializing. Running demo...'); start(sqlite3); } catch (err) { console.error('Initialization error:', err.name, err.message); } }; initializeSQLite(); ``` -------------------------------- ### JsStorageDb with localStorage/sessionStorage Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Use `JsStorageDb` for simple persistence by storing data in browser `localStorage` or `sessionStorage` via the kvvfs virtual file system. This is suitable for smaller databases and avoids OPFS requirements. ```javascript import sqlite3InitModule from '@sqlite.org/sqlite-wasm'; const sqlite3 = await sqlite3InitModule(); const db = new sqlite3.oo1.JsStorageDb('local'); // or 'session' for sessionStorage try { db.exec(` CREATE TABLE IF NOT EXISTS preferences ( key TEXT PRIMARY KEY, value TEXT, updated_at INTEGER ) `); db.exec({ sql: 'INSERT OR REPLACE INTO preferences VALUES (?, ?, ?)', bind: ['darkMode', 'true', Date.now()], }); const prefs = db.selectObjects('SELECT * FROM preferences'); console.log('Preferences:', prefs); // Check storage usage console.log('Storage size estimate:', db.storageSize(), 'bytes'); // Clear all kvvfs data (use with caution) // const deleted = db.clearStorage(); // console.log('Deleted records:', deleted); } finally { db.close(); } ``` -------------------------------- ### Creating User-Defined Functions in SQLite WASM Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Registers custom SQL functions using `createFunction()`. Supports scalar, aggregate, and window functions. Aggregate functions require `xStep` and `xFinal` callbacks, while window functions also need `xValue` and `xInverse`. ```javascript const db = new sqlite3.oo1.DB(':memory:'); // Scalar function db.createFunction('double', (ctxPtr, value) => value * 2); // Scalar function with options db.createFunction('greet', { xFunc: (ctxPtr, name) => `Hello, ${name}!`, deterministic: true, }); // Aggregate function (sum of squares) db.createFunction('sum_squares', { xStep: (ctxPtr, value) => { const current = sqlite3.capi.sqlite3_aggregate_context(ctxPtr, 8) || 0; sqlite3.wasm.poke64(current, (sqlite3.wasm.peek64(current) || 0) + value * value); }, xFinal: (ctxPtr) => { const ptr = sqlite3.capi.sqlite3_aggregate_context(ctxPtr, 0); return ptr ? sqlite3.wasm.peek64(ptr) : 0; }, }); db.exec('CREATE TABLE numbers (n INTEGER)'); db.exec('INSERT INTO numbers VALUES (1), (2), (3), (4), (5)'); console.log(db.selectValue('SELECT double(10)')); // Output: 20 console.log(db.selectValue("SELECT greet('World')")); // Output: Hello, World! console.log(db.selectValue('SELECT SUM(double(n)) FROM numbers')); // Output: 30 db.close(); ``` -------------------------------- ### Executing SQL with exec() Source: https://context7.com/sqlite/sqlite-wasm/llms.txt The `exec()` method executes one or more SQL statements. It supports binding parameters, callbacks for row processing, and various return modes. Use `rowMode` to control output format: `'array'`, `'object'`, or `'stmt'`. ```APIDOC ## Executing SQL with exec() The `exec()` method executes one or more SQL statements. It supports binding parameters, callbacks for row processing, and various return modes. Use `rowMode` to control output format: `'array'`, `'object'`, or `'stmt'`. ```javascript const db = new sqlite3.oo1.DB(':memory:'); // Create table and insert multiple rows db.exec('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)'); for (let i = 1; i <= 5; i++) { db.exec({ sql: 'INSERT INTO products (name, price) VALUES (?, ?)', bind: [`Product ${i}`, i * 10.99], }); } // Query with callback db.exec({ sql: 'SELECT * FROM products WHERE price > ?', bind: [25], rowMode: 'object', callback: (row) => { console.log(`${row.name}: $${row.price}`); }, }); // Output: // Product 3: $32.97 // Product 4: $43.96 // Product 5: $54.95 // Get all results as array of objects const allProducts = db.exec({ sql: 'SELECT name, price FROM products ORDER BY price DESC LIMIT 3', rowMode: 'object', returnValue: 'resultRows', }); console.log(allProducts); // Output: [{ name: 'Product 5', price: 54.95 }, ...] db.close(); ``` ``` -------------------------------- ### Convenience Select Methods in SQLite WASM Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Demonstrates various `select` methods for retrieving data. Use `selectValue` for a single value, `selectArray`/`selectObject` for a single row, and `selectArrays`/`selectObjects` for multiple rows. `selectValues` retrieves all values from a single column. ```javascript const db = new sqlite3.oo1.DB(':memory:'); db.exec(` CREATE TABLE employees (id INTEGER PRIMARY KEY, name TEXT, department TEXT, salary REAL); INSERT INTO employees VALUES (1, 'John', 'Engineering', 85000); INSERT INTO employees VALUES (2, 'Jane', 'Marketing', 75000); INSERT INTO employees VALUES (3, 'Bob', 'Engineering', 90000); `); // Get single value const count = db.selectValue('SELECT COUNT(*) FROM employees'); console.log('Total employees:', count); // Output: Total employees: 3 // Get single row as array const topEarner = db.selectArray('SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 1'); console.log('Top earner:', topEarner); // Output: Top earner: ['Bob', 90000] // Get single row as object const employee = db.selectObject('SELECT * FROM employees WHERE id = ?', [1]); console.log(employee); // Output: { id: 1, name: 'John', department: 'Engineering', salary: 85000 } // Get all rows as objects const engineers = db.selectObjects('SELECT name, salary FROM employees WHERE department = ?', ['Engineering']); console.log(engineers); // Output: [{ name: 'John', salary: 85000 }, { name: 'Bob', salary: 90000 }] // Get column values as array const names = db.selectValues('SELECT name FROM employees ORDER BY name'); console.log(names); // Output: ['Bob', 'Jane', 'John'] db.close(); ``` -------------------------------- ### Worker1 Promiser API for SQLite Operations Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Utilize the `sqlite3Worker1Promiser` for a Promise-based interface to SQLite workers. This API simplifies asynchronous operations like opening, executing SQL, exporting, and configuring the database. ```javascript import { sqlite3Worker1Promiser } from '@sqlite.org/sqlite-wasm'; const promiser = await new Promise((resolve) => { sqlite3Worker1Promiser({ onready: resolve, }); }); // Get SQLite configuration const config = await promiser('config-get', {}); console.log('SQLite version:', config.result.version.libVersion); console.log('Available VFS:', config.result.vfsList); // Open database with OPFS persistence const openResult = await promiser('open', { filename: 'file:mydb.sqlite3?vfs=opfs', }); const { dbId } = openResult; console.log('Database opened:', openResult.result.filename); // Execute SQL await promiser('exec', { dbId, sql: 'CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, task TEXT, done INTEGER)', }); await promiser('exec', { dbId, sql: 'INSERT INTO todos (task, done) VALUES (?, ?)', bind: ['Learn SQLite Wasm', 0], }); // Query with callback await promiser('exec', { dbId, sql: 'SELECT * FROM todos', rowMode: 'object', callback: (result) => { if (result.row) { console.log('Todo:', result.row); } }, }); // Export database as Uint8Array const exportResult = await promiser('export', { dbId }); console.log('Exported size:', exportResult.result.byteArray.length, 'bytes'); // Close database await promiser('close', { dbId }); ``` -------------------------------- ### Transactions and Savepoints in SQLite WASM Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Manages database operations using `transaction()` for atomic operations and `savepoint()` for nested transactions. `transaction()` automatically rolls back on error. Both methods return the callback's result on success. ```javascript const db = new sqlite3.oo1.DB(':memory:'); db.exec('CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, balance REAL)'); db.exec("INSERT INTO accounts VALUES (1, 'Alice', 1000), (2, 'Bob', 500)"); // Successful transaction const result = db.transaction((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance - 100 WHERE id = 1' }); db.exec({ sql: 'UPDATE accounts SET balance = balance + 100 WHERE id = 2' }); return 'Transfer complete'; }); console.log(result); // Output: Transfer complete // Transaction with rollback on error try { db.transaction((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance - 2000 WHERE id = 1' }); // Simulating a constraint check failure const balance = db.selectValue('SELECT balance FROM accounts WHERE id = 1'); if (balance < 0) throw new Error('Insufficient funds'); db.exec({ sql: 'UPDATE accounts SET balance = balance + 2000 WHERE id = 2' }); }); } catch (e) { console.log('Transaction rolled back:', e.message); } // Nested savepoints db.transaction((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance + 50 WHERE id = 1' }); db.savepoint((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance + 25 WHERE id = 2' }); // This savepoint commits }); }); console.log(db.selectObjects('SELECT * FROM accounts')); // Output: [{ id: 1, name: 'Alice', balance: 950 }, { id: 2, name: 'Bob', balance: 625 }] db.close(); ``` -------------------------------- ### Transactions and Savepoints Source: https://context7.com/sqlite/sqlite-wasm/llms.txt Manages database transactions and savepoints, ensuring data integrity with automatic rollback on errors and supporting nested transaction logic. ```APIDOC ## Transactions and Savepoints The `transaction()` method wraps a callback in BEGIN/COMMIT with automatic ROLLBACK on error. Use `savepoint()` for nested transactions. Both methods return the callback's return value on success. ```javascript const db = new sqlite3.oo1.DB(':memory:'); db.exec('CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, balance REAL)'); db.exec("INSERT INTO accounts VALUES (1, 'Alice', 1000), (2, 'Bob', 500)"); // Successful transaction const result = db.transaction((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance - 100 WHERE id = 1' }); db.exec({ sql: 'UPDATE accounts SET balance = balance + 100 WHERE id = 2' }); return 'Transfer complete'; }); console.log(result); // Output: Transfer complete // Transaction with rollback on error try { db.transaction((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance - 2000 WHERE id = 1' }); // Simulating a constraint check failure const balance = db.selectValue('SELECT balance FROM accounts WHERE id = 1'); if (balance < 0) throw new Error('Insufficient funds'); db.exec({ sql: 'UPDATE accounts SET balance = balance + 2000 WHERE id = 2' }); }); } catch (e) { console.log('Transaction rolled back:', e.message); } // Nested savepoints db.transaction((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance + 50 WHERE id = 1' }); db.savepoint((db) => { db.exec({ sql: 'UPDATE accounts SET balance = balance + 25 WHERE id = 2' }); // This savepoint commits }); }); console.log(db.selectObjects('SELECT * FROM accounts')); // Output: [{ id: 1, name: 'Alice', balance: 950 }, { id: 2, name: 'Bob', balance: 625 }] db.close(); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.