### Install Project Dependencies
Source: https://github.com/sql-js/sql.js/blob/master/CONTRIBUTING.md
Installs the necessary modules for the project. Run this after setting up the development environment.
```bash
npm install
```
--------------------------------
### Basic SQL Demo with SQL.js
Source: https://github.com/sql-js/sql.js/blob/master/examples/GUI/index.html
Demonstrates basic SQL operations including table creation, data insertion, and querying with aggregation and grouping. This is a fundamental example for understanding SQL.js capabilities.
```sql
-- Basic SQL Demo -- Create a simple employees table DROP TABLE IF EXISTS employees;
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
department TEXT,
salary NUMERIC,
hire_date DATE
);
-- Insert sample data
INSERT INTO employees (name, department, salary, hire_date)
VALUES ('Alice Smith', 'Engineering', 85000, '2020-01-15'),
('Bob Johnson', 'Marketing', 72000, '2019-03-20'),
('Carol Williams', 'Engineering', 92000, '2018-11-07'),
('Dave Brown', 'Finance', 115000, '2017-05-12'),
('Eve Davis', 'Engineering', 110000, '2021-08-30');
-- Query the data
SELECT department, COUNT(*) as employee_count, ROUND(AVG(salary), 2) as avg_salary
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;
```
--------------------------------
### Run Project Tests
Source: https://github.com/sql-js/sql.js/blob/master/CONTRIBUTING.md
Executes the project's test suite to ensure everything is functioning correctly. Run this after installing dependencies and after rebuilding the project.
```bash
npm test
```
--------------------------------
### Rebuild Project from Scratch
Source: https://github.com/sql-js/sql.js/blob/master/CONTRIBUTING.md
Recompiles the project from its source code, using the Emscripten SDK installed within the development environment. This is necessary after making changes to the build configuration or source files.
```bash
npm run rebuild
```
--------------------------------
### Retrieve Original and Normalized SQL Statements
Source: https://context7.com/sql-js/sql.js/llms.txt
Use `getSQL()` to get the original query and `getNormalizedSQL()` to get the canonical form with literals replaced by '?'. This is useful for debugging or understanding query transformations.
```javascript
const db = new SQL.Database();
db.run("CREATE TABLE test (x INTEGER);");
db.run("INSERT INTO test VALUES (1), (2), (3);");
const stmt = db.prepare("SELECT * FROM test WHERE x = 42");
stmt.step();
console.log(stmt.getSQL()); // "SELECT * FROM test WHERE x = 42"
console.log(stmt.getNormalizedSQL()); // "SELECT*FROM test WHERE x=?;";
stmt.free();
db.close();
```
--------------------------------
### Get Current Row as Object with `stmt.getAsObject()`
Source: https://context7.com/sql-js/sql.js/llms.txt
Returns the current row as a JavaScript object with column names as keys. This combines `getColumnNames()` and `get()`. Parameters can be passed directly, triggering bind and step automatically.
```javascript
const db = new SQL.Database();
db.run(`
CREATE TABLE books (isbn TEXT, title TEXT, author TEXT, year INTEGER);
INSERT INTO books VALUES
('978-0-7432-7357-1','The Road','Cormac McCarthy',2006),
('978-0-06-112008-4','To Kill a Mockingbird','Harper Lee',1960);
`);
const stmt = db.prepare("SELECT * FROM books WHERE year > $year ORDER BY year");
stmt.bind({ $year: 1990 });
while (stmt.step()) {
const book = stmt.getAsObject();
console.log(`${book.title} by ${book.author} (${book.year})`);
// The Road by Cormac McCarthy (2006)
}
stmt.free();
// Passing params directly to getAsObject (binds + steps automatically)
const stmt2 = db.prepare("SELECT title FROM books WHERE isbn = :isbn");
const result = stmt2.getAsObject({ ":isbn": "978-0-06-112008-4" });
console.log(result); // { title: 'To Kill a Mockingbird' }
stmt2.free();
db.close();
```
--------------------------------
### Execute SQL Off-Main-Thread with Web Worker API
Source: https://context7.com/sql-js/sql.js/llms.txt
Use the Web Worker build of sql.js to run SQL queries asynchronously, keeping the UI responsive. This example demonstrates opening a database, executing queries, and exporting data.
```javascript
// Main thread
const worker = new Worker('/dist/worker.sql-wasm.js');
let messageId = 0;
const pending = new Map();
worker.onmessage = ({ data }) => {
const resolve = pending.get(data.id);
if (resolve) {
pending.delete(data.id);
resolve(data);
}
};
worker.onerror = e => console.error('Worker error:', e);
function workerQuery(action, payload) {
return new Promise(resolve => {
const id = ++messageId;
pending.set(id, resolve);
worker.postMessage({ id, action, ...payload });
});
}
// Open an empty database
await workerQuery('open', {});
// Execute a query
const create = await workerQuery('exec', {
sql: `CREATE TABLE events (ts INTEGER, type TEXT, payload TEXT);
INSERT INTO events VALUES (1700000000,'click','button#submit');
INSERT INTO events VALUES (1700000001,'hover','nav#menu');`
});
// Query with params and BigInt config
const results = await workerQuery('exec', {
sql: "SELECT * FROM events WHERE type = $type",
params: { $type: 'click' },
config: { useBigInt: false }
});
console.log(results.results);
// [{ columns:['ts','type','payload'], values:[[1700000000,'click','button#submit']] }]
// Export and close
const { buffer } = await workerQuery('export', {});
console.log(`Exported ${buffer.byteLength} bytes`);
await workerQuery('close', {});
```
--------------------------------
### stmt.getAsObject(params?, config?)
Source: https://context7.com/sql-js/sql.js/llms.txt
Returns the current row as a plain JavaScript object where keys are column names. Combines the functionality of `getColumnNames()` and `get()`.
```APIDOC
## `stmt.getAsObject(params?, config?)` — Get the current row as a keyed object
Returns the current row as a plain JavaScript object where keys are column names. Combines the functionality of `getColumnNames()` and `get()`.
```javascript
const stmt = db.prepare("SELECT * FROM books WHERE year > $year ORDER BY year");
stmt.bind({ $year: 1990 });
while (stmt.step()) {
const book = stmt.getAsObject();
// book is an object like { isbn: '...', title: '...', author: '...', year: ... }
}
// Passing params directly to getAsObject
const stmt2 = db.prepare("SELECT title FROM books WHERE isbn = :isbn");
const result = stmt2.getAsObject({ ':isbn': '978-0-06-112008-4' });
// result is { title: 'To Kill a Mockingbird' }
```
```
--------------------------------
### Get Column Names with `stmt.getColumnNames()`
Source: https://context7.com/sql-js/sql.js/llms.txt
Retrieves an array of column name strings for the current result set. This method must be called after `step()` has been executed.
```javascript
const db = new SQL.Database();
db.run("CREATE TABLE t (alpha INTEGER, beta TEXT, gamma REAL);");
db.run("INSERT INTO t VALUES (1, 'hello', 2.5);");
const stmt = db.prepare("SELECT alpha, beta AS renamed, gamma FROM t");
stmt.step();
console.log(stmt.getColumnNames()); // ['alpha', 'renamed', 'gamma']
stmt.free();
// Using aliases and expressions
const stmt2 = db.prepare("SELECT 5 AS nbr, x'616200' AS data, NULL AS null_value;");
stmt2.step();
console.log(stmt2.getColumnNames()); // ['nbr', 'data', 'null_value']
stmt2.free();
db.close();
```
--------------------------------
### Get Current Row as Array with `stmt.get()`
Source: https://context7.com/sql-js/sql.js/llms.txt
Retrieves the current row's column values as an array after `step()` has been called. Can optionally accept bind parameters and a config object for options like `useBigInt`.
```javascript
const db = new SQL.Database();
db.run(`CREATE TABLE data (id INTEGER, val REAL, label TEXT, blob_col BLOB);`);
db.run(`INSERT INTO data VALUES (1, 3.14, 'pi', x'DEADBEEF');`);
const stmt = db.prepare("SELECT * FROM data WHERE id = ?");
stmt.bind([1]);
stmt.step();
const row = stmt.get();
console.log(row[0]); // 1 (INTEGER → number)
console.log(row[1]); // 3.14 (REAL → number)
console.log(row[2]); // 'pi' (TEXT → string)
console.log(row[3]); // Uint8Array([0xDE, 0xAD, 0xBE, 0xEF]) (BLOB)
// With BigInt support
stmt.reset();
stmt.bind([1]);
stmt.step();
const rowBig = stmt.get(null, { useBigInt: true });
console.log(typeof rowBig[0]); // 'bigint'
stmt.free();
db.close();
```
--------------------------------
### Initialize and Use SQL.js in Browser
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Demonstrates initializing SQL.js with a custom locateFile function and performing basic database operations like creating tables, inserting data, and querying.
```html
Output is in Javascript console
```
--------------------------------
### Load Database from Server using Fetch and sql.js
Source: https://github.com/sql-js/sql.js/wiki/Load-a-database-from-the-server
Use fetch to retrieve the database file as an ArrayBuffer and then initialize sql.js. Ensure the locateFile function points to the correct distribution folder.
```javascript
const sqlPromise = initSqlJs({
locateFile: file => `https://path/to/your/dist/folder/dist/${file}`
});
const dataPromise = fetch("/path/to/databse.sqlite").then(res => res.arrayBuffer());
const [SQL, buf] = await Promise.all([sqlPromise, dataPromise])
const db = new SQL.Database(new Uint8Array(buf));
```
--------------------------------
### Initialize SQL.js with WASM
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Demonstrates how to initialize SQL.js, specifying the location of the WebAssembly binary. This is crucial for loading the library asynchronously. Omit `locateFile` when running in Node.js.
```javascript
const initSqlJs = require('sql.js');
// or if you are in a browser:
// const initSqlJs = window.initSqlJs;
const SQL = await initSqlJs({
// Required to load the wasm binary asynchronously. Of course, you can host it wherever you want
// You can omit locateFile completely when running in node
locateFile: file => `https://sql.js.org/dist/${file}`
});
// Create a database
const db = new SQL.Database();
// NOTE: You can also use new SQL.Database(data) where
// data is an Uint8Array representing an SQLite database file
```
--------------------------------
### Prepare and Execute SQL Statements with Bindings
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Illustrates preparing an SQL statement with named parameters, binding values to these parameters, and fetching results as an object. Also shows binding values as an array and iterating through results.
```javascript
// Prepare an sql statement
const stmt = db.prepare("SELECT * FROM hello WHERE a=:aval AND b=:bval");
// Bind values to the parameters and fetch the results of the query
const result = stmt.getAsObject({':aval' : 1, ':bval' : 'world'});
console.log(result); // Will print {a:1, b:'world'}
// Bind other values
stmt.bind([0, 'hello']);
while (stmt.step()) console.log(stmt.get()); // Will print [0, 'hello']
// free the memory used by the statement
stmt.free();
// You can not use your statement anymore once it has been freed.
// But not freeing your statements causes memory leaks. You don't want that.
```
--------------------------------
### Initialization
Source: https://github.com/sql-js/sql.js/blob/master/documentation_index.md
The `initSqlJs` function is the entry point for the sql.js API. It takes a configuration object and returns a Promise that resolves to the main `SqlJs` object.
```APIDOC
## initSqlJs
### Description
Initializes the sql.js library and returns the main `SqlJs` object.
### Method
Function call
### Parameters
#### Arguments
- **config** (`SqlJsConfig`) - Optional - Configuration object for sql.js.
### Returns
- **Promise** - A Promise that resolves to the `SqlJs` object.
```
--------------------------------
### Initialize SQL.js and Load/Create Database
Source: https://github.com/sql-js/sql.js/blob/master/examples/persistent.html
This code initializes SQL.js, attempts to load a database from local storage, or creates a new one if it doesn't exist. It also sets up a configuration to locate the WASM file.
```javascript
var baseUrl = '../dist/'; function toBinArray(str) { var l = str.length, arr = new Uint8Array(l); for (var i = 0; i < l; i++) arr[i] = str.charCodeAt(i); return arr; } function toBinString(arr) { var uarr = new Uint8Array(arr); var strings = [], chunksize = 0xffff; for (var i = 0; i * chunksize < uarr.length; i++) { strings.push(String.fromCharCode.apply(null, uarr.subarray(i * chunksize, (i + 1) * chunksize))); } return strings.join(''); } var config = { locateFile: filename => `${baseUrl}/${filename}` } initSqlJs(config).then(function (SQL) { var dbstr = window.localStorage.getItem("viewcount.sqlite"); if (dbstr) { var db = new SQL.Database(toBinArray(dbstr)); } else { var db = new SQL.Database(); db.run("CREATE TABLE views (date INTEGER PRIMARY KEY)"); } db.run("INSERT INTO views(date) VALUES (?)", [Date.now()]); document.getElementById('views').textContent = db.exec("SELECT COUNT(*) FROM views")[0].values[0][0]; var count = 0, dates = document.getElementById("dates"); db.each("SELECT date FROM views ORDER BY date ASC", function callback(row) { var li = document.createElement("li"); li.textContent = new Date(row.date); dates.appendChild(li); }, function done() { var dbstr = toBinString(db.export()); window.localStorage.setItem("viewcount.sqlite", dbstr); } ); });
```
--------------------------------
### Get Rows Modified with `db.getRowsModified()`
Source: https://context7.com/sql-js/sql.js/llms.txt
Retrieve the number of rows affected by the last INSERT, UPDATE, or DELETE statement using `db.getRowsModified()`. This is useful for tracking changes made by a specific query.
```javascript
const db = new SQL.Database();
db.run("
CREATE TABLE tasks (id INTEGER, status TEXT, priority INTEGER);
INSERT INTO tasks VALUES (1,'pending',1),(2,'pending',2),(3,'done',1),(4,'pending',3);
");
db.run("UPDATE tasks SET status = 'active' WHERE status = 'pending' AND priority > 1");
console.log(db.getRowsModified()); // 2
db.run("DELETE FROM tasks WHERE status = 'done'");
console.log(db.getRowsModified()); // 1
db.run("INSERT INTO tasks VALUES (5, 'pending', 5)");
console.log(db.getRowsModified()); // 1
db.close();
```
--------------------------------
### initSqlJs(config)
Source: https://context7.com/sql-js/sql.js/llms.txt
Asynchronously loads and initializes the sql.js WebAssembly module. This must be called before creating any Database or Statement objects. The `locateFile` config property specifies the path to the WebAssembly binary.
```APIDOC
## initSqlJs(config) — Initialize the sql.js module
Asynchronously loads and initializes the sql.js WebAssembly module. Must be called before any `Database` or `Statement` can be created. The `locateFile` config property tells the loader where to find the `.wasm` binary.
```javascript
// Browser usage
const SQL = await initSqlJs({
locateFile: file => `https://sql.js.org/dist/${file}`
});
const db = new SQL.Database();
db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);");
db.run("INSERT INTO users VALUES (1, 'Alice', 30), (2, 'Bob', 25);");
const result = db.exec("SELECT * FROM users;");
console.log(result);
// [{ columns: ['id', 'name', 'age'], values: [[1, 'Alice', 30], [2, 'Bob', 25]] }]
db.close();
// Node.js usage
const initSqlJs = require('sql.js');
const SQL = await initSqlJs();
const db = new SQL.Database();
db.run("CREATE TABLE t (x TEXT);");
db.run("INSERT INTO t VALUES ('hello');");
console.log(db.exec("SELECT * FROM t;"));
// [{ columns: ['x'], values: [['hello']] }]
db.close();
```
```
--------------------------------
### Initialize SQL.js and Create Database
Source: https://github.com/sql-js/sql.js/blob/master/examples/simple.html
Initializes the SQL.js library with a custom file locator and creates a new in-memory database. The `locateFile` function is necessary when the WASM file is not in the same directory as the HTML page.
```javascript
config = { locateFile: (filename, prefix) => { console.log(`prefix is : ${prefix}`); return `../dist/${filename}`; } }
// The `initSqlJs` function is globally provided by all of the main dist files if loaded in the browser.
// We must specify this locateFile function if we are loading a wasm file from anywhere other than the current html page's folder.
initSqlJs(config).then(function (SQL) {
//Create the database
var db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE test (col1, col2);");
// Insert two rows: (1,111) and (2,222)
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1, 111, 2, 222]);
// Prepare a statement
var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({ $start: 1, $end: 1 });
// {col1:1, col2:111}
// Bind new values
stmt.bind({ $start: 1, $end: 2 });
while (stmt.step()) {
// var row = stmt.getAsObject();
console.log('Here is a row: ' + JSON.stringify(row));
}
});
```
--------------------------------
### Initialize and Execute SQL in Browser
Source: https://github.com/sql-js/sql.js/blob/master/examples/repl.html
This snippet initializes a SQL.js database and sets up an event listener to execute SQL queries entered by the user. It displays the results or any errors encountered.
```javascript
var db;
initSqlJs({ locateFile: filename => `../dist/${filename}` }).then(function (SQL) {
db = new SQL.Database();
});
document.getElementById('submit').onclick = function () {
var sql = document.getElementById('input').value;
var result = '', error = '';
try {
result = db.exec(sql);
} catch (e) {
error = e;
}
document.getElementById('result').innerHTML = JSON.stringify(result, null, ' ');
document.getElementById('error').innerHTML = error;
};
```
--------------------------------
### Create or Open a Database
Source: https://context7.com/sql-js/sql.js/llms.txt
Constructs a new in-memory SQLite database. Pass a Uint8Array of an existing .sqlite file's bytes to open it; omit the argument to create a fresh empty database.
```javascript
// Create a new empty database
const db = new SQL.Database();
```
```javascript
// Open an existing .sqlite file in Node.js
const fs = require('fs');
const fileBuffer = fs.readFileSync('mydata.sqlite');
const db = new SQL.Database(fileBuffer);
db.exec("SELECT name FROM sqlite_master WHERE type='table';").forEach(r => {
console.log('Table:', r.values);
});
db.close();
```
```javascript
// Open a database fetched from a server in the browser
const sqlPromise = initSqlJs({ locateFile: f => `/dist/${f}` });
const dataPromise = fetch('/data/mydb.sqlite').then(res => res.arrayBuffer());
const [SQL, buf] = await Promise.all([sqlPromise, dataPromise]);
const db = new SQL.Database(new Uint8Array(buf));
console.log(db.exec("SELECT COUNT(*) FROM products;"));
// [{ columns: ['COUNT(*)'], values: [[42]] }]
db.close();
```
--------------------------------
### Use SQL.js as a Web Worker
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Demonstrates setting up and communicating with a SQL.js web worker to perform database operations off the main thread. Includes opening the database and executing queries.
```html
```
--------------------------------
### Execute SQL and Retrieve Results
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Demonstrates executing a SQL query using `db.exec()` and shows the expected structure of the returned results, which includes columns and values.
```javascript
const res = db.exec("SELECT * FROM hello");
/*
[
{columns:['a','b'], values:[[0,'hello'],[1,'world']]}
]
*/
```
--------------------------------
### new SQL.Database(data?)
Source: https://context7.com/sql-js/sql.js/llms.txt
Constructs a new in-memory SQLite database. You can either create a fresh empty database or open an existing `.sqlite` file by passing its bytes as a `Uint8Array`.
```APIDOC
## new SQL.Database(data?) — Create or open a database
Constructs a new in-memory SQLite database. Pass a `Uint8Array` of an existing `.sqlite` file's bytes to open it; omit the argument to create a fresh empty database.
```javascript
// Create a new empty database
const db = new SQL.Database();
// Open an existing .sqlite file in Node.js
const fs = require('fs');
const fileBuffer = fs.readFileSync('mydata.sqlite');
const db = new SQL.Database(fileBuffer);
db.exec("SELECT name FROM sqlite_master WHERE type='table';").forEach(r => {
console.log('Table:', r.values);
});
db.close();
// Open a database fetched from a server in the browser
const sqlPromise = initSqlJs({ locateFile: f => `/dist/${f}` });
const dataPromise = fetch('/data/mydb.sqlite').then(res => res.arrayBuffer());
const [SQL, buf] = await Promise.all([sqlPromise, dataPromise]);
const db = new SQL.Database(new Uint8Array(buf));
console.log(db.exec("SELECT COUNT(*) FROM products;"));
// [{ columns: ['COUNT(*)'], values: [[42]] }]
db.close();
```
```
--------------------------------
### Create and Use Custom JavaScript Functions in SQL
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Explains how to define a JavaScript function and register it as a custom SQL function using `db.create_function()`. This allows SQL queries to leverage custom logic.
```javascript
// You can create custom aggregation functions, by passing a name
// and a set of functions to `db.create_aggregate`:
//
// - an `init` function. This function receives no argument and returns
// the initial value for the state of the aggregate function.
// - a `step` function. This function takes two arguments
// - the current state of the aggregation
// - a new value to aggregate to the state
// It should return a new value for the state.
// - a `finalize` function. This function receives a state object, and
// returns the final value of the aggregate. It can be omitted, in which case
// the final value of the state will be returned directly by the aggregate function.
//
// Here is an example aggregation function, `json_agg`, which will collect all
// input values and return them as a JSON array:
db.create_aggregate(
"json_agg",
{
init: () => [],
step: (state, val) => [...state, val],
finalize: (state) => JSON.stringify(state),
}
);
db.exec("SELECT json_agg(column1) FROM (VALUES ('hello'), ('world'))");
// -> The result of the query is the string '["hello","world"]'
```
--------------------------------
### Create and Use Custom JavaScript Functions in SQL
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Explains how to define a JavaScript function and register it as a custom SQL function using `db.create_function()`. This allows SQL queries to leverage custom logic.
```javascript
// You can use JavaScript functions inside your SQL code
// Create the js function you need
function add(a, b) {return a+b;}
// Specifies the SQL function's name, the number of it's arguments, and the js function to use
db.create_function("add_js", add);
// Run a query in which the function is used
db.run("INSERT INTO hello VALUES (add_js(7, 3), add_js('Hello ', 'world'));"); // Inserts 10 and 'Hello world'
```
--------------------------------
### Load Database from Server using Fetch
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Asynchronously loads an SQLite database file from a server using the Fetch API. Requires the SQL.js library to be initialized.
```javascript
const sqlPromise = initSqlJs({
locateFile: file => `https://path/to/your/dist/folder/dist/${file}`
});
const dataPromise = fetch("/path/to/database.sqlite").then(res => res.arrayBuffer());
const [SQL, buf] = await Promise.all([sqlPromise, dataPromise])
const db = new SQL.Database(new Uint8Array(buf));
```
--------------------------------
### Create and Use Prepared Statements with `db.prepare`
Source: https://context7.com/sql-js/sql.js/llms.txt
Compile SQL into a reusable `Statement` object using `db.prepare` for efficiency with repeated executions. Remember to free statements with `stmt.free()` when done. Supports named parameters.
```javascript
const db = new SQL.Database();
db.run("CREATE TABLE logs (level TEXT, message TEXT, ts INTEGER);");
const stmt = db.prepare(
"INSERT INTO logs (level, message, ts) VALUES (:level, :msg, :ts)"
);
const entries = [
{ ':level': 'INFO', ':msg': 'Server started', ':ts': 1700000001 },
{ ':level': 'WARN', ':msg': 'High memory usage', ':ts': 1700000045 },
{ ':level': 'ERROR', ':msg': 'Connection failed', ':ts': 1700000102 },
];
entries.forEach(entry => stmt.run(entry));
stmt.free(); // Always free prepared statements
console.log(db.exec("SELECT * FROM logs WHERE level='ERROR';"));
// [{ columns: ['level','message','ts'], values: [['ERROR','Connection failed',1700000102]] }]
db.close();
```
--------------------------------
### Load SQL.js Asynchronously (v1.x)
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Version 1.x of SQL.js requires asynchronous loading. Use the `initSqlJs` function, providing a `locateFile` callback to specify the path to the WebAssembly loader.
```html
```
```javascript
const initSqlJs = require('sql-wasm.js');
initSqlJs().then(function(SQL){
const db = new SQL.Database();
//...
});
```
--------------------------------
### Initialize sql.js Module
Source: https://context7.com/sql-js/sql.js/llms.txt
Asynchronously loads and initializes the sql.js WebAssembly module. Must be called before creating Database or Statement objects. The locateFile config property specifies the path to the .wasm binary.
```javascript
// Browser usage
const SQL = await initSqlJs({
locateFile: file => `https://sql.js.org/dist/${file}`
});
const db = new SQL.Database();
db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);");
db.run("INSERT INTO users VALUES (1, 'Alice', 30), (2, 'Bob', 25);");
const result = db.exec("SELECT * FROM users;");
console.log(result);
// [{ columns: ['id', 'name', 'age'], values: [[1, 'Alice', 30], [2, 'Bob', 25]] }]
db.close();
```
```javascript
// Node.js usage
const initSqlJs = require('sql.js');
const SQL = await initSqlJs();
const db = new SQL.Database();
db.run("CREATE TABLE t (x TEXT);");
db.run("INSERT INTO t VALUES ('hello');");
console.log(db.exec("SELECT * FROM t;"));
// [{ columns: ['x'], values: [['hello']] }]
db.close();
```
--------------------------------
### Enable BigInt Support in SQL.js
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Use the `useBigInt: true` configuration option when preparing statements or executing queries to enable BigInt support. This allows retrieving BigInt values from the database.
```html
```
```html
```
--------------------------------
### Query and Display BLOB Image in Browser
Source: https://github.com/sql-js/sql.js/wiki/Display-an-image-stored-in-a-BLOB-in-a-browser
Fetches image data from a SQL.js database and creates a URL to display it. Ensure the database is initialized and the table contains BLOB data.
```javascript
var stmt = db.prepare("SELECT image FROM test WHERE id=$id"); // SQL statement
var uarray = stmt.getAsObject({$id:1})['image']; // UInt8Array containing the bytes of the image
// (of course you can use other API methods to query your database
stmt.free(); // Free the memory used by the statement
// The tricky part : create a blob url to your image, that you can use anywhere
var objurl = window.URL.createObjectURL(new Blob([uarray]));
var img = new Image();
img.src = objurl;
img.onload = function() {
// do something with your image
}
```
--------------------------------
### RequireJS Configuration and SQL.js Initialization
Source: https://github.com/sql-js/sql.js/blob/master/examples/requireJS.html
Configures RequireJS to load SQL.js from a specified base URL and initializes the library. It includes error handling for module loading failures.
```javascript
var baseUrl = '../dist'
require.config({ baseUrl: baseUrl});
// Options: 'sql-wasm', 'sql-asm', 'sql-asm-memory-growth.js', 'sql-wasm-debug', 'sql-asm-debug'
require(['sql-wasm'], function success(initSqlJs) {
console.log(typeof initSqlJs);
if (typeof initSqlJs !== 'function') {
document.body.style.backgroundColor = 'red';
console.log('initSqlJs returned: ', initSqlJs);
alert("Failed to require sql.js through AMD");
return;
}
// The `initSqlJs` function is globally provided by all of the main dist files if loaded in the browser.
// We must specify this locateFile function if we are loading a wasm file from anywhere other than the current html page's folder.
var config = {
locateFile: filename => `${baseUrl}/${filename}`
}
initSqlJs(config).then(function (SQL) {
//Create the database
var db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE test (col1, col2);");
// Insert two rows: (1,111) and (2,222)
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1, 111, 2, 222]);
// Prepare a statement
var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({ $start: 1, $end: 1 });
// {col1:1, col2:111}
// Bind new values
stmt.bind({ $start: 1, $end: 2 });
while (stmt.step()) {
// var row = stmt.getAsObject();
// [...]
// do something with the row of result
console.log('Here is a row: ', row);
}
});
}, function error(err) {
document.body.style.backgroundColor = 'red';
console.log(err);
alert("Module load failed: " + err);
});
Output is in Javscript console
```
--------------------------------
### Export Database to Uint8Array
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Demonstrates how to export the current state of the SQLite database into a `Uint8Array`, which can be saved as a file or transferred.
```javascript
// Export the database to an Uint8Array containing the SQLite database file
const binaryArray = db.export();
```
--------------------------------
### Load Database from User File Input
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Handles loading an SQLite database file selected by the user through an HTML input element. Requires an existing HTML element with id 'dbFileElm'.
```javascript
dbFileElm.onchange = () => {
const f = dbFileElm.files[0];
const r = new FileReader();
r.onload = function() {
const Uints = new Uint8Array(r.result);
db = new SQL.Database(Uints);
}
r.readAsArrayBuffer(f);
}
```
--------------------------------
### Write Database to Disk in Node.js
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Exports the current database state to a buffer and writes it to a file on disk using Node.js 'fs' module.
```javascript
const fs = require("fs");
// [...] (create the database)
const data = db.export();
const buffer = Buffer.from(data);
fs.writeFileSync("filename.sqlite", buffer);
```
--------------------------------
### db.prepare(sql, params?)
Source: https://context7.com/sql-js/sql.js/llms.txt
Compiles an SQL string into a reusable `Statement` object. Prepared statements are more efficient for repeated execution and support parameter binding. Remember to free the statement using `stmt.free()` when done.
```APIDOC
## `db.prepare(sql, params?)` — Create a prepared statement
Compiles an SQL string into a reusable `Statement` object. Prepared statements are more efficient for repeated execution and support parameter binding. Must be freed with `stmt.free()` when done.
```javascript
const db = new SQL.Database();
db.run("CREATE TABLE logs (level TEXT, message TEXT, ts INTEGER);");
const stmt = db.prepare(
"INSERT INTO logs (level, message, ts) VALUES (:level, :msg, :ts)"
);
const entries = [
{ ':level': 'INFO', ':msg': 'Server started', ':ts': 1700000001 },
{ ':level': 'WARN', ':msg': 'High memory usage', ':ts': 1700000045 },
{ ':level': 'ERROR', ':msg': 'Connection failed', ':ts': 1700000102 },
];
entries.forEach(entry => stmt.run(entry));
stmt.free(); // Always free prepared statements
console.log(db.exec("SELECT * FROM logs WHERE level='ERROR';"));
// [{ columns: ['level','message','ts'], values: [['ERROR','Connection failed',1700000102]] }]
db.close();
```
```
--------------------------------
### Read Database from Disk in Node.js
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Reads an SQLite database file from the disk using Node.js 'fs' module and initializes SQL.js with the file buffer.
```javascript
const fs = require('fs');
const initSqlJs = require('sql-wasm.js');
const filebuffer = fs.readFileSync('test.sqlite');
initSqlJs().then(function(SQL){
// Load the db
const db = new SQL.Database(filebuffer);
});
```
--------------------------------
### Load SQL.js Synchronously (Pre v1.x)
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Prior to version 1.x, SQL.js could be loaded synchronously using a script tag or require.
```html
```
```javascript
const SQL = require('sql.js');
const db = new SQL.Database();
//...
```
--------------------------------
### Load SQLite Database from File in Node.js
Source: https://github.com/sql-js/sql.js/wiki/Use-from-node
Use this snippet to load an existing SQLite database file from your filesystem into sql.js. Ensure you have the 'fs' and 'path' modules available in your Node.js environment.
```javascript
//Node filesystem module - You know that.
var fs = require('fs');
//Ditto, path module
var path = require('path');
//Actual path I'm using to get to sql.js in my project.
var SQL = require('sql.js');
var filebuffer = fs.readFileSync(path.resolve('test.sqlite'));
// Load the db
var db = new SQL.Database(filebuffer);
//[{"columns":["id","content"],"values":[["0","hello"],["1","world"]]}]
console.dir(db.exec("SELECT * FROM test WHERE ID <= 10"));
```
--------------------------------
### stmt.get(params?, config?)
Source: https://context7.com/sql-js/sql.js/llms.txt
Returns the current row's column values as an array after `step()` has been called. Optionally accepts bind parameters and a config object.
```APIDOC
## `stmt.get(params?, config?)` — Get the current row as an array
Returns the current row's column values as an array after `step()` has been called. Optionally accepts bind parameters (triggers a `bind` + `step` internally) and a config object (e.g., `{ useBigInt: true }`).
```javascript
const stmt = db.prepare("SELECT * FROM data WHERE id = ?");
stmt.bind([1]);
stmt.step();
const row = stmt.get();
// row is an array of column values
// With BigInt support
stmt.reset();
stmt.bind([1]);
stmt.step();
const rowBig = stmt.get(null, { useBigInt: true });
```
```
--------------------------------
### db.each(sql, params, callback, done?, config?)
Source: https://context7.com/sql-js/sql.js/llms.txt
Executes a query and calls a provided callback function for each result row. An optional callback can be provided to be executed once all rows have been processed.
```APIDOC
## `db.each(sql, params, callback, done?, config?)` — Iterate rows with a callback
Executes a query and calls `callback` once per result row as a plain JavaScript object. Optionally calls `done` when all rows have been processed.
```javascript
const db = new SQL.Database();
db.run (
"CREATE TABLE products (name TEXT, price REAL, in_stock INTEGER);";
INSERT INTO products VALUES ('Apple', 0.5, 1), ('Banana', 0.3, 1),
('Cherry', 2.0, 0), ('Date', 5.0, 1);
"
);
const affordable = [];
db.each(
"SELECT name, price FROM products WHERE price < $max AND in_stock = 1",
{ $max: 3.0 },
function(row) {
affordable.push(row);
console.log(`${row.name}: $${row.price}`);
// Apple: $0.5
// Banana: $0.3
},
function() {
console.log(`Found ${affordable.length} affordable products`);
// Found 2 affordable products
}
);
db.close();
```
```
--------------------------------
### Execute Multiple SQL Statements
Source: https://github.com/sql-js/sql.js/blob/master/README.md
Shows how to execute a single string containing multiple SQL statements using `db.run()`. This method does not return any results.
```javascript
let sqlstr = "CREATE TABLE hello (a int, b char); \nINSERT INTO hello VALUES (0, 'hello'); \nINSERT INTO hello VALUES (1, 'world');";
db.run(sqlstr); // Run the query without returning anything
```
--------------------------------
### db.exec(sql, params?, config?)
Source: https://context7.com/sql-js/sql.js/llms.txt
Executes one or more SQL statements and returns all results. Each result object contains column names and row values for statements that produce rows.
```APIDOC
## `db.exec(sql, params?, config?)` — Execute SQL and return all results
Executes one or more SQL statements and returns an array of result objects, one per statement that produces rows. Each result has `columns` (array of column names) and `values` (array of row arrays).
```javascript
const db = new SQL.Database();
db.run(`
CREATE TABLE employees (id INTEGER, dept TEXT, salary REAL);
INSERT INTO employees VALUES
(1,'Engineering',95000),(2,'Engineering',110000),
(3,'Marketing',75000),(4,'Marketing',80000);
`);
// Multiple statements in one exec call
const results = db.exec(
`
SELECT dept, COUNT(*) AS headcount FROM employees GROUP BY dept;
SELECT dept, AVG(salary) AS avg_salary FROM employees GROUP BY dept;
`
);
console.log(results[0]);
// { columns: ['dept', 'headcount'], values: [['Engineering', 2], ['Marketing', 2]] }
console.log(results[1]);
// { columns: ['dept', 'avg_salary'], values: [['Engineering', 102500], ['Marketing', 77500]] }
// Exec with named parameters
const filtered = db.exec(
"SELECT * FROM employees WHERE salary > $min AND dept = $dept",
{ $min: 80000, $dept: 'Engineering' }
);
console.log(filtered);
// [{ columns: ['id','dept','salary'], values: [[1,'Engineering',95000],[2,'Engineering',110000]] }]
// Exec with BigInt support for large integers
const bigResult = db.exec("SELECT 9007199254740993 AS big_num", {}, { useBigInt: true });
console.log(bigResult[0].values[0][0]); // 9007199254740993n (BigInt)
db.close();
```
```
--------------------------------
### Convert Database to Binary String for Storage
Source: https://github.com/sql-js/sql.js/wiki/Persisting-a-Modified-Database
Converts the exported database array buffer to a binary string suitable for storage in localStorage. Handles large data by chunking.
```javascript
function toBinString (arr) {
var uarr = new Uint8Array(arr);
var strings = [], chunksize = 0xffff;
// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
for (var i=0; i*chunksize < uarr.length; i++){
strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize)));
}
return strings.join('');
}
window.localStorage.setItem("mydata", toBinString(db.export()));
```
--------------------------------
### Load SQL.js with RequireJS (AMD)
Source: https://github.com/sql-js/sql.js/blob/master/test/sql-requireJS.html
Configure RequireJS to load the sql.js module and handle success or error callbacks. This is useful for managing dependencies in AMD-compliant projects.
```javascript
require.config({ baseUrl: '../js' });
require(['sql'], function success (SQL){
if (typeof SQL !== 'object') {
document.body.style.backgroundColor = 'red';
alert("Failed to require sql.js through AMD");
} else {
document.body.style.backgroundColor = 'green';
alert("sql.js successfully loaded with AMD");
}
}, function error(err) {
console.log(err);
alert("Module load failed");
});
```
--------------------------------
### Convert String to Binary Array for Database Loading
Source: https://github.com/sql-js/sql.js/wiki/Persisting-a-Modified-Database
Converts a binary string retrieved from localStorage back into a Uint8Array, which is required to initialize a new SQL.js database instance.
```javascript
function toBinArray (str) {
var l = str.length,
arr = new Uint8Array(l);
for (var i=0; i {
const uInt8Array = new Uint8Array(xhr.response);
const db = new SQL.Database(uInt8Array);
const contents = db.exec("SELECT * FROM my_table");
// contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
};
xhr.send();
```