---
title: SQLite
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/sqlite/
updated: 2026-12-02T17:12:20.787Z
---

# SQLite

> DATA.init() with sqlite://, the connection string, the results and errors, and the SQLite client.

`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](../../reference/querybuilder/). An introduction with examples is in the guide [SQLite](../../guides/sqlite/).

## API

### DATA.init([name], [connection], [onerror])

Type: `method`

Registers a SQLite connection for the QueryBuilder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `'default'` | The connection name. |
| `connection` | `String` | no |  | The connection string: `sqlite://filename?options`. See the connection string. |
| `onerror` | `Function` | no |  | `function(message)` called for every failed query. |

The engine is chosen by the connection string: `sqlite:` registers SQLite, any other string [PostgreSQL](../../reference/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.

Example: In definitions/db.js
```js
DATA.init('default', CONF.database);
```

Example: A second connection
```js
DATA.init('logs', 'sqlite://databases/logs.db?wal=1');
DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);
```

### sqlite://filename?options

Type: `type`

The database file and its options.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `pooling` | `Number` | no | `1` | The maximum number of connections (only in `DATA.init()`). A database in the memory always has one. |
| `schema` | `String` | no |  | 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` | no | `false` | Switches the database to the WAL journal mode. |
| `readonly` | `Boolean` | no | `false` | Opens the file for reading only. A missing file gives the error `unable to open database file`. |
| `foreignkeys` | `Boolean` | no | `true` | Checks the foreign keys. |
| `timeout` | `Number` | no | `5000` | 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. |

`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://:memory:` 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.

Example: In the config file
```text
database : sqlite://databases/eshop.db?wal=1
```

Example: Options
```js
DATA.init('reports', 'sqlite://databases/eshop.db?readonly=1&timeout=1000');
```

### { '+stock': 5, '=dtupdated': 'CURRENT_TIMESTAMP' }

Type: `type`

Keys of the update() payload that change the value in the database.

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`.

Example: Stock
```js
DATA.update('tbl_product', { '+stock': 5, dtupdated: NOW }).id('p1').callback(console.log);
```

Example: A daily counter (upsert)
```js
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);
```

### callback(err, response)

Type: `type`

What each operation of the QueryBuilder returns on SQLite.

| 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`.

Example: Returning
```js
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 }
```

### err

Type: `type`

The error of a failed query.

An 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`.

Example: A duplicate key
```js
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
});
```

### require('total5/client-sqlite')

Type: `method`

The SQLite client without the QueryBuilder.

Returns: `Object` The module.

The module exports `connect()`, `pool()`, `types` and the classes `Client` and `Pool`, the same API as the [client of PostgreSQL](../../reference/postgresql/). The adapter of `DATA.init()` uses the same module, so a change in `types` applies to both.

Example: Require
```js
const SQLite = require('total5/client-sqlite');
```

### SQLite.connect(options, callback)

Type: `method`

Opens one connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `String|Object` | yes |  | The connection string or the options. |
| `callback` | `Function` | yes |  | `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 `:memory:` is a new empty database.

Example: One connection
```js
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();
});
```

### SQLite.pool(options, [max])

Type: `method`

Creates a pool of connections.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `String|Object` | yes |  | The connection string or the options of `SQLite.connect()`. |
| `max` | `Number` | no | `4` | The maximum number of connections. |

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.

Example: A pool
```js
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);
});
```

### pool.connect(callback)

Type: `method`

Borrows a connection from the pool.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `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.

Example: A transaction
```js
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();
	}
});
```

### client.query(sql, [params], [callback])

Type: `method`

Runs a query on the connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sql` | `String` | yes |  | The SQL. |
| `params` | `Array|Object` | no |  | The values of the parameters. |
| `callback` | `Function` | no |  | `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.

Example: Query
```js
client.query('SELECT id, name FROM tbl_product WHERE price>:price', { price: 100 }, function(err, response) {
	console.log(response.command, response.rowCount, response.rows);
});
```

### client.close([callback])

Type: `method`

Returns the connection to its pool or closes it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | 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`.

Example: Close
```js
client.close();
```

### pool.end([callback])

Type: `method`

Closes all connections of the pool.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | 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`.

Example: End
```js
pool.end(() => console.log('closed'));
```

### SQLite.types

Type: `property`

The parsers of values by the declared type of the column.

Returns: `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.

Example: Dates as a text
```js
const SQLite = require('total5/client-sqlite');
SQLite.types.DATE = value => value;
```

Example: A type of your own
```js
// CREATE TABLE tbl_item (id TEXT, tags CSV)
SQLite.types.CSV = value => value.split(',');
```
