Spanish Total.js
English
Documentation For AI agents
Contents

SQLite

Keep the data in one SQLite file with DATA.init() and run the QueryBuilder, raw SQL and transactions on it, without a database server.

.md GitHub
On this page

Total.js 5 has its own SQLite client, written for the framework and without npm packages, and an adapter that runs the QueryBuilder on SQLite. A whole database is one file, so there is no server to install. You register a connection once with DATA.init(). After that DATA, DB() and every method of the QueryBuilder work as described in QueryBuilder, and the adapter writes the SQL.

DATA.init('default', 'sqlite://databases/eshop.db?wal=1');

DATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);
// SELECT * FROM tbl_product WHERE "price">100 ORDER BY "name" ASC LIMIT 20

The client uses the module node:sqlite of Node.js and needs Node.js 22.16 or newer. Some versions of Node.js print an ExperimentalWarning when the module is loaded for the first time.

The full list of options and functions is in the reference of SQLite.

Connecting

Keep the connection string in the config file:

database : sqlite://databases/eshop.db?wal=1

Register the connection when the application starts, for example in definitions/db.js:

DATA.init('default', CONF.database);

The part after sqlite:// is the database file:

Connection stringDatabase
sqlite://databases/eshop.dbA file relative to the root of the application
sqlite:///data/eshop.dbAn absolute path (three slashes)
sqlite://A database in the memory, it is lost when the application ends

The file is created when it does not exist, but its folder must exist (the framework creates databases). Encode special characters of the path, such as ? and spaces, with encodeURIComponent().

The first argument of DATA.init() is the connection name. The connection default serves the tables without a prefix. A connection with another name serves the tables with that prefix, and it can use another engine:

DATA.init('default', CONF.database);                      // postgresql://...
DATA.init('logs', 'sqlite://databases/logs.db?wal=1');

DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);

DATA.init('logs', null) removes the connection and closes the database.

Options

Options go in the query string, joined with &:

OptionWhat it does
wal=1Switches the database to the WAL journal mode, so reading does not wait for writing. Use it for web applications.
pooling=3The maximum number of connections. The default is 1.
timeout=5000How long in milliseconds a query waits for a locked database. The default is 5000.
readonly=1Opens the file for reading only. The file must exist.
foreignkeys=0Turns off the checks of foreign keys. They are on by default.
schema=archiveA name put before the tables: DATA.find('tbl_product') reads archive.tbl_product. SQLite names the main database main and the attached ones by their ATTACH name.

The functions of node:sqlite are synchronous: a query blocks the process until it ends. Queries over an index take microseconds, but a long report blocks every request, and more connections do not make it faster. Use pooling for transactions, not for speed. A database in the memory always has one connection.

A locked database (another process is writing) does not block the process: the client tries the query again every 20 milliseconds and fails with database is locked after timeout.

Creating tables

SQLite does not check types strictly, but the client uses the declared type of a column to convert its values. Declare the columns like this:

DATA.query(`CREATE TABLE IF NOT EXISTS tbl_product (
    id TEXT PRIMARY KEY,
    name TEXT,
    price REAL,
    stock INTEGER DEFAULT 0,
    tags JSON,
    data JSON,
    isremoved BOOLEAN DEFAULT 0,
    dtcreated DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
    dtupdated DATETIME
);
CREATE TABLE IF NOT EXISTS tbl_order (
    id TEXT PRIMARY KEY,
    productid TEXT REFERENCES tbl_product(id),
    count INTEGER
);
CREATE TABLE IF NOT EXISTS tbl_visitor (
    id TEXT PRIMARY KEY,
    count INTEGER,
    dtupdated DATETIME
)`).callback(ERROR('database'));
Declared typeJavaScript
BOOLEAN, BOOLBoolean (stored as 1 and 0)
DATE, DATETIME, TIMESTAMP, TIMESTAMPTZDate
JSON, JSONBThe parsed value; texts in the ISO date format become Date objects
BLOBBuffer
INTEGER, REAL, NUMERICNumber; an integer that does not fit into a JavaScript number is a String
other typesString, Number or null, as it is stored

The size in parentheses is ignored, so NUMERIC(10,2) works. An expression such as COUNT(1) or UPPER(name) has no declared type, so its value comes as it is stored.

The rows are objects without a prototype: use Object.keys(row) or 'name' in row instead of row.hasOwnProperty('name').

Arrays, objects and dates

An array or an object in the payload is stored as JSON. Declare its column as JSON to get it back as an array or an object:

DATA.insert('tbl_product', { id: 'p1', name: 'Phone', price: 120, tags: ['sale', 'new'], data: { color: 'red', weight: 180 } }).returning('id,tags').callback(console.log);
// null { id: 'p1', tags: ['sale', 'new'] }

A Date is stored as ISO 8601 text in UTC (2026-12-02T16:19:22.120Z), and dates are compared as text. The functions CURRENT_TIMESTAMP and datetime() of SQLite write another format (2026-12-02 16:19:22). The client reads both, but a comparison of the two formats gives wrong results. Use NOW in the payload, or the default value strftime('%Y-%m-%dT%H:%M:%fZ', 'now') of the table above.

The SQL of the QueryBuilder

MethodSQL
where('age', '>', 20)"age">20
where('isremoved', false)"isremoved"=0
where('dtremoved', null)"dtremoved" IS NULL (IS NOT NULL with the comparer <>)
in('id', ['a', 'b']), notin()"id" IN ('a','b'), "id" NOT IN (…)
between('age', 20, 30)("age" BETWEEN 20 AND 30)
search('name', 'pet')CAST("name" AS TEXT) LIKE '%pet%'; 'pet%' with 'beg' and '%pet' with 'end'
array('tags', ['a'])The JSON array in tags has at least one of the values
array('tags', '@>', ['a', 'b'])It has all the values
array('tags', '<@', ['a', 'b'])It has no other values
year('dtcreated', 2026)CAST(strftime('%Y',"dtcreated") AS INTEGER)=2026; month(), day(), hour() and minute() work in the same way
contains('note'), empty('note')The column has a text, or it is NULL or an empty text. An empty JSON array is the text [], so it is not empty.
permit('permissions', 'R', ['admin'], userid)permissions is a JSON array; the condition is the same as on PostgreSQL
sort('name', true), take(20), skip(40)ORDER BY "name" DESC, LIMIT 20 OFFSET 40

LIKE ignores the case of the letters A to Z only, so search('name', 'é') does not find É. Another comparer of array() gives an error, and join() adds nothing to the SQL; write joins in a raw query.

The payload of update() has the same operators as on PostgreSQL: +, -, *, /, >, <, !, = and # before the name of the column. This counter adds a row for the day and then increases it:

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);

autoqueryjson() reads the properties of a JSON column, as described in QueryBuilder. truncate() runs DELETE FROM, because SQLite has no TRUNCATE; the sequence of an AUTOINCREMENT column is not restarted.

The results have the same form as on PostgreSQL: the list is in the reference.

Raw queries

DATA.query() sends the SQL as it is. The parameters are $1, $2… or ? with an array, or :name with an object:

DATA.query('SELECT id, name FROM tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);
DATA.query('SELECT id, name FROM tbl_product WHERE price>? ORDER BY id', [100]).callback(console.log);
DATA.query('SELECT id, name FROM tbl_product WHERE price>:price ORDER BY id', { price: 100 }).callback(console.log);

Conditions added with the QueryBuilder replace the text {where}, or are added at the end of the SQL when it has no {where}:

DATA.query('SELECT id, name FROM tbl_product {where} ORDER BY id').where('isremoved', false).callback(console.log);

Without parameters the SQL can have several statements; the response has the rows of the last one.

The functions and extensions compiled into the SQLite of Node.js work in raw queries. JSON properties are read with ->>:

DATA.query("SELECT id, data->>'$.color' AS color FROM tbl_product WHERE data->>'$.weight'>$1", [100]).callback(console.log);
// null [ { id: 'p1', color: 'red' } ]

Full-text search uses an FTS5 virtual table. It is a table of its own, so write into it when the source changes:

DATA.query('CREATE VIRTUAL TABLE IF NOT EXISTS tbl_search USING fts5(id UNINDEXED, body)').callback(function() {
    DATA.insert('tbl_search', { id: 'p1', body: 'A red phone with a big screen' }).callback(function() {
        DATA.query('SELECT id FROM tbl_search WHERE tbl_search MATCH $1 ORDER BY rank', ['phone scr*']).callback(console.log);
        // null [ { id: 'p1' } ]
    });
});

Transactions

Write the whole transaction as one raw query without parameters. When a statement fails, the changes are rolled back and the callback gets the error:

DATA.query(`BEGIN;
UPDATE tbl_product SET stock=stock-1 WHERE id='p1';
INSERT INTO tbl_order (id, productid, count) VALUES('o1', 'p1', 1);
COMMIT`).callback(console.log);

Without BEGIN each statement is saved on its own, so the statements before the failed one stay saved. When the transaction needs parameters or JavaScript between the statements, use the client directly (see below).

Errors and debugging

An error of SQLite is an Error with its message, code (ERR_SQLITE_ERROR), errcode (the extended result code of SQLite) and errstr (its text):

DATA.insert('tbl_order', { id: 'o1', productid: 'none', count: 1 }).callback(function(err, response) {
    if (err)
        console.log(err.errcode, err.message);
    // 787 FOREIGN KEY constraint failed
});

Every failed query is also logged with ERROR(), or passed as a text to the function in the third argument of DATA.init(). A database that cannot be opened (unable to open database file) is an error of each query and is not logged.

debug() on a query prints the SQL and the parameters to the console:

-- SQLite --> SELECT "id","name" FROM tbl_product ORDER BY "price" DESC LIMIT 2 undefined

The client without the QueryBuilder

The client is a module of the framework: require('total5/client-sqlite'). It has the same API as the client of PostgreSQL. Use it when you need one connection for several queries, for example a transaction with parameters:

const SQLite = require('total5/client-sqlite');
const pool = SQLite.pool('sqlite://' + PATH.databases('eshop.db'), 2);

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(:id, :productid, :count)', { id: 'o2', productid: 'p1', count: 2 });
        await client.query('COMMIT');
    } catch (e) {
        await client.query('ROLLBACK');
    } finally {
        release();
    }
});

A relative path in the client is relative to the working directory of the process, so build the path with PATH.databases() or PATH.root().

Made in Europe