Abort when a change encounters a conflict and roll back database.
Node.js module
node:sqlite
Not implemented in Bun
Not implemented. Consider using `bun:sqlite` for Bun's built-in high-performance SQLite driver.
namespace constants
This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.
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.
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 returnsSQLITE_CHANGESET_ABORT, the changeset is rolled back.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.
Conflicting changes are omitted.
Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either
SQLITE_CHANGESET_DATAorSQLITE_CHANGESET_CONFLICT.Deny the operation and cause an error to be returned.
Ignore the operation and continue as if it had never been requested.
Allow the operation to proceed normally.
class DatabaseSync
This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.
- readonly isTransaction: boolean
Whether the database is currently within a transaction. This method is a wrapper around
sqlite3_get_autocommit(). Closes the database connection. If the database connection is already closed then this is a no-op.
- name: string,): void;
Registers a new aggregate function with the SQLite database. This method is a wrapper around
sqlite3_create_window_function().When used as a window function, the
resultfunction will be called multiple times.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 }@param nameThe name of the SQLite function to create.
@param optionsFunction configuration settings.
name: string,): void;Registers a new aggregate function with the SQLite database. This method is a wrapper around
sqlite3_create_window_function().When used as a window function, the
resultfunction will be called multiple times.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 }@param nameThe name of the SQLite function to create.
@param optionsFunction configuration settings.
- ): boolean;
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.@param changesetA binary changeset or patchset.
@param optionsThe configuration options for how the changes will be applied.
@returnsWhether the changeset was applied successfully without being aborted.
Closes the database connection. An exception is thrown if the database is not open. This method is a wrapper around
sqlite3_close_v2().Creates and attaches a session to the database. This method is a wrapper around
sqlite3session_create()andsqlite3session_attach().@param optionsThe configuration options for the session.
@returnsA session handle.
- maxSize?: number
Creates a new
SQLTagStore, which is an LRU (Least Recently Used) 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
SQLTagStorechecks if a prepared statement 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 to avoid the overhead of repeatedly parsing and preparing the same SQL statements.import { DatabaseSync } from 'node:sqlite'; const db = new DatabaseSync(':memory:'); const sql = db.createSQLTagStore(); 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' } // ]@returnsA new SQL tag store for caching prepared statements.
- allow: boolean): void;
Enables or disables the
loadExtensionSQL function, and theloadExtension()method. WhenallowExtensionisfalsewhen constructing, you cannot enable loading extensions for security reasons.@param allowWhether to allow loading extensions.
- exec(sql: string): void;
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().@param sqlA SQL string to execute.
- name: string,): void;
This method is used to create SQLite user-defined functions. This method is a wrapper around
sqlite3_create_function_v2().@param nameThe name of the SQLite function to create.
@param optionsOptional configuration settings for the function.
@param funcThe 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
NULLif the return value isundefined.name: string,): void;This method is used to create SQLite user-defined functions. This method is a wrapper around
sqlite3_create_function_v2().@param nameThe name of the SQLite function to create.
@param funcThe 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
NULLif the return value isundefined. - path: string): void;
Loads a shared library into the database connection. This method is a wrapper around
sqlite3_load_extension(). It is required to enable theallowExtensionoption when constructing theDatabaseSyncinstance.@param pathThe path to the shared library to load.
- @param dbName
Name of the database. This can be
'main'(the default primary database) or any other database that has been added withATTACH DATABASEDefault:'main'.@returnsThe location of the database file. When using an in-memory database, this method returns null.
Opens the database specified in the
pathargument of theDatabaseSyncconstructor. 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.- sql: string
Compiles a SQL statement into a prepared statement. This method is a wrapper around
sqlite3_prepare_v2().@param sqlA SQL string to compile to a prepared statement.
@returnsThe prepared statement.
- callback: null | (actionCode: number, arg1: null | string, arg2: null | string, dbName: null | string, triggerOrView: null | string) => number): void;
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.
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).
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); }@param callbackThe authorizer function to set, or
nullto clear the current authorizer.
class 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.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 against SQL injection attacks. For these reasons, prepared statements are preferred over hand-crafted SQL strings when handling user input.
- readonly expandedSQL: string
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 around
sqlite3_expanded_sql(). - readonly sourceSQL: string
The source SQL text of the prepared statement. This property is a wrapper around
sqlite3_sql(). - all(
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
namedParametersandanonymousParameters.@param anonymousParametersZero or more values to bind to anonymous parameters.
@returnsAn 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.
all(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
namedParametersandanonymousParameters.@param namedParametersAn optional object used to bind named parameters. The keys of this object are used to configure the mapping.
@param anonymousParametersZero or more values to bind to anonymous parameters.
@returnsAn 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 is used to retrieve information about the columns returned by the prepared statement.
@returnsAn array of objects. Each object corresponds to a column in the prepared statement, and contains the following properties:
- get(
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 innamedParametersandanonymousParameters.@param anonymousParametersZero or more values to bind to anonymous parameters.
@returnsAn 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.get(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 innamedParametersandanonymousParameters.@param namedParametersAn optional object used to bind named parameters. The keys of this object are used to configure the mapping.
@param anonymousParametersZero or more values to bind to anonymous parameters.
@returnsAn 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 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
namedParametersandanonymousParameters.@param anonymousParametersZero or more values to bind to anonymous parameters.
@returnsAn 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
namedParametersandanonymousParameters.@param namedParametersAn optional object used to bind named parameters. The keys of this object are used to configure the mapping.
@param anonymousParametersZero or more values to bind to anonymous parameters.
@returnsAn 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.
- run(
This method executes a prepared statement and returns an object summarizing the resulting changes. The prepared statement parameters are bound using the values in
namedParametersandanonymousParameters.@param anonymousParametersZero or more values to bind to anonymous parameters.
run(This method executes a prepared statement and returns an object summarizing the resulting changes. The prepared statement parameters are bound using the values in
namedParametersandanonymousParameters.@param namedParametersAn optional object used to bind named parameters. The keys of this object are used to configure the mapping.
@param anonymousParametersZero or more values to bind to anonymous parameters.
- enabled: boolean): void;
The names of SQLite parameters begin with a prefix character. By default,
node:sqliterequires 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
$kand@k, in the same prepared statement will result in an exception as it cannot be determined how to bind a bare name.
@param enabledEnables or disables support for binding named parameters without the prefix character.
- enabled: boolean): void;
By default, if an unknown name is encountered while binding parameters, an exception is thrown. This method allows unknown named parameters to be ignored.
@param enabledEnables or disables support for unknown named parameters.
- enabled: boolean): void;
When reading from the database, SQLite
INTEGERs are mapped to JavaScript numbers by default. However, SQLiteINTEGERs can store values larger than JavaScript numbers are capable of representing. In such cases, this method can be used to readINTEGERdata using JavaScriptBigInts. This method has no impact on database write operations where numbers andBigInts are both supported at all times.@param enabledEnables or disables the use of
BigInts when readingINTEGERfields from the database. - enabled: boolean): void;
When enabled, query results returned by the
all(),get(), anditerate()methods will be returned as arrays instead of objects.@param enabledEnables or disables the return of query results as arrays.
- ): Promise<number>;
This method makes a database backup. This method abstracts the
sqlite3_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 cause the backup process to restart.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);@param sourceDbThe database to backup. The source database must be open.
@param pathThe path where the backup will be created. If the file already exists, the contents will be overwritten.
@param optionsOptional configuration for the backup. The following properties are supported:
@returnsA promise that fulfills with the total number of backed-up pages upon completion, or rejects if an error occurs.
Type definitions
interface AggregateOptions<T extends SQLInputValue = SQLInputValue>
- inverse?: (accumulator: T, ...args: SQLOutputValue[]) => T
When this function is provided, the
aggregatemethod 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?: (accumulator: T) => SQLInputValue
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.
- start: T | () => T
The identity value for the aggregation function. This value is used when the aggregation function is initialized. When a
Functionis passed the identity will be its return value. - step: (accumulator: T, ...args: SQLOutputValue[]) => T
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.
- useBigIntArguments?: boolean
If
true, integer arguments tofunctionare converted toBigInts. Iffalse, integer arguments are passed as JavaScript numbers. - varargs?: boolean
If
true,functionmay be invoked with any number of arguments (between zero andSQLITE_MAX_FUNCTION_ARG). Iffalse,functionmust be invoked with exactlyfunction.lengtharguments.
interface ApplyChangesetOptions
- filter?: (tableName: string) => boolean
Skip changes that, when targeted table name is supplied to this function, return a truthy value. By default, all changes are attempted.
- onConflict?: (conflictType: number) => number
A function that determines how to handle conflicts. The function receives one argument, which can be one of the following values:
SQLITE_CHANGESET_DATA: ADELETEorUPDATEchange does not contain the expected "before" values.SQLITE_CHANGESET_NOTFOUND: A row matching the primary key of theDELETEorUPDATEchange does not exist.SQLITE_CHANGESET_CONFLICT: AnINSERTchange 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 NULLconstraint 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_DATAorSQLITE_CHANGESET_CONFLICTconflicts).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.
interface BackupOptions
- progress?: (progressInfo: BackupProgressInfo) => void
An optional callback function that will be called after each backup step. The argument passed to this callback is an
ObjectwithremainingPagesandtotalPagesproperties, describing the current progress of the backup operation. - source?: string
Name of the source database. This can be
'main'(the default primary database) or any other database that have been added withATTACH DATABASE - target?: string
Name of the target database. This can be
'main'(the default primary database) or any other database that have been added withATTACH DATABASE
interface BackupProgressInfo
interface CreateSessionOptions
- db?: string
Name of the database to track. This is useful when multiple databases have been added using
ATTACH DATABASE.
interface DatabaseSyncOptions
- allowBareNamedParameters?: boolean
If
true, allows binding named parameters without the prefix character (e.g.,fooinstead of:foo). - allowExtension?: boolean
If
true, theloadExtensionSQL function and theloadExtension()method are enabled. You can callenableLoadExtension(false)later to disable this feature. - allowUnknownNamedParameters?: boolean
If
true, unknown named parameters are ignored when binding. Iffalse, an exception is thrown for unknown named parameters. - 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. - 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 usingPRAGMA foreign_keys. - open?: boolean
If
true, the database is opened by the constructor. When this value isfalse, the database must be opened via theopen()method. - readBigInts?: boolean
If
true, integer fields are read as JavaScriptBigIntvalues. Iffalse, integer fields are read as JavaScript numbers. - readOnly?: boolean
If
true, the database is opened in read-only mode. If the database does not exist, opening it will fail. - 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.
interface FunctionOptions
- useBigIntArguments?: boolean
If
true, integer arguments tofunctionare converted toBigInts. Iffalse, integer arguments are passed as JavaScript numbers. - varargs?: boolean
If
true,functionmay be invoked with any number of arguments (between zero andSQLITE_MAX_FUNCTION_ARG). Iffalse,functionmust be invoked with exactlyfunction.lengtharguments.
interface Session
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().@returnsBinary changeset that can be applied to other databases.
Closes the session. An exception is thrown if the database or the session is not open. This method is a wrapper around
sqlite3session_delete().Similar to the method above, but generates a more compact patchset. See Changesets and Patchsets in 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().@returnsBinary patchset that can be applied to other databases.
interface SQLTagStore
This class represents a single LRU (Least Recently Used) cache for storing prepared statements.
Instances of this class are created via the database.createSQLTagStore() 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.
The cache has a maxSize that defaults to 1000 statements, but a custom size can be provided (e.g., database.createSQLTagStore(100)). All APIs exposed by this class execute synchronously.
- readonly capacity: number
A read-only property that returns the maximum number of prepared statements the cache can hold.
- readonly db: DatabaseSync
A read-only property that returns the
DatabaseSyncobject associated with thisSQLTagStore. - all(stringElements: TemplateStringsArray,
Executes the given SQL query and returns all resulting rows as an array of objects.
Resets the LRU cache, clearing all stored prepared statements.
- get(stringElements: TemplateStringsArray,
Executes the given SQL query and returns the first resulting row as an object.
- stringElements: TemplateStringsArray,
Executes the given SQL query and returns an iterator over the resulting rows.
- run(stringElements: TemplateStringsArray,
Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE).
A read-only property that returns the number of prepared statements currently in the cache.
@returnsThe maximum number of prepared statements the cache can hold.
interface StatementColumnMetadata
- column: null | string
The unaliased name of the column in the origin table, or
nullif the column is the result of an expression or subquery. This property is the result ofsqlite3_column_origin_name(). - database: null | string
The unaliased name of the origin database, or
nullif the column is the result of an expression or subquery. This property is the result ofsqlite3_column_database_name(). - name: string
The name assigned to the column in the result set of a
SELECTstatement. This property is the result ofsqlite3_column_name(). - table: null | string
The unaliased name of the origin table, or
nullif the column is the result of an expression or subquery. This property is the result ofsqlite3_column_table_name(). - type: null | string
The declared data type of the column, or
nullif the column is the result of an expression or subquery. This property is the result ofsqlite3_column_decltype().
interface StatementResultingChanges
- changes: number | bigint
The number of rows modified, inserted, or deleted by the most recently completed
INSERT,UPDATE, orDELETEstatement. This field is either a number or aBigIntdepending on the prepared statement's configuration. This property is the result ofsqlite3_changes64(). - lastInsertRowid: number | bigint
The most recently inserted rowid. This field is either a number or a
BigIntdepending on the prepared statement's configuration. This property is the result ofsqlite3_last_insert_rowid().
- type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView
- type SQLOutputValue = null | number | bigint | string | NodeJS.NonSharedUint8Array