DatabaseSync
new DatabaseSync(path[, options])database.aggregate(name, options)database.close()database.loadExtension(path[, entryPoint])database.enableLoadExtension(allow)database.enableDefensive(active)database.location([dbName])database.exec(sql)database.function(name[, options], fn)database.setAuthorizer(callback)database.isOpendatabase.isTransactiondatabase.limitsdatabase.open()database.serialize([dbName])database.deserialize(buffer[, options])database.prepare(sql[, options])database.createTagStore([maxSize])database.createSession([options])database.applyChangeset(changeset[, options])database[Symbol.dispose]()Session
StatementSync
statement.all([namedParameters][, ...anonymousParameters])statement.columns()statement.expandedSQLstatement.get([namedParameters][, ...anonymousParameters])statement.iterate([namedParameters][, ...anonymousParameters])statement.run([namedParameters][, ...anonymousParameters])statement.setAllowBareNamedParameters(enabled)statement.setAllowUnknownNamedParameters(enabled)statement.setReturnArrays(enabled)statement.setReadBigInts(enabled)statement.sourceSQLSQLTagStore
sqlite.backup(sourceDb, path[, options])sqlite.constants
node:module APISQLite is no longer behind --experimental-sqlite but still experimental.
Stability: 1.2 - Release candidate.
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.
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' } ]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' } ]
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.
| Storage class | JavaScript to SQLite | SQLite to JavaScript |
|---|---|---|
NULL |
<null> |
<null> |
INTEGER |
<number> or <bigint> |
<number> or <bigint> (configurable) |
REAL |
<number> |
<number> |
TEXT |
<string> |
<string> |
BLOB |
<TypedArray> or <DataView> |
<Uint8Array> |
INTEGER values are converted to number or bigint in JavaScript,
such as the readBigInts option for statements and the useBigIntArguments
option for user-defined functions. If Node.js reads an INTEGER value from
SQLite that is outside the JavaScript safe integer range, and the option to
read BigInts is not enabled, then an ERR_OUT_OF_RANGE error will be thrown.
DatabaseSync#timeout option.The path argument now supports Buffer and URL objects.
new DatabaseSync(path[, options])#defensive by default.defensive option.Add new SQLite database options.
path <string> | <Buffer> | <URL> 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 <Object> Configuration options for the database connection. The
following options are supported:
open <boolean> If true, the database is opened by the constructor. When
this value is false, the database must be opened via the open() method.
Default: true.readOnly <boolean> If true, the database is opened in read-only mode.
If the database does not exist, opening it will fail. Default: false.enableForeignKeyConstraints <boolean> If true, 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 using
PRAGMA foreign_keys. Default: true.enableDoubleQuotedStringLiterals <boolean> If true, SQLite will accept
double-quoted string literals. This is not recommended but can be
enabled for compatibility with legacy database schemas.
Default: false.allowExtension <boolean> If true, the loadExtension SQL function
and the loadExtension() method are enabled.
You can call enableLoadExtension(false) later to disable this feature.
Default: false.timeout <number> The busy timeout in milliseconds. This is the maximum amount of
time that SQLite will wait for a database lock to be released before
returning an error. Default: 0.readBigInts <boolean> If true, integer fields are read as JavaScript BigInt values. If false,
integer fields are read as JavaScript numbers. Default: false.returnArrays <boolean> If true, query results are returned as arrays instead of objects.
Default: false.allowBareNamedParameters <boolean> If true, allows binding named parameters without the prefix
character (e.g., foo instead of :foo). Default: true.allowUnknownNamedParameters <boolean> If true, unknown named parameters are ignored when binding.
If false, an exception is thrown for unknown named parameters. Default: false.defensive <boolean> If true, enables the defensive flag. When the defensive flag is enabled,
language features that allow ordinary SQL to deliberately corrupt the database file are disabled.
The defensive flag can also be set using enableDefensive().
Default: true.limits <Object> Configuration for various SQLite limits. These limits
can be used to prevent excessive resource consumption when handling
potentially malicious input. See Run-Time Limits and Limit Constants
in the SQLite documentation for details. Default values are determined by
SQLite's compile-time defaults and may vary depending on how SQLite was
built. The following properties are supported:
length <number> Maximum length of a string or BLOB.sqlLength <number> Maximum length of an SQL statement.column <number> Maximum number of columns.exprDepth <number> Maximum depth of an expression tree.compoundSelect <number> Maximum number of terms in a compound SELECT.vdbeOp <number> Maximum number of VDBE instructions.functionArg <number> Maximum number of function arguments.attach <number> Maximum number of attached databases.likePatternLength <number> Maximum length of a LIKE pattern.variableNumber <number> Maximum number of SQL variables.triggerDepth <number> Maximum trigger recursion depth.DatabaseSync instance.
database.aggregate(name, options)#Registers a new aggregate function with the SQLite database. This method is a wrapper around
sqlite3_create_window_function().
name <string> The name of the SQLite function to create.options <Object> Function configuration settings.
deterministic <boolean> If true, the SQLITE_DETERMINISTIC flag is
set on the created function. Default: false.directOnly <boolean> If true, the SQLITE_DIRECTONLY flag is set on
the created function. Default: false.useBigIntArguments <boolean> If true, integer arguments to options.step and options.inverse
are converted to BigInts. If false, integer arguments are passed as
JavaScript numbers. Default: false.varargs <boolean> If true, options.step and options.inverse may be invoked with any number of
arguments (between zero and SQLITE_MAX_FUNCTION_ARG). If false,
inverse and step must be invoked with exactly length arguments.
Default: false.start <number> | <string> | <null> | <Array> | <Object> | <Function> The identity
value for the aggregation function. This value is used when the aggregation
function is initialized. When a <Function> is passed the identity will be its return value.step <Function> The function to call for each row in the aggregation. The
function receives the current state and the row value. The return value of
this function should be the new state.result <Function> The function to call to get the result of the
aggregation. The function receives the final state and should return the
result of the aggregation.inverse <Function> When this function is provided, the aggregate method will work as a window function.
The function receives the current state and the dropped row value. The return value of this function should be the
new state.result function will be called multiple times.const { DatabaseSync } = require('node:sqlite'); const db = new DatabaseSync(':memory:'); db.exec(` CREATE TABLE t3(x, y); INSERT INTO t3 VALUES ('a', 4), ('b', 5), ('c', 3), ('d', 8), ('e', 1); `); db.aggregate('sumint', { start: 0, step: (acc, value) => acc + value, }); db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }import { DatabaseSync } from 'node:sqlite'; const db = new DatabaseSync(':memory:'); db.exec(` CREATE TABLE t3(x, y); INSERT INTO t3 VALUES ('a', 4), ('b', 5), ('c', 3), ('d', 8), ('e', 1); `); db.aggregate('sumint', { start: 0, step: (acc, value) => acc + value, }); db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }
database.close()#sqlite3_close_v2().
database.loadExtension(path[, entryPoint])#path <string> The path to the shared library to load.entryPoint <string> The name of the extension's entry-point function. When
omitted, SQLite derives the entry point from the shared library's filename;
pass this argument explicitly when the derived name does not match.sqlite3_load_extension(). It is required to enable the
allowExtension option when constructing the DatabaseSync instance.import { DatabaseSync } from 'node:sqlite'; const database = new DatabaseSync(':memory:', { allowExtension: true }); // Load using the entry point derived from the filename. database.loadExtension('./decimal.dylib'); // Override the entry point when the derived name does not match. database.loadExtension('./base64.dylib', 'sqlite3_base64_init');const { DatabaseSync } = require('node:sqlite'); const database = new DatabaseSync(':memory:', { allowExtension: true }); // Load using the entry point derived from the filename. database.loadExtension('./decimal.dylib'); // Override the entry point when the derived name does not match. database.loadExtension('./base64.dylib', 'sqlite3_base64_init');
database.enableLoadExtension(allow)#allow <boolean> Whether to allow loading extensions.loadExtension SQL function, and the loadExtension()
method. When allowExtension is false when constructing, you cannot enable
loading extensions for security reasons.
database.enableDefensive(active)#active <boolean> Whether to set the defensive flag.SQLITE_DBCONFIG_DEFENSIVE in the SQLite documentation for details.
database.location([dbName])#dbName <string> Name of the database. This can be 'main' (the default primary database) or any other
database that has been added with ATTACH DATABASE Default: 'main'.<string> | <null> The location of the database file. When using an in-memory database,
this method returns null.sqlite3_db_filename()
database.exec(sql)#sql <string> A SQL string to execute.sqlite3_exec().
database.function(name[, options], fn)#name <string> The name of the SQLite function to create.options <Object> Optional configuration settings for the function. The
following properties are supported:
deterministic <boolean> If true, the SQLITE_DETERMINISTIC flag is
set on the created function. Default: false.directOnly <boolean> If true, the SQLITE_DIRECTONLY flag is set on
the created function. Default: false.useBigIntArguments <boolean> If true, integer arguments to function
are converted to BigInts. If false, integer arguments are passed as
JavaScript numbers. Default: false.varargs <boolean> If true, function may be invoked with any number of
arguments (between zero and SQLITE_MAX_FUNCTION_ARG). If false,
function must be invoked with exactly function.length arguments.
Default: false.fn <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 to
NULL if the return value is undefined.sqlite3_create_function_v2().
database.setAuthorizer(callback)#callback <Function> | <null> The authorizer function to set, or null to
clear the current authorizer.Sets an authorizer callback that SQLite will invoke whenever it attempts to
access data or modify the database schema through prepared statements.
This can be used to implement security policies, audit access, or restrict certain operations.
This method is a wrapper around sqlite3_set_authorizer().
When invoked, the callback receives five arguments:
actionCode <number> The type of operation being performed (e.g., SQLITE_INSERT, SQLITE_UPDATE, SQLITE_SELECT).arg1 <string> | <null> The first argument (context-dependent, often a table name).arg2 <string> | <null> The second argument (context-dependent, often a column name).dbName <string> | <null> The name of the database.triggerOrView <string> | <null> The name of the trigger or view causing the access.SQLITE_OK - Allow the operation.SQLITE_DENY - Deny the operation (causes an error).SQLITE_IGNORE - Ignore the operation (silently skip).const { DatabaseSync, constants } = require('node:sqlite'); const db = new DatabaseSync(':memory:'); // Set up an authorizer that denies all table creation db.setAuthorizer((actionCode) => { if (actionCode === constants.SQLITE_CREATE_TABLE) { return constants.SQLITE_DENY; } return constants.SQLITE_OK; }); // This will work db.prepare('SELECT 1').get(); // This will throw an error due to authorization denial try { db.exec('CREATE TABLE blocked (id INTEGER)'); } catch (err) { console.log('Operation blocked:', err.message); }import { DatabaseSync, constants } from 'node:sqlite'; const db = new DatabaseSync(':memory:'); // Set up an authorizer that denies all table creation db.setAuthorizer((actionCode) => { if (actionCode === constants.SQLITE_CREATE_TABLE) { return constants.SQLITE_DENY; } return constants.SQLITE_OK; }); // This will work db.prepare('SELECT 1').get(); // This will throw an error due to authorization denial try { db.exec('CREATE TABLE blocked (id INTEGER)'); } catch (err) { console.log('Operation blocked:', err.message); }
database.isOpen#<boolean> Whether the database is currently open or not.database.isTransaction#<boolean> Whether the database is currently within a transaction. This method
is a wrapper around sqlite3_get_autocommit().database.limits#<Object>An object for getting and setting SQLite database limits at runtime. Each property corresponds to an SQLite limit and can be read or written.
const db = new DatabaseSync(':memory:');
// Read current limit
console.log(db.limits.length);
// Set a new limit
db.limits.sqlLength = 100000;
// Reset a limit to its compile-time maximum
db.limits.sqlLength = Infinity;
Available properties: length, sqlLength, column, exprDepth,
compoundSelect, vdbeOp, functionArg, attach, likePatternLength,
variableNumber, triggerDepth.
Infinity resets the limit to its compile-time maximum value.
database.open()#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.serialize([dbName])#dbName <string> Name of the database to serialize. This can be 'main'
(the default primary database) or any other database that has been added with
ATTACH DATABASE. Default: 'main'.<Uint8Array> A binary representation of the database.Uint8Array. This is useful for saving, cloning, or transferring an in-memory
database. This method is a wrapper around sqlite3_serialize().import { DatabaseSync } from 'node:sqlite'; const db = new DatabaseSync(':memory:'); db.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); db.exec("INSERT INTO t VALUES (1, 'hello')"); const buffer = db.serialize(); console.log(buffer.length); // Prints the byte length of the databaseconst { DatabaseSync } = require('node:sqlite'); const db = new DatabaseSync(':memory:'); db.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); db.exec("INSERT INTO t VALUES (1, 'hello')"); const buffer = db.serialize(); console.log(buffer.length); // Prints the byte length of the database
database.deserialize(buffer[, options])#buffer <Uint8Array> A binary representation of a database, such as the
output of database.serialize().options <Object> Optional configuration for the deserialization.
dbName <string> Name of the database to deserialize into. Default: 'main'.sqlite3_deserialize().import { DatabaseSync } from 'node:sqlite'; const original = new DatabaseSync(':memory:'); original.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); original.exec("INSERT INTO t VALUES (1, 'hello')"); const buffer = original.serialize(); original.close(); const clone = new DatabaseSync(':memory:'); clone.deserialize(buffer); console.log(clone.prepare('SELECT value FROM t').get()); // Prints: { value: 'hello' }const { DatabaseSync } = require('node:sqlite'); const original = new DatabaseSync(':memory:'); original.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); original.exec("INSERT INTO t VALUES (1, 'hello')"); const buffer = original.serialize(); original.close(); const clone = new DatabaseSync(':memory:'); clone.deserialize(buffer); console.log(clone.prepare('SELECT value FROM t').get()); // Prints: { value: 'hello' }
database.prepare(sql[, options])#sql <string> A SQL string to compile to a prepared statement.options <Object> Optional configuration for the prepared statement.
readBigInts <boolean> If true, integer fields are read as BigInts.
Default: inherited from database options or false.returnArrays <boolean> If true, results are returned as arrays.
Default: inherited from database options or false.allowBareNamedParameters <boolean> If true, allows binding named
parameters without the prefix character. Default: inherited from
database options or true.allowUnknownNamedParameters <boolean> If true, unknown named parameters
are ignored. Default: inherited from database options or false.<StatementSync> The prepared statement.sqlite3_prepare_v2().
database.createTagStore([maxSize])#maxSize <integer> The maximum number of prepared statements to cache. Default: 1000.Creates a new SQLTagStore, which is a Least Recently Used (LRU) cache
for storing prepared statements. This allows for the efficient reuse of
prepared statements by tagging them with a unique identifier.
When a tagged SQL literal is executed, the SQLTagStore checks if a prepared
statement for the corresponding SQL query string already exists in the cache.
If it does, the cached statement is used. If not, a new prepared statement is
created, executed, and then stored in the cache for future use. This mechanism
helps to avoid the overhead of repeatedly parsing and preparing the same SQL
statements.
Tagged statements bind the placeholder values from the template literal as parameters to the underlying prepared statement. For example:
sqlTagStore.get`SELECT ${value}`;
is equivalent to:
db.prepare('SELECT ?').get(value);
However, in the first example, the tag store will cache the underlying prepared statement for future use.
Note: The
${value}syntax in tagged statements binds a parameter to the prepared statement. This differs from its behavior in untagged template literals, where it performs string interpolation.// This a safe example of binding a parameter to a tagged statement. sqlTagStore.run`INSERT INTO t1 (id) VALUES (${id})`; // This is an *unsafe* example of an untagged template string. // `id` is interpolated into the query text as a string. // This can lead to SQL injection and data corruption. db.run(`INSERT INTO t1 (id) VALUES (${id})`);
The tag store will match a statement from the cache if the query strings (including the positions of any bound placeholders) are identical.
// The following statements will match in the cache:
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${12345} AND active = 1`;
// The following statements will not match, as the query strings
// and bound placeholders differ:
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;
sqlTagStore.get`SELECT * FROM t1 WHERE id = 12345 AND active = 1`;
// The following statements will not match, as matches are case-sensitive:
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;
sqlTagStore.get`select * from t1 where id = ${id} and active = 1`;
The only way of binding parameters in tagged statements is with the ${value}
syntax. Do not add parameter binding placeholders (? etc.) to the SQL query
string itself.import { DatabaseSync } from 'node:sqlite'; const db = new DatabaseSync(':memory:'); const sql = db.createTagStore(); db.exec('CREATE TABLE users (id INT, name TEXT)'); // Using the 'run' method to insert data. // The tagged literal is used to identify the prepared statement. sql.run`INSERT INTO users VALUES (1, 'Alice')`; sql.run`INSERT INTO users VALUES (2, 'Bob')`; // Using the 'get' method to retrieve a single row. const name = 'Alice'; const user = sql.get`SELECT * FROM users WHERE name = ${name}`; console.log(user); // { id: 1, name: 'Alice' } // Using the 'all' method to retrieve all rows. const allUsers = sql.all`SELECT * FROM users ORDER BY id`; console.log(allUsers); // [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' } // ]const { DatabaseSync } = require('node:sqlite'); const db = new DatabaseSync(':memory:'); const sql = db.createTagStore(); db.exec('CREATE TABLE users (id INT, name TEXT)'); // Using the 'run' method to insert data. // The tagged literal is used to identify the prepared statement. sql.run`INSERT INTO users VALUES (1, 'Alice')`; sql.run`INSERT INTO users VALUES (2, 'Bob')`; // Using the 'get' method to retrieve a single row. const name = 'Alice'; const user = sql.get`SELECT * FROM users WHERE name = ${name}`; console.log(user); // { id: 1, name: 'Alice' } // Using the 'all' method to retrieve all rows. const allUsers = sql.all`SELECT * FROM users ORDER BY id`; console.log(allUsers); // [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' } // ]
database.createSession([options])#options <Object> The configuration options for the session.
table <string> A specific table to track changes for. By default, changes to all tables are tracked.db <string> Name of the database to track. This is useful when multiple databases have been added using ATTACH DATABASE. Default: 'main'.<Session> A session handle.sqlite3session_create() and sqlite3session_attach().
database.applyChangeset(changeset[, options])#changeset <Uint8Array> A binary changeset or patchset.options <Object> The configuration options for how the changes will be applied.
filter <Function> Skip changes that, when targeted table name is supplied to this function, return a truthy value.
By default, all changes are attempted.
onConflict <Function> A function that determines how to handle conflicts. The function receives one argument,
which can be one of the following values:
SQLITE_CHANGESET_DATA: A DELETE or UPDATE change does not contain the expected "before" values.SQLITE_CHANGESET_NOTFOUND: A row matching the primary key of the DELETE or UPDATE change does not exist.SQLITE_CHANGESET_CONFLICT: An INSERT 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 a UNIQUE, CHECK, or NOT 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 with
SQLITE_CHANGESET_DATA or SQLITE_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 returns SQLITE_CHANGESET_ABORT.
<boolean> Whether the changeset was applied successfully without being aborted.sqlite3changeset_apply().import { DatabaseSync } from 'node:sqlite'; 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.const { DatabaseSync } = require('node:sqlite'); 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]()#No longer experimental.
Closes the database connection. If the database connection is already closed then this is a no-op.Session#session.changeset()#<Uint8Array> Binary changeset that can be applied to other databases.sqlite3session_changeset().
session.patchset()#<Uint8Array> Binary patchset that can be applied to other databases.sqlite3session_patchset().
session.close()#sqlite3session_delete().
session[Symbol.dispose]()#StatementSync#This class represents a single prepared statement. This class cannot be
instantiated via its constructor. Instead, instances are created via the
database.prepare() method. All APIs exposed by this class execute
synchronously.
statement.all([namedParameters][, ...anonymousParameters])#Add support for DataView and typed array objects for anonymousParameters.
namedParameters <Object> An optional object used to bind named parameters.
The keys of this object are used to configure the mapping....anonymousParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> Zero or
more values to bind to anonymous parameters.<Array> 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.namedParameters and anonymousParameters.
statement.columns()#Returns: <Array> An array of objects. Each object corresponds to a column
in the prepared statement, and contains the following properties:
column <string> | <null> The unaliased name of the column in the origin
table, or null if the column is the result of an expression or subquery.
This property is the result of sqlite3_column_origin_name().database <string> | <null> The unaliased name of the origin database, or null if the column is the result of an expression or subquery. This
property is the result of sqlite3_column_database_name().name <string> The name assigned to the column in the result set of a SELECT statement. This property is the result of
sqlite3_column_name().table <string> | <null> The unaliased name of the origin table, or null if
the column is the result of an expression or subquery. This property is the
result of sqlite3_column_table_name().type <string> | <null> The declared data type of the column, or null if the
column is the result of an expression or subquery. This property is the
result of sqlite3_column_decltype().statement.expandedSQL#<string> The source SQL expanded to include parameter values.sqlite3_expanded_sql().
statement.get([namedParameters][, ...anonymousParameters])#Add support for DataView and typed array objects for anonymousParameters.
namedParameters <Object> An optional object used to bind named parameters.
The keys of this object are used to configure the mapping....anonymousParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> Zero or
more values to bind to anonymous parameters.<Object> | <undefined> 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.undefined. The prepared statement parameters are bound using the
values in namedParameters and anonymousParameters.
statement.iterate([namedParameters][, ...anonymousParameters])#Add support for DataView and typed array objects for anonymousParameters.
namedParameters <Object> An optional object used to bind named parameters.
The keys of this object are used to configure the mapping....anonymousParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> Zero or
more values to bind to anonymous parameters.<Iterator> 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.namedParameters and anonymousParameters.
statement.run([namedParameters][, ...anonymousParameters])#Add support for DataView and typed array objects for anonymousParameters.
namedParameters <Object> An optional object used to bind named parameters.
The keys of this object are used to configure the mapping....anonymousParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> Zero or
more values to bind to anonymous parameters.<Object>
changes <number> | <bigint> The number of rows modified, inserted, or deleted
by the most recently completed INSERT, UPDATE, or DELETE statement.
This field is either a number or a BigInt depending on the prepared
statement's configuration. This property is the result of
sqlite3_changes64().lastInsertRowid <number> | <bigint> The most recently inserted rowid. This
field is either a number or a BigInt depending on the prepared statement's
configuration. This property is the result of
sqlite3_last_insert_rowid().namedParameters and anonymousParameters.
statement.setAllowBareNamedParameters(enabled)#enabled <boolean> Enables or disables support for binding named parameters
without the prefix character.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.
$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)#enabled <boolean> Enables or disables support for unknown named parameters.statement.setReturnArrays(enabled)#enabled <boolean> Enables or disables the return of query results as arrays.all(), get(), and iterate() methods will be returned as arrays instead
of objects.
statement.setReadBigInts(enabled)#enabled <boolean> Enables or disables the use of BigInts when reading
INTEGER fields from the database.INTEGERs are mapped to JavaScript
numbers by default. However, SQLite INTEGERs 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 BigInts. This method has no
impact on database write operations where numbers and BigInts are both
supported at all times.
statement.sourceSQL#<string> The source SQL used to create this prepared statement.sqlite3_sql().
SQLTagStore#This class represents a single LRU (Least Recently Used) cache for storing prepared statements.
Instances of this class are created via the database.createTagStore()
method, not by using a constructor. The store caches prepared statements based
on the provided SQL query string. When the same query is seen again, the store
retrieves the cached statement and safely applies the new values through
parameter binding, thereby preventing attacks like SQL injection.
database.createTagStore(100)). All APIs exposed by this
class execute synchronously.
sqlTagStore.all(stringElements[, ...boundParameters])#stringElements <string[]> Template literal elements containing the SQL
query....boundParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView>
Parameter values to be bound to placeholders in the template string.<Array> An array of objects representing the rows returned by the query.Executes the given SQL query and returns all resulting rows as an array of objects.
This function is intended to be used as a template literal tag, not to be called directly.sqlTagStore.get(stringElements[, ...boundParameters])#stringElements <string[]> Template literal elements containing the SQL
query....boundParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView>
Parameter values to be bound to placeholders in the template string.<Object> | <undefined> An object representing the first row returned by
the query, or undefined if no rows are returned.Executes the given SQL query and returns the first resulting row as an object.
This function is intended to be used as a template literal tag, not to be called directly.sqlTagStore.iterate(stringElements[, ...boundParameters])#stringElements <string[]> Template literal elements containing the SQL
query....boundParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView>
Parameter values to be bound to placeholders in the template string.<Iterator> An iterator that yields objects representing the rows returned by the query.Executes the given SQL query and returns an iterator over the resulting rows.
This function is intended to be used as a template literal tag, not to be called directly.sqlTagStore.run(stringElements[, ...boundParameters])#stringElements <string[]> Template literal elements containing the SQL
query....boundParameters <null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView>
Parameter values to be bound to placeholders in the template string.<Object> An object containing information about the execution, including changes and lastInsertRowid.Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE).
This function is intended to be used as a template literal tag, not to be called directly.sqlTagStore.size#Changed from a method to a getter.
<integer>sqlTagStore.capacity#<integer>sqlTagStore.db#<DatabaseSync>DatabaseSync object associated with this SQLTagStore.
sqlTagStore.clear()#sqlite.backup(sourceDb, path[, options])#The path argument now supports Buffer and URL objects.
sourceDb <DatabaseSync> The database to backup. The source database must be open.path <string> | <Buffer> | <URL> The path where the backup will be created. If the file already exists,
the contents will be overwritten.options <Object> Optional configuration for the backup. The
following properties are supported:
source <string> 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 <string> 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> Number of pages to be transmitted in each batch of the backup. Default: 100.progress <Function> An optional callback function that will be called after each backup step. The argument passed
to this callback is an <Object> with remainingPages and totalPages properties, describing the current progress
of the backup operation.<Promise> A promise that fulfills with the total number of backed-up pages upon completion, or 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.
<DatabaseSync> - 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#<Object>sqlite.constants object.
One of the following constants is available as an argument to the onConflict
conflict resolution handler passed to database.applyChangeset(). See also
Constants 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. |
onConflict conflict
resolution handler passed to database.applyChangeset(). See also
Constants 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. |
database.setAuthorizer() method.
database.setAuthorizer().| Constant | Description |
|---|---|
SQLITE_OK |
Allow the operation to proceed normally. |
SQLITE_DENY |
Deny the operation and cause an error to be returned. |
SQLITE_IGNORE |
Ignore the operation and continue as if it had never been requested. |
The following constants are passed as the first argument to the authorizer callback function to indicate what type of operation is being authorized.
| Constant | Description |
|---|---|
SQLITE_CREATE_INDEX |
Create an index |
SQLITE_CREATE_TABLE |
Create a table |
SQLITE_CREATE_TEMP_INDEX |
Create a temporary index |
SQLITE_CREATE_TEMP_TABLE |
Create a temporary table |
SQLITE_CREATE_TEMP_TRIGGER |
Create a temporary trigger |
SQLITE_CREATE_TEMP_VIEW |
Create a temporary view |
SQLITE_CREATE_TRIGGER |
Create a trigger |
SQLITE_CREATE_VIEW |
Create a view |
SQLITE_DELETE |
Delete from a table |
SQLITE_DROP_INDEX |
Drop an index |
SQLITE_DROP_TABLE |
Drop a table |
SQLITE_DROP_TEMP_INDEX |
Drop a temporary index |
SQLITE_DROP_TEMP_TABLE |
Drop a temporary table |
SQLITE_DROP_TEMP_TRIGGER |
Drop a temporary trigger |
SQLITE_DROP_TEMP_VIEW |
Drop a temporary view |
SQLITE_DROP_TRIGGER |
Drop a trigger |
SQLITE_DROP_VIEW |
Drop a view |
SQLITE_INSERT |
Insert into a table |
SQLITE_PRAGMA |
Execute a PRAGMA statement |
SQLITE_READ |
Read from a table |
SQLITE_SELECT |
Execute a SELECT statement |
SQLITE_TRANSACTION |
Begin, commit, or rollback a transaction |
SQLITE_UPDATE |
Update a table |
SQLITE_ATTACH |
Attach a database |
SQLITE_DETACH |
Detach a database |
SQLITE_ALTER_TABLE |
Alter a table |
SQLITE_REINDEX |
Reindex |
SQLITE_ANALYZE |
Analyze the database |
SQLITE_CREATE_VTABLE |
Create a virtual table |
SQLITE_DROP_VTABLE |
Drop a virtual table |
SQLITE_FUNCTION |
Use a function |
SQLITE_SAVEPOINT |
Create, release, or rollback a savepoint |
SQLITE_COPY |
Copy data (legacy) |
SQLITE_RECURSIVE |
Recursive query |