SQLite
DATA.init() with sqlite://, the connection string, the results and errors, and the SQLite client.
On this page
DATA.init() with a sqlite:// connection string, what the SQLite adapter returns, the operators of the payload, the errors and the client total5/client-sqlite. The methods of the QueryBuilder are in the reference of QueryBuilder. An introduction with examples is in the guide SQLite.
API
method
DATA.init([name], [connection], [onerror])
Registers a SQLite connection for the QueryBuilder.
DATA.init([name], [connection], [onerror])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The connection name. Default: 'default' |
connection? |
String |
The connection string: sqlite://filename?options. See the connection string. |
onerror? |
Function |
function(message) called for every failed query. |
The engine is chosen by the connection string: sqlite: registers SQLite, any other string PostgreSQL. It registers an adapter (NEWDB()) with the name name. The connection default serves the tables without a prefix, any other connection the tables with its prefix (DATA.find('logs/tbl_request')). Calling it again with the same name closes the open connections and replaces them. With null instead of connection the connection is removed and closed. Every failed query is passed to onerror as a text with the error and the first 100 characters of the SQL; without onerror it is logged with ERROR(name). The callback of the query gets the error in both cases.
It needs Node.js 22.16 or newer. The file is opened by the first query.
DATA.init('default', CONF.database);
DATA.init('logs', 'sqlite://databases/logs.db?wal=1');
DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);
type
sqlite://filename?options
The database file and its options.
sqlite://filename?options| Parameter | Type | Description |
|---|---|---|
pooling? |
Number |
The maximum number of connections (only in DATA.init()). A database in the memory always has one. Default: 1 |
schema? |
String |
A name put before the tables (only in DATA.init()): DATA.find('tbl_product') reads schema.tbl_product. builder.schema(name) changes it for one query. Raw queries do not use it. |
wal? |
Boolean |
Switches the database to the WAL journal mode. Default: false |
readonly? |
Boolean |
Opens the file for reading only. A missing file gives the error unable to open database file. Default: false |
foreignkeys? |
Boolean |
Checks the foreign keys. Default: true |
timeout? |
Number |
How long in milliseconds a query waits for a locked database before it fails with database is locked. The process is not blocked while it waits. 0 fails at once. Default: 5000 |
sqlite://databases/eshop.db is relative to the root of the application in DATA.init() and to the working directory of the process in the client, sqlite:///data/eshop.db is an absolute path and sqlite:// is a database in the memory. The file name is decoded with decodeURIComponent(). Other options are ignored. For a true or false option write 1 or true; anything else is false.
A connection that comes back to the pool inside an open transaction is rolled back. An idle connection closes after 10 seconds; the connection of a database in the memory stays open.
database : sqlite://databases/eshop.db?wal=1
DATA.init('reports', 'sqlite://databases/eshop.db?readonly=1&timeout=1000');
type
{ '+stock': 5, '=dtupdated': 'CURRENT_TIMESTAMP' }
Keys of the update() payload that change the value in the database.
{ '+stock': 5, '=dtupdated': 'CURRENT_TIMESTAMP' }The first character of a key in the payload of update():
| Key | SQL |
|---|---|
+name, -name, *name, /name | "name"=COALESCE("name",0)+$1 (and -, *, /) |
>name | "name"=MAX("name",$1) |
<name | "name"=MIN("name",$1) |
!name | "name"=NOT "name" |
=name | "name"=value, the value is raw SQL |
#name | The same as =, but insert() leaves the key out |
In insert() (also the insert of an upsert) the character is removed: the column gets the value (0 when it is empty), ! inserts 0 and = inserts the raw SQL. Keys without an operator are sent as parameters. MAX() and MIN() of SQLite return NULL when one value is NULL.
DATA.update('tbl_product', { '+stock': 5, dtupdated: NOW }).id('p1').callback(console.log);
var id = NOW.format('yyyy-MM-dd');
DATA.update('tbl_visitor', { '+count': 1, dtupdated: NOW }, true).id(id).insert(doc => doc.id = id).callback(console.log);
type
callback(err, response)
What each operation of the QueryBuilder returns on SQLite.
callback(err, response)| Operation | Response |
|---|---|
find() | An array of rows. |
read() | One row or null. |
list() | { items, count, page, limit, pages }; the adapter runs the page and SELECT COUNT(1). |
check() | true or false. |
count() | A number. |
scalar() | A number for sum, avg, min, max and count; rows { key, value } for group. |
insert() | The number of inserted rows, the value of the primarykey() column, or the inserted row with returning(). |
update() | The number of changed rows, an array of rows with returning(), one row with returning() and first(). |
remove() | The number of removed rows, or an array of rows with returning(). |
query() | An array of rows; with several statements the rows of the last one. |
truncate(), drop() | Run DELETE FROM … and DROP TABLE …. |
The values are converted by the declared type of the column: BOOLEAN is a Boolean; DATE, DATETIME and TIMESTAMP are Date objects; JSON and JSONB are parsed (texts in the ISO date format become Date objects); a BLOB is a Buffer; an integer that does not fit into a JavaScript number is a String.
DATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);
// null { id: 'p3', dtcreated: 2026-12-02T16:19:22.120Z }
type
err
The error of a failed query.
errAn error of SQLite is an Error with the message of SQLite and the fields code (ERR_SQLITE_ERROR), errcode (the extended result code, for example 1555 for a duplicate primary key, 787 for a foreign key, 5 for a locked database) and errstr (the text of the result code). Errors of the client are Connection is closed, Pool is closed and Multiple statements can't be used with parameters.
DATA.insert('tbl_product', { id: 'p1' }).callback(function(err, response) {
if (err)
console.log(err.errcode, err.message);
// 1555 UNIQUE constraint failed: tbl_product.id
});
method
require('total5/client-sqlite')
The SQLite client without the QueryBuilder.
require('total5/client-sqlite')Returns Object The module.
The module exports connect(), pool(), types and the classes Client and Pool, the same API as the client of PostgreSQL. The adapter of DATA.init() uses the same module, so a change in types applies to both.
const SQLite = require('total5/client-sqlite');
method
SQLite.connect(options, callback)
Opens one connection.
SQLite.connect(options, callback)| Parameter | Type | Description |
|---|---|---|
options |
String|Object |
The connection string or the options. |
callback |
Function |
function(err, client). |
Returns Client
options is a connection string, a file name, or an object with filename (or connectionString), wal, readonly, foreignkeys and timeout (milliseconds). Close the connection with client.end() or client.close(). Every connection to is a new empty database.
const SQLite = require('total5/client-sqlite');
SQLite.connect({ filename: PATH.databases('eshop.db'), wal: true }, async function(err, client) {
var response = await client.query('SELECT $1 + 1 AS value', [41]);
console.log(response.rows); // [ { value: 42 } ]
client.close();
});
method
SQLite.pool(options, [max])
Creates a pool of connections.
SQLite.pool(options, [max])| Parameter | Type | Description |
|---|---|---|
options |
String|Object |
The connection string or the options of SQLite.connect(). |
max? |
Number |
The maximum number of connections. Default: 4 |
Returns Pool
The pool opens up to max connections and reuses them. When options is an object, max and idle (milliseconds an idle connection stays open, default 10000) can be in it too. The option pooling of the connection string is not used here. A pool of a database in the memory always has one connection.
const SQLite = require('total5/client-sqlite');
const pool = SQLite.pool('sqlite://' + PATH.databases('eshop.db') + '?wal=1');
pool.query('SELECT id FROM tbl_product WHERE price>$1', [100], function(err, response) {
console.log(response.rows);
});
method
pool.connect(callback)
Borrows a connection from the pool.
pool.connect(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(err, client, release). |
The callback gets the connection and a release function that returns it to the pool (client.release() does the same). An open transaction is rolled back when the connection is released.
pool.connect(async function(err, client, release) {
if (err) {
console.log(err);
return;
}
try {
await client.query('BEGIN IMMEDIATE');
await client.query('UPDATE tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);
await client.query('INSERT INTO tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
} finally {
release();
}
});
method
client.query(sql, [params], [callback])
Runs a query on the connection.
client.query(sql, [params], [callback])| Parameter | Type | Description |
|---|---|---|
sql |
String |
The SQL. |
params? |
Array|Object |
The values of the parameters. |
callback? |
Function |
function(err, response). |
Returns Promise Without callback. The response is { command, rowCount, rows, fields, lastid }.
The parameters are $1, $2… or ? with an array, and :name, @name or $name with an object. Without parameters the SQL can have several statements; the response is then an array with one result for each statement. In the parameters a Date is sent as ISO 8601 text in UTC, a Boolean as 1 or 0, an array or an object as JSON, a Buffer as binary data and undefined as NULL.
fields is an array of { name, type } with the declared types, and lastid is the rowid of the last inserted row after an INSERT or a REPLACE without RETURNING. Without callback it returns a promise. pool.query() takes the same arguments and runs the query on a free connection of the pool.
client.query('SELECT id, name FROM tbl_product WHERE price>:price', { price: 100 }, function(err, response) {
console.log(response.command, response.rowCount, response.rows);
});
method
client.close([callback])
Returns the connection to its pool or closes it.
client.close([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Called when it is done. |
A connection of a pool goes back to the pool (alias client.release()). Other connections are closed after their pending queries, like client.end([callback]). A later query fails with Connection is closed.
client.close();
method
pool.end([callback])
Closes all connections of the pool.
pool.end([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Called when all connections are closed. |
Idle connections close at once, busy ones when they are released. Waiting and later requests fail with Pool is closed.
pool.end(() => console.log('closed'));
property
SQLite.types
The parsers of values by the declared type of the column.
SQLite.typesReturns Object
An object { TYPE: function(value) } with the names of the types in upper case: BOOLEAN, BOOL, DATE, DATETIME, TIMESTAMP, TIMESTAMPTZ, JSON and JSONB. A type without a parser is returned as it is stored. null is not passed to the parser. Change the parsers before the first query.
const SQLite = require('total5/client-sqlite');
SQLite.types.DATE = value => value;
// CREATE TABLE tbl_item (id TEXT, tags CSV)
SQLite.types.CSV = value => value.split(',');