SQLite#

History
VersionChanges
v23.4.0, v22.13.0

SQLite is no longer behind--experimental-sqlite but still experimental.

v22.5.0

Added in: v22.5.0

Stability: 1.1 - Active development.

Source Code:lib/sqlite.js

Thenode:sqlite module facilitates working with SQLite databases.To access it:

import sqlitefrom'node:sqlite';const sqlite =require('node:sqlite');

This module is only available under thenode: scheme.

The following example shows the basic usage of thenode:sqlite module to openan in-memory database, write data to the database, and then read the data back.

import {DatabaseSync }from'node:sqlite';const database =newDatabaseSync(':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 =newDatabaseSync(':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#

History
VersionChanges
v24.0.0, v22.16.0

Addtimeout option.

v23.10.0, v22.15.0

Thepath argument now supports Buffer and URL objects.

v22.5.0

Added in: v22.5.0

This class represents a singleconnection to a SQLite database. All APIsexposed by this class execute synchronously.

new DatabaseSync(path[, options])#

History
VersionChanges
v25.1.0

Adddefensive option.

v24.4.0, v22.18.0

Add new SQLite database options.

v22.5.0

Added in: v22.5.0

  • path<string> |<Buffer> |<URL> The path of the database. A SQLite database can bestored in a file or completelyin memory. To use a file-backed database,the path should be a file path. To use an in-memory database, the pathshould be the special name':memory:'.
  • options<Object> Configuration options for the database connection. Thefollowing options are supported:
    • open<boolean> Iftrue, the database is opened by the constructor. Whenthis value isfalse, the database must be opened via theopen() method.Default:true.
    • readOnly<boolean> Iftrue, the database is opened in read-only mode.If the database does not exist, opening it will fail.Default:false.
    • enableForeignKeyConstraints<boolean> Iftrue, foreign key constraintsare enabled. This is recommended but can be disabled for compatibility withlegacy database schemas. The enforcement of foreign key constraints can beenabled and disabled after opening the database usingPRAGMA foreign_keys.Default:true.
    • enableDoubleQuotedStringLiterals<boolean> Iftrue, SQLite will acceptdouble-quoted string literals. This is not recommended but can beenabled for compatibility with legacy database schemas.Default:false.
    • allowExtension<boolean> Iftrue, theloadExtension SQL functionand theloadExtension() method are enabled.You can callenableLoadExtension(false) later to disable this feature.Default:false.
    • timeout<number> Thebusy timeout in milliseconds. This is the maximum amount oftime that SQLite will wait for a database lock to be released beforereturning an error.Default:0.
    • readBigInts<boolean> Iftrue, integer fields are read as JavaScriptBigInt values. Iffalse,integer fields are read as JavaScript numbers.Default:false.
    • returnArrays<boolean> Iftrue, query results are returned as arrays instead of objects.Default:false.
    • allowBareNamedParameters<boolean> Iftrue, allows binding named parameters without the prefixcharacter (e.g.,foo instead of:foo).Default:true.
    • allowUnknownNamedParameters<boolean> Iftrue, unknown named parameters are ignored when binding.Iffalse, an exception is thrown for unknown named parameters.Default:false.
    • defensive<boolean> Iftrue, 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 usingenableDefensive().Default:false.

Constructs a newDatabaseSync instance.

database.aggregate(name, options)#

Added in: v24.0.0, v22.16.0

Registers a new aggregate function with the SQLite database. This method is a wrapper aroundsqlite3_create_window_function().

  • name<string> The name of the SQLite function to create.
  • options<Object> Function configuration settings.
    • deterministic<boolean> Iftrue, theSQLITE_DETERMINISTIC flag isset on the created function.Default:false.
    • directOnly<boolean> Iftrue, theSQLITE_DIRECTONLY flag is set onthe created function.Default:false.
    • useBigIntArguments<boolean> Iftrue, integer arguments tooptions.step andoptions.inverseare converted toBigInts. Iffalse, integer arguments are passed asJavaScript numbers.Default:false.
    • varargs<boolean> Iftrue,options.step andoptions.inverse may be invoked with any number ofarguments (between zero andSQLITE_MAX_FUNCTION_ARG). Iffalse,inverse andstep must be invoked with exactlylength arguments.Default:false.
    • start<number> |<string> |<null> |<Array> |<Object> |<Function> The identityvalue for the aggregation function. This value is used when the aggregationfunction 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. Thefunction receives the current state and the row value. The return value ofthis function should be the new state.
    • result<Function> The function to call to get the result of theaggregation. The function receives the final state and should return theresult of the aggregation.
    • inverse<Function> When this function is provided, theaggregate 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 thenew state.

When used as a window function, theresult function will be called multiple times.

const {DatabaseSync } =require('node:sqlite');const db =newDatabaseSync(':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 =newDatabaseSync(':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()#

Added in: v22.5.0

Closes the database connection. An exception is thrown if the database is notopen. This method is a wrapper aroundsqlite3_close_v2().

database.loadExtension(path)#

Added in: v23.5.0, v22.13.0
  • path<string> The path to the shared library to load.

Loads a shared library into the database connection. This method is a wrapperaroundsqlite3_load_extension(). It is required to enable theallowExtension option when constructing theDatabaseSync instance.

database.enableLoadExtension(allow)#

Added in: v23.5.0, v22.13.0
  • allow<boolean> Whether to allow loading extensions.

Enables or disables theloadExtension SQL function, and theloadExtension()method. WhenallowExtension isfalse when constructing, you cannot enableloading extensions for security reasons.

database.enableDefensive(active)#

Added in: v25.1.0
  • active<boolean> Whether to set the defensive flag.

Enables or disables the defensive flag. When the defensive flag is active,language features that allow ordinary SQL to deliberately corrupt the database file are disabled.SeeSQLITE_DBCONFIG_DEFENSIVE in the SQLite documentation for details.

database.location([dbName])#

Added in: v24.0.0, v22.16.0
  • dbName<string> Name of the database. This can be'main' (the default primary database) or any otherdatabase that has been added withATTACH DATABASEDefault:'main'.
  • Returns:<string> |<null> The location of the database file. When using an in-memory database,this method returns null.

This method is a wrapper aroundsqlite3_db_filename()

database.exec(sql)#

Added in: v22.5.0

This method allows one or more SQL statements to be executed without returningany results. This method is useful when executing SQL statements read from afile. This method is a wrapper aroundsqlite3_exec().

database.function(name[, options], function)#

Added in: v23.5.0, v22.13.0
  • name<string> The name of the SQLite function to create.
  • options<Object> Optional configuration settings for the function. Thefollowing properties are supported:
    • deterministic<boolean> Iftrue, theSQLITE_DETERMINISTIC flag isset on the created function.Default:false.
    • directOnly<boolean> Iftrue, theSQLITE_DIRECTONLY flag is set onthe created function.Default:false.
    • useBigIntArguments<boolean> Iftrue, integer arguments tofunctionare converted toBigInts. Iffalse, integer arguments are passed asJavaScript numbers.Default:false.
    • varargs<boolean> Iftrue,function may be invoked with any number ofarguments (between zero andSQLITE_MAX_FUNCTION_ARG). Iffalse,function must be invoked with exactlyfunction.length arguments.Default:false.
  • function<Function> The JavaScript function to call when the SQLitefunction is invoked. The return value of this function should be a validSQLite data type: seeType 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 awrapper aroundsqlite3_create_function_v2().

database.setAuthorizer(callback)#

Added in: v24.10.0
  • callback<Function> |<null> The authorizer function to set, ornull toclear the current authorizer.

Sets an authorizer callback that SQLite will invoke whenever it attempts toaccess 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 aroundsqlite3_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.

The callback must return one of the following constants:

  • 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 =newDatabaseSync(':memory:');// Set up an authorizer that denies all table creationdb.setAuthorizer((actionCode) => {if (actionCode === constants.SQLITE_CREATE_TABLE) {return constants.SQLITE_DENY;  }return constants.SQLITE_OK;});// This will workdb.prepare('SELECT 1').get();// This will throw an error due to authorization denialtry {  db.exec('CREATE TABLE blocked (id INTEGER)');}catch (err) {console.log('Operation blocked:', err.message);}import {DatabaseSync, constants }from'node:sqlite';const db =newDatabaseSync(':memory:');// Set up an authorizer that denies all table creationdb.setAuthorizer((actionCode) => {if (actionCode === constants.SQLITE_CREATE_TABLE) {return constants.SQLITE_DENY;  }return constants.SQLITE_OK;});// This will workdb.prepare('SELECT 1').get();// This will throw an error due to authorization denialtry {  db.exec('CREATE TABLE blocked (id INTEGER)');}catch (err) {console.log('Operation blocked:', err.message);}

database.isOpen#

Added in: v23.11.0, v22.15.0
  • Type:<boolean> Whether the database is currently open or not.

database.isTransaction#

Added in: v24.0.0, v22.16.0

database.open()#

Added in: v22.5.0

Opens the database specified in thepath argument of theDatabaseSyncconstructor. This method should only be used when the database is not opened viathe constructor. An exception is thrown if the database is already open.

database.prepare(sql)#

Added in: v22.5.0

Compiles a SQL statement into aprepared statement. This method is a wrapperaroundsqlite3_prepare_v2().

database.createTagStore([maxSize])#

Added in: v24.9.0
  • maxSize<integer> The maximum number of prepared statements to cache.Default:1000.
  • Returns:<SQLTagStore> A new SQL tag store for caching prepared statements.

Creates a newSQLTagStore, which is an LRU (Least Recently Used) cache forstoring prepared statements. This allows for the efficient reuse of preparedstatements by tagging them with a unique identifier.

When a tagged SQL literal is executed, theSQLTagStore checks if a preparedstatement for that specific SQL 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 toavoid the overhead of repeatedly parsing and preparing the same SQL statements.

import {DatabaseSync }from'node:sqlite';const db =newDatabaseSync(':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 id =1;const user = sql.get`SELECT * FROM users WHERE id =${id}`;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 =newDatabaseSync(':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 id =1;const user = sql.get`SELECT * FROM users WHERE id =${id}`;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])#

Added in: v23.3.0, v22.12.0
  • 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 usingATTACH DATABASE.Default:'main'.
  • Returns:<Session> A session handle.

Creates and attaches a session to the database. This method is a wrapper aroundsqlite3session_create() andsqlite3session_attach().

database.applyChangeset(changeset[, options])#

Added in: v23.3.0, v22.12.0
  • 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: 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 constraintviolation.

      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:<boolean> Whether the changeset was applied successfully without being aborted.

An exception is thrown if the database is notopen. This method is a wrapper aroundsqlite3changeset_apply().

import {DatabaseSync }from'node:sqlite';const sourceDb =newDatabaseSync(':memory:');const targetDb =newDatabaseSync(':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 =newDatabaseSync(':memory:');const targetDb =newDatabaseSync(':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]()#

History
VersionChanges
v24.2.0

No longer experimental.

v23.11.0, v22.15.0

Added in: v23.11.0, v22.15.0

Closes the database connection. If the database connection is already closedthen this is a no-op.

Class:Session#

Added in: v23.3.0, v22.12.0

session.changeset()#

Added in: v23.3.0, v22.12.0
  • Returns:<Uint8Array> Binary changeset that can be applied to other databases.

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 aroundsqlite3session_changeset().

session.patchset()#

Added in: v23.3.0, v22.12.0
  • Returns:<Uint8Array> Binary patchset that can be applied to other databases.

Similar to the method above, but generates a more compact patchset. SeeChangesets and Patchsetsin the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is awrapper aroundsqlite3session_patchset().

session.close().#

Closes the session. An exception is thrown if the database or the session is not open. This method is awrapper aroundsqlite3session_delete().

Class:StatementSync#

Added in: v22.5.0

This class represents a singleprepared statement. This class cannot beinstantiated via its constructor. Instead, instances are created via thedatabase.prepare() method. All APIs exposed by this class executesynchronously.

A prepared statement is an efficient binary representation of the SQL used tocreate it. Prepared statements are parameterizable, and can be invoked multipletimes with different bound values. Parameters also offer protection againstSQL injection attacks. For these reasons, prepared statements are preferredover hand-crafted SQL strings when handling user input.

statement.all([namedParameters][, ...anonymousParameters])#

History
VersionChanges
v23.7.0, v22.14.0

Add support forDataView and typed array objects foranonymousParameters.

v22.5.0

Added in: v22.5.0

  • 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 ormore values to bind to anonymous parameters.
  • Returns:<Array> An array of objects. Each object corresponds to a rowreturned by executing the prepared statement. The keys and values of eachobject correspond to the column names and values of the row.

This method executes a prepared statement and returns all results as an array ofobjects. If the prepared statement does not return any results, this methodreturns an empty array. The prepared statementparameters are bound usingthe values innamedParameters andanonymousParameters.

statement.columns()#

Added in: v23.11.0, v22.16.0
  • Returns:<Array> An array of objects. Each object corresponds to a columnin the prepared statement, and contains the following properties:

This method is used to retrieve information about the columns returned by theprepared statement.

statement.expandedSQL#

Added in: v22.5.0
  • Type:<string> The source SQL expanded to include parameter values.

The source SQL text of the prepared statement with parameterplaceholders replaced by the values that were used during the most recentexecution of this prepared statement. This property is a wrapper aroundsqlite3_expanded_sql().

statement.get([namedParameters][, ...anonymousParameters])#

History
VersionChanges
v23.7.0, v22.14.0

Add support forDataView and typed array objects foranonymousParameters.

v22.5.0

Added in: v22.5.0

  • 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 ormore values to bind to anonymous parameters.
  • Returns:<Object> |<undefined> An object corresponding to the first row returnedby executing the prepared statement. The keys and values of the objectcorrespond to the column names and values of the row. If no rows were returnedfrom the database then this method returnsundefined.

This method executes a prepared statement and returns the first result as anobject. If the prepared statement does not return any results, this methodreturnsundefined. The prepared statementparameters are bound using thevalues innamedParameters andanonymousParameters.

statement.iterate([namedParameters][, ...anonymousParameters])#

History
VersionChanges
v23.7.0, v22.14.0

Add support forDataView and typed array objects foranonymousParameters.

v23.4.0, v22.13.0

Added in: v23.4.0, v22.13.0

  • 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 ormore values to bind to anonymous parameters.
  • Returns:<Iterator> An iterable iterator of objects. Each object corresponds to a rowreturned by executing the prepared statement. The keys and values of eachobject correspond to the column names and values of the row.

This method executes a prepared statement and returns an iterator ofobjects. If the prepared statement does not return any results, this methodreturns an empty iterator. The prepared statementparameters are bound usingthe values innamedParameters andanonymousParameters.

statement.run([namedParameters][, ...anonymousParameters])#

History
VersionChanges
v23.7.0, v22.14.0

Add support forDataView and typed array objects foranonymousParameters.

v22.5.0

Added in: v22.5.0

  • 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 ormore values to bind to anonymous parameters.
  • Returns:<Object>
    • changes<number> |<bigint> The number of rows modified, inserted, or deletedby the most recently completedINSERT,UPDATE, orDELETE statement.This field is either a number or aBigInt depending on the preparedstatement's configuration. This property is the result ofsqlite3_changes64().
    • lastInsertRowid<number> |<bigint> The most recently inserted rowid. Thisfield is either a number or aBigInt depending on the prepared statement'sconfiguration. This property is the result ofsqlite3_last_insert_rowid().

This method executes a prepared statement and returns an object summarizing theresulting changes. The prepared statementparameters are bound using thevalues innamedParameters andanonymousParameters.

statement.setAllowBareNamedParameters(enabled)#

Added in: v22.5.0
  • enabled<boolean> Enables or disables support for binding named parameterswithout 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 bindingparameters. However, with the exception of dollar sign character, theseprefix characters also require extra quoting when used in object keys.

To improve ergonomics, this method can be used to also allow bare namedparameters, which do not require the prefix character in JavaScript code. Thereare 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 nameswill have slightly better binding performance.
  • Using ambiguous named parameters, such as$k and@k, in the same preparedstatement will result in an exception as it cannot be determined how to binda bare name.

statement.setAllowUnknownNamedParameters(enabled)#

Added in: v23.11.0, v22.15.0
  • enabled<boolean> Enables or disables support for unknown named parameters.

By default, if an unknown name is encountered while binding parameters, anexception is thrown. This method allows unknown named parameters to be ignored.

statement.setReturnArrays(enabled)#

Added in: v24.0.0, v22.16.0
  • enabled<boolean> Enables or disables the return of query results as arrays.

When enabled, query results returned by theall(),get(), anditerate() methods will be returned as arrays insteadof objects.

statement.setReadBigInts(enabled)#

Added in: v22.5.0
  • enabled<boolean> Enables or disables the use ofBigInts when readingINTEGER fields from the database.

When reading from the database, SQLiteINTEGERs are mapped to JavaScriptnumbers by default. However, SQLiteINTEGERs can store values larger thanJavaScript numbers are capable of representing. In such cases, this method canbe used to readINTEGER data using JavaScriptBigInts. This method has noimpact on database write operations where numbers andBigInts are bothsupported at all times.

statement.sourceSQL#

Added in: v22.5.0
  • Type:<string> The source SQL used to create this prepared statement.

The source SQL text of the prepared statement. This property is awrapper aroundsqlite3_sql().

Class:SQLTagStore#

Added in: v24.9.0

This class represents a single LRU (Least Recently Used) cache for storingprepared statements.

Instances of this class are created via the database.createTagStore() method,not by using a constructor. The store caches prepared statements based on theprovided SQL query string. When the same query is seen again, the storeretrieves the cached statement and safely applies the new values throughparameter binding, thereby preventing attacks like SQL injection.

The cache has a maxSize that defaults to 1000 statements, but a custom size canbe provided (e.g., database.createTagStore(100)). All APIs exposed by thisclass execute synchronously.

sqlTagStore.all(sqlTemplate[, ...values])#

Added in: v24.9.0
  • sqlTemplate<Template Literal> A template literal containing the SQL query.
  • ...values<any> Values to be interpolated into the template literal.
  • Returns:<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.

sqlTagStore.get(sqlTemplate[, ...values])#

Added in: v24.9.0
  • sqlTemplate<Template Literal> A template literal containing the SQL query.
  • ...values<any> Values to be interpolated into the template literal.
  • Returns:<Object> |<undefined> An object representing the first row returned bythe query, orundefined if no rows are returned.

Executes the given SQL query and returns the first resulting row as an object.

sqlTagStore.iterate(sqlTemplate[, ...values])#

Added in: v24.9.0
  • sqlTemplate<Template Literal> A template literal containing the SQL query.
  • ...values<any> Values to be interpolated into the template literal.
  • Returns:<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.

sqlTagStore.run(sqlTemplate[, ...values])#

Added in: v24.9.0
  • sqlTemplate<Template Literal> A template literal containing the SQL query.
  • ...values<any> Values to be interpolated into the template literal.
  • Returns:<Object> An object containing information about the execution, includingchanges andlastInsertRowid.

Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE).

sqlTagStore.size()#

Added in: v24.9.0
  • Returns:<integer> The number of prepared statements currently in the cache.

A read-only property that returns the number of prepared statements currently in the cache.

sqlTagStore.capacity#

Added in: v24.9.0
  • Returns:<integer> The maximum number of prepared statements the cache can hold.

A read-only property that returns the maximum number of prepared statements the cache can hold.

sqlTagStore.db#

Added in: v24.9.0

A read-only property that returns theDatabaseSync object associated with thisSQLTagStore.

sqlTagStore.reset()#

Added in: v24.9.0

Resets the LRU cache, clearing all stored prepared statements.

sqlTagStore.clear()#

Added in: v24.9.0

An alias forsqlTagStore.reset().

Type conversion between JavaScript and SQLite#

When Node.js writes to or reads from SQLite it is necessary to convert betweenJavaScript data types and SQLite'sdata types. Because JavaScript supportsmore data types than SQLite, only a subset of JavaScript types are supported.Attempting to write an unsupported data type to SQLite will result in anexception.

SQLiteJavaScript
NULL<null>
INTEGER<number> or<bigint>
REAL<number>
TEXT<string>
BLOB<TypedArray> or<DataView>

sqlite.backup(sourceDb, path[, options])#

History
VersionChanges
v23.10.0

Thepath argument now supports Buffer and URL objects.

v23.8.0, v22.16.0

Added in: v23.8.0, v22.16.0

  • 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. Thefollowing properties are supported:
    • source<string> Name of the source database. This can be'main' (the default primary database) or any otherdatabase that have been added withATTACH DATABASEDefault:'main'.
    • target<string> Name of the target database. This can be'main' (the default primary database) or any otherdatabase that have been added withATTACH DATABASEDefault:'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 passedto this callback is an<Object> withremainingPages andtotalPages properties, describing the current progressof the backup operation.
  • Returns:<Promise> A promise that fulfills with the total number of backed-up pages upon completion, or rejects if anerror occurs.

This method makes a database backup. This method abstracts thesqlite3_backup_init(),sqlite3_backup_step()andsqlite3_backup_finish() functions.

The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same<DatabaseSync> - object will be reflected in the backup right away. However, mutations from other connections will causethe backup process to restart.

const { backup,DatabaseSync } =require('node:sqlite');(async () => {const sourceDb =newDatabaseSync('source.db');const totalPagesTransferred =awaitbackup(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 =newDatabaseSync('source.db');const totalPagesTransferred =awaitbackup(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, v22.13.0

An object containing commonly used constants for SQLite operations.

SQLite constants#

The following constants are exported by thesqlite.constants object.

Conflict resolution constants#

One of the following constants is available as an argument to theonConflictconflict resolution handler passed todatabase.applyChangeset(). See alsoConstants Passed To The Conflict Handler in the SQLite documentation.

ConstantDescription
SQLITE_CHANGESET_DATAThe 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_NOTFOUNDThe 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_CONFLICTThis constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.
SQLITE_CHANGESET_CONSTRAINTIf 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 returnsSQLITE_CHANGESET_OMIT, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returnsSQLITE_CHANGESET_ABORT, the changeset is rolled back.
SQLITE_CHANGESET_FOREIGN_KEYIf 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 theonConflict conflictresolution handler passed todatabase.applyChangeset(). See alsoConstants Returned From The Conflict Handler in the SQLite documentation.

ConstantDescription
SQLITE_CHANGESET_OMITConflicting changes are omitted.
SQLITE_CHANGESET_REPLACEConflicting changes replace existing values. Note that this value can only be returned when the type of conflict is eitherSQLITE_CHANGESET_DATA orSQLITE_CHANGESET_CONFLICT.
SQLITE_CHANGESET_ABORTAbort when a change encounters a conflict and roll back database.
Authorization constants#

The following constants are used with thedatabase.setAuthorizer() method.

Authorization result codes#

One of the following constants must be returned from the authorizer callbackfunction passed todatabase.setAuthorizer().

ConstantDescription
SQLITE_OKAllow the operation to proceed normally.
SQLITE_DENYDeny the operation and cause an error to be returned.
SQLITE_IGNOREIgnore the operation and continue as if it had never been requested.
Authorization action codes#

The following constants are passed as the first argument to the authorizercallback function to indicate what type of operation is being authorized.

ConstantDescription
SQLITE_CREATE_INDEXCreate an index
SQLITE_CREATE_TABLECreate a table
SQLITE_CREATE_TEMP_INDEXCreate a temporary index
SQLITE_CREATE_TEMP_TABLECreate a temporary table
SQLITE_CREATE_TEMP_TRIGGERCreate a temporary trigger
SQLITE_CREATE_TEMP_VIEWCreate a temporary view
SQLITE_CREATE_TRIGGERCreate a trigger
SQLITE_CREATE_VIEWCreate a view
SQLITE_DELETEDelete from a table
SQLITE_DROP_INDEXDrop an index
SQLITE_DROP_TABLEDrop a table
SQLITE_DROP_TEMP_INDEXDrop a temporary index
SQLITE_DROP_TEMP_TABLEDrop a temporary table
SQLITE_DROP_TEMP_TRIGGERDrop a temporary trigger
SQLITE_DROP_TEMP_VIEWDrop a temporary view
SQLITE_DROP_TRIGGERDrop a trigger
SQLITE_DROP_VIEWDrop a view
SQLITE_INSERTInsert into a table
SQLITE_PRAGMAExecute a PRAGMA statement
SQLITE_READRead from a table
SQLITE_SELECTExecute a SELECT statement
SQLITE_TRANSACTIONBegin, commit, or rollback a transaction
SQLITE_UPDATEUpdate a table
SQLITE_ATTACHAttach a database
SQLITE_DETACHDetach a database
SQLITE_ALTER_TABLEAlter a table
SQLITE_REINDEXReindex
SQLITE_ANALYZEAnalyze the database
SQLITE_CREATE_VTABLECreate a virtual table
SQLITE_DROP_VTABLEDrop a virtual table
SQLITE_FUNCTIONUse a function
SQLITE_SAVEPOINTCreate, release, or rollback a savepoint
SQLITE_COPYCopy data (legacy)
SQLITE_RECURSIVERecursive query