Bun

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

    • Abort when a change encounters a conflict and roll back database.

    • This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.

    • const SQLITE_CHANGESET_DATA: number

      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 returns SQLITE_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.

    • const SQLITE_CHANGESET_OMIT: number

      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 or SQLITE_CHANGESET_CONFLICT.

  • class DatabaseSync

    This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.

    • readonly isOpen: boolean

      Whether the database is currently open or not.

    • Closes the database connection. If the database connection is already closed then this is a no-op.

    • changeset: Uint8Array,
      ): 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 changeset

      A binary changeset or patchset.

      @param options

      The configuration options for how the changes will be applied.

      @returns

      Whether the changeset was applied successfully without being aborted.

    • close(): void;

      Closes the database connection. An exception is thrown if the database is not open. This method is a wrapper around sqlite3_close_v2().

    • @param options

      The configuration options for the session.

      @returns

      A session handle.

    • allow: boolean
      ): void;

      Enables or disables the loadExtension SQL function, and the loadExtension() method. When allowExtension is false when constructing, you cannot enable loading extensions for security reasons.

      @param allow

      Whether to allow loading extensions.

    • 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 sql

      A SQL string to execute.

    • name: string,
      options: FunctionOptions,
      func: (...args: SQLOutputValue[]) => SQLInputValue
      ): void;
      @param name

      The name of the SQLite function to create.

      @param options

      Optional configuration settings for the function.

      @param func

      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.

      name: string,
      func: (...args: SQLOutputValue[]) => SQLInputValue
      ): void;
      @param name

      The name of the SQLite function to create.

      @param func

      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.

    • 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 the allowExtension option when constructing the DatabaseSync instance.

      @param path

      The path to the shared library to load.

    • open(): void;

      Opens the database specified in the path argument of the DatabaseSyncconstructor. 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
      @param sql

      A SQL string to compile to a prepared statement.

      @returns

      The prepared statement.

  • class StatementSync

    This class represents a single prepared statement. This class cannot be instantiated via its constructor. Instead, instances are created via thedatabase.prepare() method. All APIs exposed by this class execute synchronously.

    A prepared statement is an efficient binary representation of the SQL used to create it. Prepared statements are parameterizable, and can be invoked multiple times with different bound values. Parameters also offer protection 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().

    • ...anonymousParameters: SQLInputValue[]
      ): Record<string, SQLOutputValue>[];

      This method executes a prepared statement and returns all results as an array of objects. If the prepared statement does not return any results, this method returns an empty array. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param anonymousParameters

      Zero or more values to bind to anonymous parameters.

      @returns

      An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.

      namedParameters: Record<string, SQLInputValue>,
      ...anonymousParameters: SQLInputValue[]
      ): Record<string, SQLOutputValue>[];

      This method executes a prepared statement and returns all results as an array of objects. If the prepared statement does not return any results, this method returns an empty array. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param namedParameters

      An optional object used to bind named parameters. The keys of this object are used to configure the mapping.

      @param anonymousParameters

      Zero or more values to bind to anonymous parameters.

      @returns

      An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.

    • ...anonymousParameters: SQLInputValue[]
      ): undefined | Record<string, SQLOutputValue>;

      This method executes a prepared statement and returns the first result as an object. If the prepared statement does not return any results, this method returns undefined. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param anonymousParameters

      Zero or more values to bind to anonymous parameters.

      @returns

      An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no rows were returned from the database then this method returns undefined.

      namedParameters: Record<string, SQLInputValue>,
      ...anonymousParameters: SQLInputValue[]
      ): undefined | Record<string, SQLOutputValue>;

      This method executes a prepared statement and returns the first result as an object. If the prepared statement does not return any results, this method returns undefined. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param namedParameters

      An optional object used to bind named parameters. The keys of this object are used to configure the mapping.

      @param anonymousParameters

      Zero or more values to bind to anonymous parameters.

      @returns

      An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no rows were returned from the database then this method returns undefined.

    • ...anonymousParameters: SQLInputValue[]
      ): Iterator<Record<string, SQLOutputValue>>;

      This method executes a prepared statement and returns an iterator of objects. If the prepared statement does not return any results, this method returns an empty iterator. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param anonymousParameters

      Zero or more values to bind to anonymous parameters.

      @returns

      An iterable iterator of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.

      namedParameters: Record<string, SQLInputValue>,
      ...anonymousParameters: SQLInputValue[]
      ): Iterator<Record<string, SQLOutputValue>>;

      This method executes a prepared statement and returns an iterator of objects. If the prepared statement does not return any results, this method returns an empty iterator. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param namedParameters

      An optional object used to bind named parameters. The keys of this object are used to configure the mapping.

      @param anonymousParameters

      Zero or more values to bind to anonymous parameters.

      @returns

      An iterable iterator of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.

    • ...anonymousParameters: SQLInputValue[]

      This method executes a prepared statement and returns an object summarizing the resulting changes. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param anonymousParameters

      Zero or more values to bind to anonymous parameters.

      namedParameters: Record<string, SQLInputValue>,
      ...anonymousParameters: SQLInputValue[]

      This method executes a prepared statement and returns an object summarizing the resulting changes. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

      @param namedParameters

      An optional object used to bind named parameters. The keys of this object are used to configure the mapping.

      @param anonymousParameters

      Zero 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 enabled

      Enables 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 enabled

      Enables 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, 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.

      @param enabled

      Enables or disables the use of BigInts when reading INTEGER 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: 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.

  • interface CreateSessionOptions

    • db?: string

      Name of the database to track. This is useful when multiple databases have been added using ATTACH DATABASE.

    • table?: string

      A specific table to track changes for. By default, changes to all tables are tracked.

  • interface DatabaseSyncOptions

    • allowExtension?: boolean

      If true, the loadExtension SQL function and the loadExtension() method are enabled. You can call enableLoadExtension(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 using PRAGMA foreign_keys.

    • 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.

    • readOnly?: boolean

      If true, the database is opened in read-only mode. If the database does not exist, opening it will fail.

  • interface FunctionOptions

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

      @returns

      Binary changeset that can be applied to other databases.

    • close(): void;

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

      @returns

      Binary 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, 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().

  • type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView
  • type SQLOutputValue = null | number | bigint | string | Uint8Array