Constructs a new DatabaseSync instance.
constructor
sqlite.DatabaseSync.constructor
Not implemented in Bun
The path of the database. A SQLite database can be stored in a file or completely in memory. To use a file-backed database, the path should be a file path. To use an in-memory database, the path should be the special name ':memory:'.
Configuration options for the database connection.
Referenced types
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.
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.