SQLite | Node.js v23.11.0 Documentation (original) (raw)
Added in: v22.5.0
Source Code: lib/sqlite.js
The node:sqlite
module facilitates working with SQLite databases. To access it:
import sqlite from 'node:sqlite';
const sqlite = require('node:sqlite');
This module is only available under the node:
scheme.
The following example shows the basic usage of the node:sqlite
module to open an in-memory database, write data to the database, and then read the data back.
`` import { DatabaseSync } from 'node:sqlite'; const database = new DatabaseSync(':memory:');
// Execute SQL statements from strings.
database.exec( CREATE TABLE data( key INTEGER PRIMARY KEY, value TEXT ) STRICT
);
// Create a prepared statement to insert data into the database.
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
// Execute the prepared statement with bound values.
insert.run(1, 'hello');
insert.run(2, 'world');
// Create a prepared statement to read data from the database.
const query = database.prepare('SELECT * FROM data ORDER BY key');
// Execute the prepared statement and log the result set.
console.log(query.all());
// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]
'use strict';
const { DatabaseSync } = require('node:sqlite');
const database = new DatabaseSync(':memory:');
// Execute SQL statements from strings.
database.exec( CREATE TABLE data( key INTEGER PRIMARY KEY, value TEXT ) STRICT
);
// Create a prepared statement to insert data into the database.
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
// Execute the prepared statement with bound values.
insert.run(1, 'hello');
insert.run(2, 'world');
// Create a prepared statement to read data from the database.
const query = database.prepare('SELECT * FROM data ORDER BY key');
// Execute the prepared statement and log the result set.
console.log(query.all());
// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] ``
Class: DatabaseSync
#
This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.
new DatabaseSync(path[, options])
#
Added in: v22.5.0
path
| | The path of the database. A SQLite database can be stored in a file or completely in memory. To use a file-backed database, the path should be a file path. To use an in-memory database, the path should be the special name':memory:'
.options
Configuration options for the database connection. The following options are supported:open
Iftrue
, the database is opened by the constructor. When this value isfalse
, the database must be opened via theopen()
method.Default:true
.readOnly
Iftrue
, the database is opened in read-only mode. If the database does not exist, opening it will fail. Default:false
.enableForeignKeyConstraints
Iftrue
, foreign key constraints are enabled. This is recommended but can be disabled for compatibility with legacy database schemas. The enforcement of foreign key constraints can be enabled and disabled after opening the database usingPRAGMA foreign_keys. Default:true
.enableDoubleQuotedStringLiterals
Iftrue
, SQLite will acceptdouble-quoted string literals. This is not recommended but can be enabled for compatibility with legacy database schemas.Default:false
.allowExtension
Iftrue
, theloadExtension
SQL function and theloadExtension()
method are enabled. You can callenableLoadExtension(false)
later to disable this feature.Default:false
.
Constructs a new DatabaseSync
instance.
database.close()
#
Added in: v22.5.0
Closes the database connection. An exception is thrown if the database is not open. This method is a wrapper around sqlite3_close_v2().
database.loadExtension(path)
#
Added in: v23.5.0
Loads a shared library into the database connection. This method is a wrapper around sqlite3_load_extension(). It is required to enable theallowExtension
option when constructing the DatabaseSync
instance.
database.enableLoadExtension(allow)
#
Added in: v23.5.0
Enables or disables the loadExtension
SQL function, and the loadExtension()
method. When allowExtension
is false
when constructing, you cannot enable loading extensions for security reasons.
database.exec(sql)
#
Added in: v22.5.0
This method allows one or more SQL statements to be executed without returning any results. This method is useful when executing SQL statements read from a file. This method is a wrapper around sqlite3_exec().
database.function(name[, options], function)
#
Added in: v23.5.0
name
The name of the SQLite function to create.options
Optional configuration settings for the function. The following properties are supported:deterministic
Iftrue
, the SQLITE_DETERMINISTIC flag is set on the created function. Default:false
.directOnly
Iftrue
, the SQLITE_DIRECTONLY flag is set on the created function. Default:false
.useBigIntArguments
Iftrue
, integer arguments tofunction
are converted toBigInt
s. Iffalse
, integer arguments are passed as JavaScript numbers. Default:false
.varargs
Iftrue
,function
may be invoked with any number of arguments (between zero and SQLITE_MAX_FUNCTION_ARG). Iffalse
,function
must be invoked with exactlyfunction.length
arguments.Default:false
.
function
The JavaScript function to call when the SQLite function is invoked. The return value of this function should be a valid SQLite data type: see Type conversion between JavaScript and SQLite. The result defaults toNULL
if the return value isundefined
.
This method is used to create SQLite user-defined functions. This method is a wrapper around sqlite3_create_function_v2().
database.isOpen
#
Added in: v23.11.0
database.open()
#
Added in: v22.5.0
Opens the database specified in the path
argument of the DatabaseSync
constructor. This method should only be used when the database is not opened via the constructor. An exception is thrown if the database is already open.
database.createSession([options])
#
Added in: v23.3.0
options
The configuration options for the session.table
A specific table to track changes for. By default, changes to all tables are tracked.db
Name of the database to track. This is useful when multiple databases have been added using ATTACH DATABASE. Default:'main'
.
- Returns: A session handle.
Creates and attaches a session to the database. This method is a wrapper around sqlite3session_create() and sqlite3session_attach().
database.applyChangeset(changeset[, options])
#
Added in: v23.3.0
changeset
A binary changeset or patchset.options
The configuration options for how the changes will be applied.filter
Skip changes that, when targeted table name is supplied to this function, return a truthy value. By default, all changes are attempted.onConflict
A function that determines how to handle conflicts. The function receives one argument, which can be one of the following values:
*SQLITE_CHANGESET_DATA
: ADELETE
orUPDATE
change does not contain the expected "before" values.
*SQLITE_CHANGESET_NOTFOUND
: A row matching the primary key of theDELETE
orUPDATE
change does not exist.
*SQLITE_CHANGESET_CONFLICT
: AnINSERT
change results in a duplicate primary key.
*SQLITE_CHANGESET_FOREIGN_KEY
: Applying a change would result in a foreign key violation.
*SQLITE_CHANGESET_CONSTRAINT
: Applying a change results in aUNIQUE
,CHECK
, orNOT NULL
constraint violation.
The function should return one of the following values:
*SQLITE_CHANGESET_OMIT
: Omit conflicting changes.
*SQLITE_CHANGESET_REPLACE
: Replace existing values with conflicting changes (only valid withSQLITE_CHANGESET_DATA
orSQLITE_CHANGESET_CONFLICT
conflicts).
*SQLITE_CHANGESET_ABORT
: Abort on conflict and roll back the database.
When an error is thrown in the conflict handler or when any other value is returned from the handler, applying the changeset is aborted and the database is rolled back.
Default: A function that returnsSQLITE_CHANGESET_ABORT
.- Returns: Whether the changeset was applied successfully without being aborted.
An exception is thrown if the database is not open. This method is a wrapper around sqlite3changeset_apply().
`const sourceDb = new DatabaseSync(':memory:'); const targetDb = new DatabaseSync(':memory:');
sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
const session = sourceDb.createSession();
const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); insert.run(1, 'hello'); insert.run(2, 'world');
const changeset = session.changeset(); targetDb.applyChangeset(changeset); // Now that the changeset has been applied, targetDb contains the same data as sourceDb.`
database[Symbol.dispose]()
#
Added in: v23.11.0
Closes the database connection. If the database connection is already closed then this is a no-op.
Class: Session
#
Added in: v23.3.0
session.changeset()
#
Added in: v23.3.0
Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. An exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_changeset().
session.patchset()
#
Added in: v23.3.0
Similar to the method above, but generates a more compact patchset. See Changesets and Patchsetsin the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_patchset().
session.close()
.#
Closes the session. An exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_delete().
Class: StatementSync
#
Added in: v22.5.0
This class represents a single prepared statement. This class cannot be instantiated via its constructor. Instead, instances are created via thedatabase.prepare()
method. All APIs exposed by this class execute synchronously.
A prepared statement is an efficient binary representation of the SQL used to create it. Prepared statements are parameterizable, and can be invoked multiple times with different bound values. Parameters also offer protection againstSQL injection attacks. For these reasons, prepared statements are preferred over hand-crafted SQL strings when handling user input.
statement.all([namedParameters][, ...anonymousParameters])
#
namedParameters
An optional object used to bind named parameters. The keys of this object are used to configure the mapping....anonymousParameters
| | | | | | Zero or more values to bind to anonymous parameters.- Returns: An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.
This method executes a prepared statement and returns all results as an array of objects. If the prepared statement does not return any results, this method returns an empty array. The prepared statement parameters are bound using the values in namedParameters
and anonymousParameters
.
statement.columns()
#
Added in: v23.11.0
- Returns: An array of objects. Each object corresponds to a column in the prepared statement, and contains the following properties:
column
: | The unaliased name of the column in the origin table, ornull
if the column is the result of an expression or subquery. This property is the result of sqlite3_column_origin_name().database
: | The unaliased name of the origin database, ornull
if the column is the result of an expression or subquery. This property is the result of sqlite3_column_database_name().name
: The name assigned to the column in the result set of aSELECT
statement. This property is the result ofsqlite3_column_name().table
: | The unaliased name of the origin table, ornull
if the column is the result of an expression or subquery. This property is the result of sqlite3_column_table_name().type
: | The declared data type of the column, ornull
if the column is the result of an expression or subquery. This property is the result of sqlite3_column_decltype().
This method is used to retrieve information about the columns returned by the prepared statement.
statement.expandedSQL
#
Added in: v22.5.0
The source SQL text of the prepared statement with parameter placeholders replaced by the values that were used during the most recent execution of this prepared statement. This property is a wrapper aroundsqlite3_expanded_sql().
statement.get([namedParameters][, ...anonymousParameters])
#
namedParameters
An optional object used to bind named parameters. The keys of this object are used to configure the mapping....anonymousParameters
| | | | | | Zero or more values to bind to anonymous parameters.- Returns: | An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no rows were returned from the database then this method returns
undefined
.
This method executes a prepared statement and returns the first result as an object. If the prepared statement does not return any results, this method returns undefined
. The prepared statement parameters are bound using the values in namedParameters
and anonymousParameters
.
statement.iterate([namedParameters][, ...anonymousParameters])
#
namedParameters
An optional object used to bind named parameters. The keys of this object are used to configure the mapping....anonymousParameters
| | | | | | Zero or more values to bind to anonymous parameters.- Returns: An iterable iterator of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.
This method executes a prepared statement and returns an iterator of objects. If the prepared statement does not return any results, this method returns an empty iterator. The prepared statement parameters are bound using the values in namedParameters
and anonymousParameters
.
statement.run([namedParameters][, ...anonymousParameters])
#
namedParameters
An optional object used to bind named parameters. The keys of this object are used to configure the mapping....anonymousParameters
| | | | | | Zero or more values to bind to anonymous parameters.- Returns:
changes
: | The number of rows modified, inserted, or deleted by the most recently completedINSERT
,UPDATE
, orDELETE
statement. This field is either a number or aBigInt
depending on the prepared statement's configuration. This property is the result ofsqlite3_changes64().lastInsertRowid
: | The most recently inserted rowid. This field is either a number or aBigInt
depending on the prepared statement's configuration. This property is the result ofsqlite3_last_insert_rowid().
This method executes a prepared statement and returns an object summarizing the resulting changes. The prepared statement parameters are bound using the values in namedParameters
and anonymousParameters
.
statement.setAllowBareNamedParameters(enabled)
#
Added in: v22.5.0
The names of SQLite parameters begin with a prefix character. By default,node:sqlite
requires that this prefix character is present when binding parameters. However, with the exception of dollar sign character, these prefix characters also require extra quoting when used in object keys.
To improve ergonomics, this method can be used to also allow bare named parameters, which do not require the prefix character in JavaScript code. There are several caveats to be aware of when enabling bare named parameters:
- The prefix character is still required in SQL.
- The prefix character is still allowed in JavaScript. In fact, prefixed names will have slightly better binding performance.
- Using ambiguous named parameters, such as
$k
and@k
, in the same prepared statement will result in an exception as it cannot be determined how to bind a bare name.
statement.setAllowUnknownNamedParameters(enabled)
#
Added in: v23.11.0
By default, if an unknown name is encountered while binding parameters, an exception is thrown. This method allows unknown named parameters to be ignored.
statement.setReadBigInts(enabled)
#
Added in: v22.5.0
When reading from the database, SQLite INTEGER
s are mapped to JavaScript numbers by default. However, SQLite INTEGER
s can store values larger than JavaScript numbers are capable of representing. In such cases, this method can be used to read INTEGER
data using JavaScript BigInt
s. This method has no impact on database write operations where numbers and BigInt
s are both supported at all times.
statement.sourceSQL
#
Added in: v22.5.0
The source SQL text of the prepared statement. This property is a wrapper around sqlite3_sql().
Type conversion between JavaScript and SQLite#
When Node.js writes to or reads from SQLite it is necessary to convert between JavaScript data types and SQLite's data types. Because JavaScript supports more data types than SQLite, only a subset of JavaScript types are supported. Attempting to write an unsupported data type to SQLite will result in an exception.
SQLite | JavaScript |
---|---|
NULL | |
INTEGER | or |
REAL | |
TEXT | |
BLOB | or |
sqlite.backup(sourceDb, path[, options])
#
sourceDb
The database to backup. The source database must be open.path
| | The path where the backup will be created. If the file already exists, the contents will be overwritten.options
Optional configuration for the backup. The following properties are supported:source
Name of the source database. This can be'main'
(the default primary database) or any other database that have been added with ATTACH DATABASE Default:'main'
.target
Name of the target database. This can be'main'
(the default primary database) or any other database that have been added with ATTACH DATABASE Default:'main'
.rate
Number of pages to be transmitted in each batch of the backup. Default:100
.progress
Callback function that will be called with the number of pages copied and the total number of pages.
- Returns: A promise that resolves when the backup is completed and rejects if an error occurs.
This method makes a database backup. This method abstracts the sqlite3_backup_init(), sqlite3_backup_step()and sqlite3_backup_finish() functions.
The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same - object will be reflected in the backup right away. However, mutations from other connections will cause the backup process to restart.
`const { backup, DatabaseSync } = require('node:sqlite');
(async () => { const sourceDb = new DatabaseSync('source.db'); const totalPagesTransferred = await backup(sourceDb, 'backup.db', { rate: 1, // Copy one page at a time. progress: ({ totalPages, remainingPages }) => { console.log('Backup in progress', { totalPages, remainingPages }); }, });
console.log('Backup completed', totalPagesTransferred);
})();
import { backup, DatabaseSync } from 'node:sqlite';
const sourceDb = new DatabaseSync('source.db'); const totalPagesTransferred = await backup(sourceDb, 'backup.db', { rate: 1, // Copy one page at a time. progress: ({ totalPages, remainingPages }) => { console.log('Backup in progress', { totalPages, remainingPages }); }, });
console.log('Backup completed', totalPagesTransferred);`
sqlite.constants
#
Added in: v23.5.0
An object containing commonly used constants for SQLite operations.
SQLite constants#
The following constants are exported by the sqlite.constants
object.
Conflict resolution constants#
One of the following constants is available as an argument to the onConflict
conflict resolution handler passed to database.applyChangeset(). See alsoConstants Passed To The Conflict Handler in the SQLite documentation.
Constant | Description |
---|---|
SQLITE_CHANGESET_DATA | The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. |
SQLITE_CHANGESET_NOTFOUND | The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. |
SQLITE_CHANGESET_CONFLICT | This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. |
SQLITE_CHANGESET_CONSTRAINT | If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns SQLITE_CHANGESET_OMIT, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns SQLITE_CHANGESET_ABORT, the changeset is rolled back. |
SQLITE_CHANGESET_FOREIGN_KEY | If any other constraint violation occurs while applying a change (i.e. a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is invoked with this constant. |
One of the following constants must be returned from the onConflict
conflict resolution handler passed to database.applyChangeset(). See alsoConstants Returned From The Conflict Handler in the SQLite documentation.
Constant | Description |
---|---|
SQLITE_CHANGESET_OMIT | Conflicting changes are omitted. |
SQLITE_CHANGESET_REPLACE | Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. |
SQLITE_CHANGESET_ABORT | Abort when a change encounters a conflict and roll back database. |