### Pre-run Setup for Benchmarks Source: https://github.com/powersync-ja/wa-sqlite/blob/master/demo/benchmarks/index.html Executes a PRAGMA command to set the journal mode before running benchmarks. This is a common setup step for database performance testing. ```sql -- Pre-run setup PRAGMA journal_mode=delete; Start ``` -------------------------------- ### Benchmark Setup: Journal Mode Source: https://github.com/powersync-ja/wa-sqlite/blob/master/demo/benchmarks/benchmarks.html Sets the journal mode to delete for benchmark preparation. This is a common setup step for database benchmarks. ```sql -- Pre-run setup PRAGMA journal_mode=delete; Start ``` -------------------------------- ### SQL Initialization and Query Source: https://github.com/powersync-ja/wa-sqlite/blob/master/demo/hello/hello.html Example SQL statements to create a table, insert data, and select from it. ```sql CREATE TABLE IF NOT EXISTS t(x PRIMARY KEY); INSERT OR REPLACE INTO t VALUES ('foo'), ('bar'); SELECT * FROM t; ``` -------------------------------- ### Load wa-sqlite Library and Execute SQL Source: https://github.com/powersync-ja/wa-sqlite/blob/master/README.md Demonstrates loading the wa-sqlite library asynchronously and executing a simple SQL query. This example uses ES6 modules and requires a factory function to initialize the SQLite instance. ```javascript import SQLiteESMFactory from '@journeyapps/wa-sqlite/dist/wa-sqlite.mjs'; import * as SQLite from '@journeyapps/wa-sqlite'; async function hello() { const module = await SQLiteESMFactory(); const sqlite3 = SQLite.Factory(module); const db = await sqlite3.open_v2('myDB'); await sqlite3.exec(db, `SELECT 'Hello, world!'`, (row, columns) => { console.log(row); }); await sqlite3.close(db); } hello(); ``` -------------------------------- ### Creating a SQLiteAPI Instance Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Follow these steps to create an instance of the SQLite API. This example demonstrates importing the necessary modules, invoking the ES6 module factory to create the SQLite Emscripten module, and then using the module to build the API instance. Finally, it shows how to use the API to open a database. ```javascript // Import an ES6 module factory function from one of the // package builds, either 'wa-sqlite.mjs' (synchronous) or // 'wa-sqlite-async.mjs' (asynchronous). You should only // use the asynchronous build if you plan to use an // asynchronous VFS or module.import SQLiteESMFactory from 'wa-sqlite/dist/wa-sqlite.mjs'; // Import the Javascript API wrappers. import * as SQLite from 'wa-sqlite'; // Use an async function to simplify Promise handling. (async function() { // Invoke the ES6 module factory to create the SQLite // Emscripten module. This will fetch and compile the // .wasm file. const module = await SQLiteESMFactory(); // Use the module to build the API instance. const sqlite3 = SQLite.Factory(module); // Use the API to open and access a database. const db = await sqlite3.open_v2('myDB'); // ... })(); ``` -------------------------------- ### Web Worker and MessageChannel Setup Source: https://github.com/powersync-ja/wa-sqlite/blob/master/demo/hello/index.html Loads the wa-sqlite script, either in the main window or a web worker, using MessageChannel for communication. ```javascript // Load script in the Window or in a Worker, depending on whether // the URL contains a "worker" query parameter. Use a MessageChannel // to communicate with the script. const { port1, port2 } = new MessageChannel(); const searchParams = new URLSearchParams(window.location.search); if (searchParams.has('worker')) { document.querySelector('h1').textContent = 'Running in a Worker'; const worker = new Worker('./hello.js', { type: 'module' }); worker.postMessage('messagePort', [port2]) } else { document.querySelector('h1').textContent = 'Running in the Window'; await import('./hello.js') window.postMessage('messagePort', '*', [port2]); } // Submit SQL over the MessageChannel. document.getElementById('submit').addEventListener('click', () => { port1.postMessage(document.getElementById('input').value); }); // Handle query results. port1.addEventListener('message', (event) => { console.log(event.data); const output = document.getElementById('output'); output.innerHTML = ''; if (Array.isArray(event.data)) { for (const { columns, rows } of event.data) { output.appendChild(buildHTMLTable(columns, rows)); } } else { output.textContent = 'Error: ' + event.data.error; } }); port1.start(); function buildHTMLTable(columns, rows) { function tx(tag, data) { const tx = document.createElement(tag); tx.textContent = data.toString(); return tx; } const table = document.createElement('table'); const thead = document.createElement('thead'); const tr = document.createElement('tr'); columns.forEach(column => tr.appendChild(tx('th', column))); thead.appendChild(tr); table.appendChild(thead); const tbody = document.createElement('tbody'); rows.forEach(row => { const tr = document.createElement('tr'); row.forEach(cell => tr.appendChild(tx('td', cell))); tbody.appendChild(tr); }); table.appendChild(tbody); return table; } ``` -------------------------------- ### xFileSize Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Gets the current size of a file. ```APIDOC ## xFileSize ### Description Gets the current size of a file. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pFile** (number) - Description not specified. * **pSize** (number) - Description not specified. ### Returns * number | Promise - The size of the file. ### See [https://sqlite.org/c3ref/io_methods.html](https://sqlite.org/c3ref/io_methods.html) ``` -------------------------------- ### bind_int64 Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a 64-bit integer number to a prepared statement parameter. Binding indices start from 1. ```APIDOC ## bind_int64 ### Description Binds a 64-bit integer number (bigint) to a prepared statement parameter. ### Method (Implicitly called within a JavaScript context, not a direct HTTP method) ### Parameters #### Parameters * **stmt**: number - prepared statement pointer * **i**: number - binding index (starts from 1) * **value**: bigint - The 64-bit integer to bind ### Returns number - `SQLITE_OK` (throws exception on error) ### See [https://www.sqlite.org/c3ref/bind_blob.html](https://www.sqlite.org/c3ref/bind_blob.html) ``` -------------------------------- ### Get Number of Bound Parameters Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves the total number of binding locations in a prepared statement. ```typescript sqlite3.bind_parameter_count(stmt); ``` -------------------------------- ### bind_blob Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a blob value to a prepared statement parameter. Binding indices start from 1. ```APIDOC ## bind_blob ### Description Binds a blob value to a prepared statement parameter. Binding indices start from 1. ### Method (Not specified, likely a function call in an SDK) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (Not applicable) ### Parameters * **stmt** (number) - prepared statement pointer * **i** (number) - binding index * **value** (number[] | Uint8Array) - The blob value to bind ### Returns * **number** - `SQLITE_OK` (throws exception on error) ### See * [https://www.sqlite.org/c3ref/bind_blob.html](https://www.sqlite.org/c3ref/bind_blob.html) ``` -------------------------------- ### bind_int Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds an integer number to a prepared statement parameter. Binding indices start from 1. ```APIDOC ## bind_int ### Description Binds an integer number to a prepared statement parameter. ### Method (Implicitly called within a JavaScript context, not a direct HTTP method) ### Parameters #### Parameters * **stmt**: number - prepared statement pointer * **i**: number - binding index (starts from 1) * **value**: number - The integer to bind ### Returns number - `SQLITE_OK` (throws exception on error) ### See [https://www.sqlite.org/c3ref/bind_blob.html](https://www.sqlite.org/c3ref/bind_blob.html) ``` -------------------------------- ### Bind Collection of Values to Statement Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds values from an array or object to a prepared statement. Array values are bound implicitly by index, while object values are bound by named parameters (prefixed with ':', '@', or '$'). Note that SQLite indices start at 1, while array indices start at 0. ```typescript const sql = 'INSERT INTO tbl VALUES (?, ?, ?)'; for await (const stmt of sqlite3.statements(db, sql)) { sqlite3.bind_collection(stmt, [42, 'hello', null]); ... ``` ```typescript const sql = 'INSERT INTO tbl VALUES (?, ?, ?)'; for await (const stmt of sqlite3.statements(db, sql)) { sqlite3.bind_collection(stmt, { '@foo': 42, '@bar': 'hello', '@baz': null, }); ... ``` -------------------------------- ### bind_null Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a NULL value to a prepared statement parameter. Binding indices start from 1. ```APIDOC ## bind_null ### Description Binds a NULL value to a prepared statement parameter. ### Method (Implicitly called within a JavaScript context, not a direct HTTP method) ### Parameters #### Parameters * **stmt**: number - prepared statement pointer * **i**: number - binding index (starts from 1) ### Returns number - `SQLITE_OK` (throws exception on error) ### See [https://www.sqlite.org/c3ref/bind_blob.html](https://www.sqlite.org/c3ref/bind_blob.html) ``` -------------------------------- ### bind Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a value to a prepared statement parameter. This function automatically selects the appropriate bind_* function based on the value's type. Binding indices start from 1. ```APIDOC ## bind ### Description Binds a value to a prepared statement parameter. This function automatically selects the appropriate bind_* function based on the value's type. Binding indices start from 1. ### Method (Not specified, likely a function call in an SDK) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (Not applicable) ### Parameters * **stmt** (number) - prepared statement pointer * **i** (number) - binding index * **value** ([SQLiteCompatibleType]) - The value to bind ### Returns * **number** - `SQLITE_OK` (throws exception on error) ``` -------------------------------- ### bind_text Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a string value to a specified parameter in a prepared SQL statement. Parameter indices start from 1. ```APIDOC ## bind_text(stmt, i, value) ### Description Binds a string value to a prepared statement. Note that binding indices begin with 1. ### Parameters #### Path Parameters * **stmt** (number) - Required - prepared statement pointer * **i** (number) - Required - binding index * **value** (string) - Required - The string value to bind ### Returns `SQLITE_OK` (throws exception on error) ``` -------------------------------- ### bind_double Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a double-precision floating-point number to a prepared statement parameter. Binding indices start from 1. ```APIDOC ## bind_double ### Description Binds a number (double-precision float) to a prepared statement parameter. ### Method (Implicitly called within a JavaScript context, not a direct HTTP method) ### Parameters #### Parameters * **stmt**: number - prepared statement pointer * **i**: number - binding index (starts from 1) * **value**: number - The number to bind ### Returns number - `SQLITE_OK` (throws exception on error) ### See [https://www.sqlite.org/c3ref/bind_blob.html](https://www.sqlite.org/c3ref/bind_blob.html) ``` -------------------------------- ### Bind Integer to Prepared Statement Parameter Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds an integer value to a specific parameter index in a prepared statement. Binding indices start at 1. ```typescript sqlite3.bind_int(stmt, i, value); ``` -------------------------------- ### Bind BigInt to Prepared Statement Parameter Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a BigInt value to a specific parameter index in a prepared statement. Binding indices start at 1. ```typescript sqlite3.bind_int64(stmt, i, value); ``` -------------------------------- ### Bind Double to Prepared Statement Parameter Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a number value to a specific parameter index in a prepared statement. Binding indices start at 1. ```typescript sqlite3.bind_double(stmt, i, value); ``` -------------------------------- ### Get Name of Bound Parameter Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves the name of a bound parameter at a specific index. Binding indices start at 1. ```typescript sqlite3.bind_parameter_name(stmt, i); ``` -------------------------------- ### value_type Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Gets the type of an sqlite3_value pointer. ```APIDOC ## value_type(pValue) ### Description Get type of `sqlite3_value`. ### Parameters #### Path Parameters * **pValue** (number) - Required - `sqlite3_value` pointer ### Returns number enumeration value for type ### See [https://sqlite.org/c3ref/value_blob.html](https://sqlite.org/c3ref/value_blob.html) ``` -------------------------------- ### open_v2(zFilename, iFlags?, zVfs?) Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Opens a new database connection. Returns a Promise-wrapped database pointer. ```APIDOC ## open_v2(zFilename, iFlags?, zVfs?) ### Description Opening a new database connection. Note that this function differs from the C API in that it returns the Promise-wrapped database pointer (instead of a result code). ### Parameters #### Path Parameters * **zFilename** (string) - Required * **iFlags** (number) - Optional - `SQLite.SQLITE_OPEN_CREATE | SQLite.SQLITE_OPEN_READWRITE` (0x6) if omitted * **zVfs** (string) - Optional - VFS name ### Returns Promise - Promise-wrapped database pointer. ### See [https://sqlite.org/c3ref/open.html](https://sqlite.org/c3ref/open.html) ``` -------------------------------- ### SQLiteAPI Instance Creation and Usage Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html This snippet demonstrates how to import the wa-sqlite ES6 module factory, create an instance of the SQLite API, and open a database. It highlights the use of an async function to handle Promises returned by certain API operations. ```APIDOC ## SQLiteAPI Instance Creation and Usage ### Description This section details the process of initializing and using the wa-sqlite API. It covers importing the necessary modules, creating an API instance, and opening a database connection. Note that some operations, like opening/closing databases or executing statements, may return Promises to support both synchronous and asynchronous SQLite builds. ### Usage 1. **Import Factory Function**: Import an ES6 module factory function from either `wa-sqlite.mjs` (synchronous) or `wa-sqlite-async.mjs` (asynchronous). 2. **Import API Wrappers**: Import the JavaScript API wrappers. 3. **Create API Instance**: Use an async function to invoke the factory and create the SQLite Emscripten module, then use this module to build the API instance. 4. **Open Database**: Use the API instance to open a database. ### Code Example ```javascript // Import an ES6 module factory function from one of the // package builds, either 'wa-sqlite.mjs' (synchronous) or // 'wa-sqlite-async.mjs' (asynchronous). You should only // use the asynchronous build if you plan to use an // asynchronous VFS or module. import SQLiteESMFactory from 'wa-sqlite/dist/wa-sqlite.mjs'; // Import the Javascript API wrappers. import * as SQLite from 'wa-sqlite'; // Use an async function to simplify Promise handling. (async function() { // Invoke the ES6 module factory to create the SQLite // Emscripten module. This will fetch and compile the // .wasm file. const module = await SQLiteESMFactory(); // Use the module to build the API instance. const sqlite3 = SQLite.Factory(module); // Use the API to open and access a database. const db = await sqlite3.open_v2('myDB'); // ... further database operations ... })(); ``` ### Notes - For C functions that return an error code, the corresponding JavaScript wrapper will throw an exception with a `code` property on error. - Functions involved in opening/closing a database or executing a statement may return a `Promise`. ``` -------------------------------- ### Build wa-sqlite with Make Source: https://github.com/powersync-ja/wa-sqlite/blob/master/README.md Build the wa-sqlite project using the Makefile. The -B flag forces a rebuild. ```bash make -B ``` -------------------------------- ### bind_parameter_name Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves the name of a bound parameter at a specific index. Binding indices start from 1. ```APIDOC ## bind_parameter_name ### Description Gets the name of a bound parameter at a specific index. ### Method (Implicitly called within a JavaScript context, not a direct HTTP method) ### Parameters #### Parameters * **stmt**: number - prepared statement pointer * **i**: number - binding index (starts from 1) ### Returns string - The binding name. ### See [https://www.sqlite.org/c3ref/bind_parameter_name.html](https://www.sqlite.org/c3ref/bind_parameter_name.html) ``` -------------------------------- ### SQL Preamble for Write Hint Test Source: https://github.com/powersync-ja/wa-sqlite/blob/master/demo/write-hint/index.html This SQL statement sets up the initial table structure for the write hint test. ```sql CREATE TABLE t(x); ``` -------------------------------- ### xSync Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Synchronizes data to disk for a file. ```APIDOC ## xSync ### Description Synchronizes data to disk for a file. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pFile** (number) - Description not specified. * **flags** (number) - Description not specified. ### Returns * number | Promise - The result of the sync operation. ### See [https://sqlite.org/c3ref/io_methods.html](https://sqlite.org/c3ref/io_methods.html) ``` -------------------------------- ### xOpen Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Opens a file within the virtual file system. ```APIDOC ## xOpen ### Description Opens a file within the virtual file system. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pVfs** (number) - Description not specified. * **zName** (number) - Description not specified. * **pFile** (number) - Description not specified. * **flags** (number) - Description not specified. * **pOutFlags** (number) - Description not specified. ### Returns * number | Promise - The result of the open operation. ### See [https://sqlite.org/c3ref/vfs.html](https://sqlite.org/c3ref/vfs.html) ``` -------------------------------- ### SQLiteVFS Interface Methods Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html This section details the methods available in the SQLiteVFS interface. Each method can be implemented synchronously or asynchronously. ```APIDOC ## Interface SQLiteVFS SQLite Virtual File System object Objects with this interface can be passed to [SQLiteAPI.vfs_register](SQLiteAPI.html#vfs_register) to define a new filesystem. ### Methods #### xAccess * **Description**: Checks if a file has certain access permissions. * **Parameters**: * `pVfs` (number) * `zName` (number) * `flags` (number) * `pResOut` (number) * **Returns**: `number | Promise` * **See**: [https://sqlite.org/c3ref/vfs.html](https://sqlite.org/c3ref/vfs.html) #### xCheckReservedLock * **Description**: Checks for a reserved lock on a file. * **Parameters**: * `pFile` (number) * `pResOut` (number) * **Returns**: `number | Promise` * **See**: [https://sqlite.org/c3ref/io_methods.html](https://sqlite.org/c3ref/io_methods.html) #### xClose * **Description**: Closes a file. * **Parameters**: * `pFile` (number) * **Returns**: `number | Promise` * **See**: [https://sqlite.org/c3ref/io_methods.html](https://sqlite.org/c3ref/io_methods.html) #### xDelete * **Description**: Deletes a file. * **Parameters**: * `pVfs` (number) * `zName` (number) * `syncDir` (number) * **Returns**: `number | Promise` #### xDeviceCharacteristics * **Description**: Returns the device characteristics of a file. * **Parameters**: * `pFile` (number) * **Returns**: `number | Promise` #### xFileControl * **Description**: Performs a file control operation. * **Parameters**: * `pFile` (number) * `op` (number) * `pArg` (number) * **Returns**: `number | Promise` #### xFileSize * **Description**: Gets the size of a file. * **Parameters**: * `pFile` (number) * `pSize` (number) * **Returns**: `number | Promise` #### xFullPathname * **Description**: Gets the full path name of a file. * **Parameters**: * `pVfs` (number) * `zName` (number) * `nOut` (number) * `zOut` (number) * **Returns**: `number | Promise` #### xGetLastError * **Description**: Gets the last error message. * **Parameters**: * `pVfs` (number) * `nBuf` (number) * `zBuf` (number) * **Returns**: `number | Promise` #### xLock * **Description**: Acquires a lock on a file. * **Parameters**: * `pFile` (number) * `lockType` (number) * **Returns**: `number | Promise` #### xOpen * **Description**: Opens a file. * **Parameters**: * `pVfs` (number) * `zName` (number) * `pFile` (number) * `flags` (number) * `pOutFlags` (number) * **Returns**: `number | Promise` #### xRead * **Description**: Reads data from a file. * **Parameters**: * `pFile` (number) * `pData` (number) * `iAmt` (number) * `iOffsetLo` (number) * `iOffsetHi` (number) * **Returns**: `number | Promise` #### xSectorSize * **Description**: Gets the sector size of a file. * **Parameters**: * `pFile` (number) * **Returns**: `number | Promise` #### xSync * **Description**: Synchronizes file changes. * **Parameters**: * `pFile` (number) * `flags` (number) * **Returns**: `number | Promise` #### xTruncate * **Description**: Truncates a file to a specified size. * **Parameters**: * `pFile` (number) * `sizeLo` (number) * `sizeHi` (number) * **Returns**: `number | Promise` #### xUnlock * **Description**: Releases a lock on a file. * **Parameters**: * `pFile` (number) * `lockType` (number) * **Returns**: `number | Promise` #### xWrite * **Description**: Writes data to a file. * **Parameters**: * `pFile` (number) * `pData` (number) * `iAmt` (number) * `iOffsetLo` (number) * `iOffsetHi` (number) * **Returns**: `number | Promise` ``` -------------------------------- ### libversion() Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves the version of the SQLite library as a string array. ```APIDOC ## libversion() ### Description Get SQLite library version. ### Returns string - version string, e.g. '3.35.5' ### See [https://www.sqlite.org/c3ref/libversion.html](https://www.sqlite.org/c3ref/libversion.html) ``` -------------------------------- ### SQLitePrepareOptions Interface Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLitePrepareOptions.html Defines options for preparing SQL statements. It can include flags to modify preparation behavior and an unscoped option to control statement lifetime. ```APIDOC ## Interface SQLitePrepareOptions Options object argument for [SQLiteAPI.statements](SQLiteAPI.html#statements) ### Properties * **flags?** (number) - Optional - SQLITE_PREPARE_* flags. See [https://sqlite.org/c3ref/c_prepare_dont_log.html#sqlitepreparepersistent](https://sqlite.org/c3ref/c_prepare_dont_log.html#sqlitepreparepersistent) * **unscoped?** (boolean) - Optional - Set to `true` to give iterated statements an arbitrary lifetime, otherwise they are valid only within the scope of an iteration. ``` -------------------------------- ### Clone wa-sqlite Repository Source: https://github.com/powersync-ja/wa-sqlite/blob/master/README.md Clone the wa-sqlite repository to your local machine. ```bash git clone [this repo] ``` -------------------------------- ### Bind Null to Prepared Statement Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Binds a null value to a specific parameter index in a prepared statement. Binding indices start at 1. ```typescript sqlite3.bind_null(stmt, i); ``` -------------------------------- ### SQL Transaction with Write Hint Source: https://github.com/powersync-ja/wa-sqlite/blob/master/demo/write-hint/index.html This SQL transaction simulates a write hint using PRAGMA and inserts data into a table, returning the inserted value if a condition is met. It's designed for deadlock-free synchronization. ```sql PRAGMA write_hint; -- simulate fcntl write transaction hint WITH cnt AS ( SELECT COUNT() AS n FROM t ) INSERT INTO t SELECT * FROM cnt WHERE n < 500 RETURNING *; ``` -------------------------------- ### JavaScript for Web Worker or Window Execution Source: https://github.com/powersync-ja/wa-sqlite/blob/master/demo/hello/hello.html Loads the wa-sqlite script either in the main window or a web worker based on URL parameters. Uses MessageChannel for communication. ```javascript // Load script in the Window or in a Worker, depending on whether // the URL contains a "worker" query parameter. Use a MessageChannel // to communicate with the script. const { port1, port2 } = new MessageChannel(); const searchParams = new URLSearchParams(window.location.search); if (searchParams.has('worker')) { document.querySelector('h1').textContent = 'Running in a Worker'; const worker = new Worker('./hello.js', { type: 'module' }); worker.postMessage('messagePort', [port2]) } else { document.querySelector('h1').textContent = 'Running in the Window'; await import('./hello.js') window.postMessage('messagePort', '*', [port2]); } // Submit SQL over the MessageChannel. document.getElementById('submit').addEventListener('click', () => { port1.postMessage(document.getElementById('input').value); }); // Handle query results. port1.addEventListener('message', (event) => { console.log(event.data); const output = document.getElementById('output'); output.innerHTML = ''; if (Array.isArray(event.data)) { for (const { columns, rows } of event.data) { output.appendChild(buildHTMLTable(columns, rows)); } } else { output.textContent = 'Error: ' + event.data.error; } }); port1.start(); function buildHTMLTable(columns, rows) { function tx(tag, data) { const tx = document.createElement(tag); tx.textContent = data.toString(); return tx; } const table = document.createElement('table'); const thead = document.createElement('thead'); const tr = document.createElement('tr'); columns.forEach(column => tr.appendChild(tx('th', column))); thead.appendChild(tr); table.appendChild(thead); const tbody = document.createElement('tbody'); rows.forEach(row => { const tr = document.createElement('tr'); row.forEach(cell => tr.appendChild(tx('td', cell))); tbody.appendChild(tr); }); table.appendChild(tbody); return table; } ``` -------------------------------- ### vfs_register Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Registers a new Virtual File System (VFS) with SQLite. Optionally sets it as the default VFS. ```APIDOC ## vfs_register(vfs, makeDefault) ### Description Register a new Virtual File System. ### Parameters #### Path Parameters * **vfs** ([SQLiteVFS](SQLiteVFS.html)) - Required - VFS object * **makeDefault** (boolean) - Optional ### Returns number `SQLITE_OK` (throws exception on error) ### See [https://www.sqlite.org/c3ref/vfs_find.html](https://www.sqlite.org/c3ref/vfs_find.html) ``` -------------------------------- ### step Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Evaluates an SQL statement, returning SQLITE_ROW or SQLITE_DONE. ```APIDOC ## step(stmt) ### Description Evaluates an SQL statement. ### Parameters * **stmt** (number) - Required - prepared statement pointer ### Returns Promise - Promise resolving to `SQLITE_ROW` or `SQLITE_DONE` (rejects on error) ### See [https://www.sqlite.org/c3ref/step.html](https://www.sqlite.org/c3ref/step.html) ``` -------------------------------- ### exec Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Provides a one-step interface for executing SQL queries. It handles row copying and BigInt conversion for large integers, and can optionally accept a callback for processing output rows. ```APIDOC ## exec ### Description One-step query execution interface. The implementation of this function uses [row](SQLiteAPI.html#row), which makes a copy of blobs and returns BigInt for integers outside the safe integer bounds for Number. ### Parameters * **db**: number - database pointer * **zSQL**: string - queries * **callback**: ((row, columns) => void) - Optional callback called for each output row * **row**: [SQLiteCompatibleType](../types/SQLiteCompatibleType.html)[] * **columns**: string[] ### Returns * **Promise** - Promise resolving to `SQLITE_OK` (rejects on error) ### See [https://www.sqlite.org/c3ref/exec.html](https://www.sqlite.org/c3ref/exec.html) ``` -------------------------------- ### xFullPathname Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Converts a file name to its full path within the VFS. ```APIDOC ## xFullPathname ### Description Converts a file name to its full path within the VFS. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pVfs** (number) - Description not specified. * **zName** (number) - Description not specified. * **nOut** (number) - Description not specified. * **zOut** (number) - Description not specified. ### Returns * number | Promise - The result of the full path operation. ### See [https://sqlite.org/c3ref/vfs.html](https://sqlite.org/c3ref/vfs.html) ``` -------------------------------- ### statements Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Manages statement compilation by creating an async iterator that yields a prepared statement handle on each iteration. It is typically used with a `for await` loop. ```APIDOC ## statements(db, sql, options?) ### Description Compiles SQL statements and provides an async iterator for prepared statement handles. ### Parameters * **db** (number) - Required - database pointer * **sql** (string) - Required * **options** (SQLitePrepareOptions) - Optional ### Returns AsyncIterable ### See [https://www.sqlite.org/c3ref/prepare.html](https://www.sqlite.org/c3ref/prepare.html) ``` -------------------------------- ### sql Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves the SQL statement associated with a prepared statement pointer. ```APIDOC ## sql(stmt) ### Description Get statement SQL ### Parameters #### Path Parameters * **stmt** (number) - Required - prepared statement pointer ### Returns string SQL ``` -------------------------------- ### xDelete Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Deletes a file from the virtual file system. It takes the VFS pointer, the file name, and a sync directory flag as input. ```APIDOC ## xDelete ### Description Deletes a file from the virtual file system. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pVfs** (number) - Description not specified. * **zName** (number) - Description not specified. * **syncDir** (number) - Description not specified. ### Returns * number | Promise - The result of the delete operation. ### See [https://sqlite.org/c3ref/vfs.html](https://sqlite.org/c3ref/vfs.html) ``` -------------------------------- ### set_authorizer Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Registers a callback function to authorize SQL statement actions. It takes a database pointer, an authorization function, and user data. ```APIDOC ## set_authorizer(db, authFunction, userData) ### Description Register a callback function that is invoked to authorize certain SQL statement actions. ### Parameters #### Path Parameters * **db** (number) - Required - database pointer * **authFunction** ((userData, iActionCode, param3, param4, param5, param6) => number | Promise) - Required - * **Parameters** * **userData** (any) - * **iActionCode** (number) - * **param3** (string) - * **param4** (string) - * **param5** (string) - * **param6** (string) - #### Returns number | Promise * **userData** (any) - Required - ### Returns number ``` -------------------------------- ### progress_handler(db, nProgressOps, handler, userData) Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Specifies a callback to be invoked between long-running queries. ```APIDOC ## progress_handler(db, nProgressOps, handler, userData) ### Description Specify callback to be invoked between long-running queries The application data passed is ignored. Use closures instead. If any callback function returns a Promise, that function must be declared `async`, i.e. it must allow use of `await`. ### Parameters #### Path Parameters * **db** (number) - Required - database pointer * **nProgressOps** (number) - Required - target number of database operations between handler invocations * **handler** ((userData) => number | Promise) - Required * **userData** (any) - Required #### Returns number | Promise * **userData** (any) - Required ### Returns any ``` -------------------------------- ### xLock Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Acquires a lock on a file. ```APIDOC ## xLock ### Description Acquires a lock on a file. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pFile** (number) - Description not specified. * **lockType** (number) - Description not specified. ### Returns * number | Promise - The result of the lock operation. ### See [https://sqlite.org/c3ref/io_methods.html](https://sqlite.org/c3ref/io_methods.html) ``` -------------------------------- ### vfs_register Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Registers a new Virtual File System (VFS) with the SQLite instance. This allows for custom file system implementations. ```APIDOC ## vfs_register ### Description Registers a new Virtual File System (VFS) with the SQLite instance. This allows for custom file system implementations. ### Method (Not specified, likely a function call within a library) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **vfs**: (object) - Required - The VFS object to register. - **makeDefault**: (boolean) - Optional - If true, this VFS will be set as the default. ``` -------------------------------- ### xSectorSize Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Retrieves the sector size of the device associated with a file. ```APIDOC ## xSectorSize ### Description Retrieves the sector size of the device associated with a file. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pFile** (number) - Description not specified. ### Returns * number | Promise - The sector size of the device. ### See [https://sqlite.org/c3ref/io_methods.html](https://sqlite.org/c3ref/io_methods.html) ``` -------------------------------- ### column_names Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves the names of all columns for a prepared statement. ```APIDOC ## column_names(stmt) ### Description Get names for all columns of a prepared statement. This is a convenience function that calls [column_count](SQLiteAPI.html#column_count) and [column_name](SQLiteAPI.html#column_name). ### Parameters #### Path Parameters * **stmt** (number) ### Returns string[] - array of column names ``` -------------------------------- ### Execute an SQL Statement Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Evaluates a prepared SQL statement. It resolves to SQLITE_ROW for each row of data or SQLITE_DONE when execution is complete. Rejects on error. ```javascript await sqlite3.step(stmt) ``` -------------------------------- ### create_function Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Allows the creation or redefinition of SQL functions within the SQLite database. It supports asynchronous callback functions if Promises are involved. ```APIDOC ## create_function ### Description Create or redefine SQL functions. The application data passed is ignored. Use closures instead. If any callback function returns a Promise, that function must be declared `async`. ### Parameters * **db**: number - database pointer * **zFunctionName**: string * **nArg**: number - number of function arguments * **eTextRep**: number - text encoding (and other flags) * **pApp**: number - application data (ignored) * **xFunc**: ((context, values) => void | Promise) - Optional callback function * **context**: number * **values**: Uint32Array * **xStep**: ((context, values) => void | Promise) - Optional callback function * **context**: number * **values**: Uint32Array * **xFinal**: ((context) => void | Promise) - Optional callback function * **context**: number ### Returns * **number** - `SQLITE_OK` (throws exception on error) ### See [https://sqlite.org/c3ref/create_function.html](https://sqlite.org/c3ref/create_function.html) ``` -------------------------------- ### libversion_number() Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves the version of the SQLite library as a number. ```APIDOC ## libversion_number() ### Description Get SQLite library version. ### Returns number - version number, e.g. 3035005 ### See [https://www.sqlite.org/c3ref/libversion.html](https://www.sqlite.org/c3ref/libversion.html) ``` -------------------------------- ### xWrite Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Writes data to a file at a specified offset. This method is part of the VFS (Virtual File System) interface for SQLite. ```APIDOC ## xWrite ### Description Writes data to a file at a specified offset. This method is part of the VFS (Virtual File System) interface for SQLite. ### Method (Not specified, likely internal VFS callback) ### Endpoint (Not applicable, this is an interface method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **pFile** (number) - Description of pFile parameter. * **pData** (number) - Description of pData parameter. * **iAmt** (number) - Description of iAmt parameter. * **iOffsetLo** (number) - Description of iOffsetLo parameter. * **iOffsetHi** (number) - Description of iOffsetHi parameter. ### Returns * number | Promise - The result of the write operation. ``` -------------------------------- ### xFileControl Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteVFS.html Provides a mechanism for controlling file operations through the VFS. ```APIDOC ## xFileControl ### Description Provides a mechanism for controlling file operations through the VFS. ### Method (Not specified, likely internal VFS operation) ### Parameters #### Path Parameters * **pFile** (number) - Description not specified. * **op** (number) - Description not specified. * **pArg** (number) - Description not specified. ### Returns * number | Promise - The result of the file control operation. ### See [https://sqlite.org/c3ref/io_methods.html](https://sqlite.org/c3ref/io_methods.html) ``` -------------------------------- ### row Source: https://github.com/powersync-ja/wa-sqlite/blob/master/docs/interfaces/SQLiteAPI.html Retrieves all column data for a row from a prepared statement step. It returns a copy of the blob data and BigInt for large integers. ```APIDOC ## row(stmt) ### Description Get all column data for a row from a prepared statement step. This convenience function will return a copy of any blob, unlike [column_blob](SQLiteAPI.html#column_blob) which returns a value referencing volatile WASM memory with short validity. Like [column](SQLiteAPI.html#column), it will return a BigInt for integers outside the safe integer bounds for Number. ### Parameters #### Path Parameters * **stmt** (number) - Required - prepared statement pointer ### Returns [SQLiteCompatibleType](../types/SQLiteCompatibleType.html)[ ] row data ```