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_DATA
orSQLITE_CHANGESET_CONFLICT
.
class DatabaseSync
This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.
Closes the database connection. If the database connection is already closed then this is a no-op.
- ): 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.
- allow: boolean): void;
Enables or disables the
loadExtension
SQL function, and theloadExtension()
method. WhenallowExtension
isfalse
when 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
NULL
if 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
NULL
if 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 theallowExtension
option when constructing theDatabaseSync
instance.@param pathThe path to the shared library to load.
Opens the database specified in the
path
argument of theDatabaseSync
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.- 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.
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
namedParameters
andanonymousParameters
.@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
namedParameters
andanonymousParameters
.@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.
- 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 innamedParameters
andanonymousParameters
.@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 innamedParameters
andanonymousParameters
.@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
namedParameters
andanonymousParameters
.@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
namedParameters
andanonymousParameters
.@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
namedParameters
andanonymousParameters
.@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
namedParameters
andanonymousParameters
.@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:sqlite
requires that this prefix character is present when binding parameters. However, with the exception of dollar sign character, these prefix characters also require extra quoting when used in object keys.To improve ergonomics, this method can be used to also allow bare named parameters, which do not require the prefix character in JavaScript code. There are several caveats to be aware of when enabling bare named parameters:
- The prefix character is still required in SQL.
- The prefix character is still allowed in JavaScript. In fact, prefixed names will have slightly better binding performance.
- Using ambiguous named parameters, such as
$k
and@k
, in the same prepared statement will result in an exception as it cannot be determined how to bind a bare name.
@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
INTEGER
s are mapped to JavaScript numbers by default. However, SQLiteINTEGER
s can store values larger than JavaScript numbers are capable of representing. In such cases, this method can be used to readINTEGER
data using JavaScriptBigInt
s. This method has no impact on database write operations where numbers andBigInt
s are both supported at all times.@param enabledEnables or disables the use of
BigInt
s when readingINTEGER
fields from the database.
Type definitions
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
: ADELETE
orUPDATE
change does not contain the expected "before" values.SQLITE_CHANGESET_NOTFOUND
: A row matching the primary key of theDELETE
orUPDATE
change does not exist.SQLITE_CHANGESET_CONFLICT
: AnINSERT
change results in a duplicate primary key.SQLITE_CHANGESET_FOREIGN_KEY
: Applying a change would result in a foreign key violation.SQLITE_CHANGESET_CONSTRAINT
: Applying a change results in aUNIQUE
,CHECK
, orNOT NULL
constraint violation.
The function should return one of the following values:
SQLITE_CHANGESET_OMIT
: Omit conflicting changes.SQLITE_CHANGESET_REPLACE
: Replace existing values with conflicting changes (only valid withSQLITE_CHANGESET_DATA
orSQLITE_CHANGESET_CONFLICT
conflicts).SQLITE_CHANGESET_ABORT
: Abort on conflict and roll back the database.
When an error is thrown in the conflict handler or when any other value is returned from the handler, applying the changeset is aborted and the database is rolled back.
Default: A function that returns
SQLITE_CHANGESET_ABORT
.
interface CreateSessionOptions
- db?: string
Name of the database to track. This is useful when multiple databases have been added using
ATTACH DATABASE
.
interface DatabaseSyncOptions
- allowExtension?: boolean
If
true
, theloadExtension
SQL function and theloadExtension()
method are enabled. You can callenableLoadExtension(false)
later to disable this feature. - 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. - readOnly?: boolean
If
true
, the database is opened in read-only mode. If the database does not exist, opening it will fail.
interface FunctionOptions
- useBigIntArguments?: boolean
If
true
, integer arguments tofunction
are converted toBigInt
s. Iffalse
, integer arguments are passed as JavaScript numbers. - varargs?: boolean
If
true
,function
may be invoked with any number of arguments (between zero andSQLITE_MAX_FUNCTION_ARG
). Iffalse
,function
must be invoked with exactlyfunction.length
arguments.
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 StatementResultingChanges
- changes: number | bigint
The number of rows modified, inserted, or deleted by the most recently completed
INSERT
,UPDATE
, orDELETE
statement. This field is either a number or aBigInt
depending on the prepared statement's configuration. This property is the result ofsqlite3_changes64()
. - lastInsertRowid: 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 ofsqlite3_last_insert_rowid()
.
- type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView
- type SQLOutputValue = null | number | bigint | string | Uint8Array