The node:sqlite module facilitates working with SQLite databases.\nTo access it:
import sqlite from 'node:sqlite';\n\nconst sqlite = require('node:sqlite');\n\nThis module is only available under the node: scheme.
The following example shows the basic usage of the node:sqlite module to open\nan in-memory database, write data to the database, and then read the data back.
import { DatabaseSync } from 'node:sqlite';\nconst database = new DatabaseSync(':memory:');\n\n// Execute SQL statements from strings.\ndatabase.exec(`\n CREATE TABLE data(\n key INTEGER PRIMARY KEY,\n value TEXT\n ) STRICT\n`);\n// Create a prepared statement to insert data into the database.\nconst insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\n// Execute the prepared statement with bound values.\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n// Create a prepared statement to read data from the database.\nconst query = database.prepare('SELECT * FROM data ORDER BY key');\n// Execute the prepared statement and log the result set.\nconsole.log(query.all());\n// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]\n\n'use strict';\nconst { DatabaseSync } = require('node:sqlite');\nconst database = new DatabaseSync(':memory:');\n\n// Execute SQL statements from strings.\ndatabase.exec(`\n CREATE TABLE data(\n key INTEGER PRIMARY KEY,\n value TEXT\n ) STRICT\n`);\n// Create a prepared statement to insert data into the database.\nconst insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\n// Execute the prepared statement with bound values.\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n// Create a prepared statement to read data from the database.\nconst query = database.prepare('SELECT * FROM data ORDER BY key');\n// Execute the prepared statement and log the result set.\nconsole.log(query.all());\n// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]\n",
"classes": [
{
"textRaw": "Class: `DatabaseSync`",
"name": "DatabaseSync",
"type": "class",
"meta": {
"added": [
"v22.5.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57752",
"description": "Add `timeout` option."
},
{
"version": [
"v23.10.0",
"v22.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/56991",
"description": "The `path` argument now supports Buffer and URL objects."
}
]
},
"desc": "This class represents a single connection to a SQLite database. All APIs\nexposed by this class execute synchronously.
", "signatures": [ { "textRaw": "`new DatabaseSync(path[, options])`", "name": "DatabaseSync", "type": "ctor", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": "v25.5.0", "pr-url": "https://github.com/nodejs/node/pull/61266", "description": "Enable `defensive` by default." }, { "version": [ "v25.1.0" ], "pr-url": "https://github.com/nodejs/node/pull/60217", "description": "Add `defensive` option." }, { "version": [ "v24.4.0", "v22.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/58697", "description": "Add new SQLite database options." } ] }, "params": [ { "textRaw": "`path` {string|Buffer|URL} 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:'`.", "name": "path", "type": "string|Buffer|URL", "desc": "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:'`." }, { "textRaw": "`options` {Object} Configuration options for the database connection. The following options are supported:", "name": "options", "type": "Object", "desc": "Configuration options for the database connection. The following options are supported:", "options": [ { "textRaw": "`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. **Default:** `true`.", "name": "open", "type": "boolean", "default": "`true`", "desc": "If `true`, the database is opened by the constructor. When this value is `false`, the database must be opened via the `open()` method." }, { "textRaw": "`readOnly` {boolean} If `true`, the database is opened in read-only mode. If the database does not exist, opening it will fail. **Default:** `false`.", "name": "readOnly", "type": "boolean", "default": "`false`", "desc": "If `true`, the database is opened in read-only mode. If the database does not exist, opening it will fail." }, { "textRaw": "`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`. **Default:** `true`.", "name": "enableForeignKeyConstraints", "type": "boolean", "default": "`true`", "desc": "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`." }, { "textRaw": "`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. **Default:** `false`.", "name": "enableDoubleQuotedStringLiterals", "type": "boolean", "default": "`false`", "desc": "If `true`, SQLite will accept double-quoted string literals. This is not recommended but can be enabled for compatibility with legacy database schemas." }, { "textRaw": "`allowExtension` {boolean} If `true`, the `loadExtension` SQL function and the `loadExtension()` method are enabled. You can call `enableLoadExtension(false)` later to disable this feature. **Default:** `false`.", "name": "allowExtension", "type": "boolean", "default": "`false`", "desc": "If `true`, the `loadExtension` SQL function and the `loadExtension()` method are enabled. You can call `enableLoadExtension(false)` later to disable this feature." }, { "textRaw": "`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. **Default:** `0`.", "name": "timeout", "type": "number", "default": "`0`", "desc": "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." }, { "textRaw": "`readBigInts` {boolean} If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, integer fields are read as JavaScript numbers. **Default:** `false`.", "name": "readBigInts", "type": "boolean", "default": "`false`", "desc": "If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, integer fields are read as JavaScript numbers." }, { "textRaw": "`returnArrays` {boolean} If `true`, query results are returned as arrays instead of objects. **Default:** `false`.", "name": "returnArrays", "type": "boolean", "default": "`false`", "desc": "If `true`, query results are returned as arrays instead of objects." }, { "textRaw": "`allowBareNamedParameters` {boolean} If `true`, allows binding named parameters without the prefix character (e.g., `foo` instead of `:foo`). **Default:** `true`.", "name": "allowBareNamedParameters", "type": "boolean", "default": "`true`", "desc": "If `true`, allows binding named parameters without the prefix character (e.g., `foo` instead of `:foo`)." }, { "textRaw": "`allowUnknownNamedParameters` {boolean} If `true`, unknown named parameters are ignored when binding. If `false`, an exception is thrown for unknown named parameters. **Default:** `false`.", "name": "allowUnknownNamedParameters", "type": "boolean", "default": "`false`", "desc": "If `true`, unknown named parameters are ignored when binding. If `false`, an exception is thrown for unknown named parameters." }, { "textRaw": "`defensive` {boolean} If `true`, 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 using `enableDefensive()`. **Default:** `true`.", "name": "defensive", "type": "boolean", "default": "`true`", "desc": "If `true`, 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 using `enableDefensive()`." }, { "textRaw": "`limits` {Object} Configuration for various SQLite limits. These limits can be used to prevent excessive resource consumption when handling potentially malicious input. See Run-Time Limits and Limit Constants in the SQLite documentation for details. Default values are determined by SQLite's compile-time defaults and may vary depending on how SQLite was built. The following properties are supported:", "name": "limits", "type": "Object", "desc": "Configuration for various SQLite limits. These limits can be used to prevent excessive resource consumption when handling potentially malicious input. See Run-Time Limits and Limit Constants in the SQLite documentation for details. Default values are determined by SQLite's compile-time defaults and may vary depending on how SQLite was built. The following properties are supported:", "options": [ { "textRaw": "`length` {number} Maximum length of a string or BLOB.", "name": "length", "type": "number", "desc": "Maximum length of a string or BLOB." }, { "textRaw": "`sqlLength` {number} Maximum length of an SQL statement.", "name": "sqlLength", "type": "number", "desc": "Maximum length of an SQL statement." }, { "textRaw": "`column` {number} Maximum number of columns.", "name": "column", "type": "number", "desc": "Maximum number of columns." }, { "textRaw": "`exprDepth` {number} Maximum depth of an expression tree.", "name": "exprDepth", "type": "number", "desc": "Maximum depth of an expression tree." }, { "textRaw": "`compoundSelect` {number} Maximum number of terms in a compound SELECT.", "name": "compoundSelect", "type": "number", "desc": "Maximum number of terms in a compound SELECT." }, { "textRaw": "`vdbeOp` {number} Maximum number of VDBE instructions.", "name": "vdbeOp", "type": "number", "desc": "Maximum number of VDBE instructions." }, { "textRaw": "`functionArg` {number} Maximum number of function arguments.", "name": "functionArg", "type": "number", "desc": "Maximum number of function arguments." }, { "textRaw": "`attach` {number} Maximum number of attached databases.", "name": "attach", "type": "number", "desc": "Maximum number of attached databases." }, { "textRaw": "`likePatternLength` {number} Maximum length of a LIKE pattern.", "name": "likePatternLength", "type": "number", "desc": "Maximum length of a LIKE pattern." }, { "textRaw": "`variableNumber` {number} Maximum number of SQL variables.", "name": "variableNumber", "type": "number", "desc": "Maximum number of SQL variables." }, { "textRaw": "`triggerDepth` {number} Maximum trigger recursion depth.", "name": "triggerDepth", "type": "number", "desc": "Maximum trigger recursion depth." } ] } ], "optional": true } ], "desc": "Constructs a new DatabaseSync instance.
Registers a new aggregate function with the SQLite database. This method is a wrapper around\nsqlite3_create_window_function().
When used as a window function, the result function will be called multiple times.
const { DatabaseSync } = require('node:sqlite');\n\nconst db = new DatabaseSync(':memory:');\ndb.exec(`\n CREATE TABLE t3(x, y);\n INSERT INTO t3 VALUES ('a', 4),\n ('b', 5),\n ('c', 3),\n ('d', 8),\n ('e', 1);\n`);\n\ndb.aggregate('sumint', {\n start: 0,\n step: (acc, value) => acc + value,\n});\n\ndb.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }\n\nimport { DatabaseSync } from 'node:sqlite';\n\nconst db = new DatabaseSync(':memory:');\ndb.exec(`\n CREATE TABLE t3(x, y);\n INSERT INTO t3 VALUES ('a', 4),\n ('b', 5),\n ('c', 3),\n ('d', 8),\n ('e', 1);\n`);\n\ndb.aggregate('sumint', {\n start: 0,\n step: (acc, value) => acc + value,\n});\n\ndb.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }\n"
},
{
"textRaw": "`database.close()`",
"name": "close",
"type": "method",
"meta": {
"added": [
"v22.5.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Closes the database connection. An exception is thrown if the database is not\nopen. This method is a wrapper around sqlite3_close_v2().
Loads a shared library into the database connection. This method is a wrapper\naround sqlite3_load_extension(). It is required to enable the\nallowExtension option when constructing the DatabaseSync instance.
Enables or disables the loadExtension SQL function, and the loadExtension()\nmethod. When allowExtension is false when constructing, you cannot enable\nloading extensions for security reasons.
Enables or disables the defensive flag. When the defensive flag is active,\nlanguage features that allow ordinary SQL to deliberately corrupt the database file are disabled.\nSee SQLITE_DBCONFIG_DEFENSIVE in the SQLite documentation for details.
This method is a wrapper around sqlite3_db_filename()
This method allows one or more SQL statements to be executed without returning\nany results. This method is useful when executing SQL statements read from a\nfile. This method is a wrapper around sqlite3_exec().
This method is used to create SQLite user-defined functions. This method is a\nwrapper around sqlite3_create_function_v2().
Sets an authorizer callback that SQLite will invoke whenever it attempts to\naccess data or modify the database schema through prepared statements.\nThis can be used to implement security policies, audit access, or restrict certain operations.\nThis method is a wrapper around sqlite3_set_authorizer().
When invoked, the callback receives five arguments:
\nactionCode <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:
\nSQLITE_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');\nconst db = new DatabaseSync(':memory:');\n\n// Set up an authorizer that denies all table creation\ndb.setAuthorizer((actionCode) => {\n if (actionCode === constants.SQLITE_CREATE_TABLE) {\n return constants.SQLITE_DENY;\n }\n return constants.SQLITE_OK;\n});\n\n// This will work\ndb.prepare('SELECT 1').get();\n\n// This will throw an error due to authorization denial\ntry {\n db.exec('CREATE TABLE blocked (id INTEGER)');\n} catch (err) {\n console.log('Operation blocked:', err.message);\n}\n\nimport { DatabaseSync, constants } from 'node:sqlite';\nconst db = new DatabaseSync(':memory:');\n\n// Set up an authorizer that denies all table creation\ndb.setAuthorizer((actionCode) => {\n if (actionCode === constants.SQLITE_CREATE_TABLE) {\n return constants.SQLITE_DENY;\n }\n return constants.SQLITE_OK;\n});\n\n// This will work\ndb.prepare('SELECT 1').get();\n\n// This will throw an error due to authorization denial\ntry {\n db.exec('CREATE TABLE blocked (id INTEGER)');\n} catch (err) {\n console.log('Operation blocked:', err.message);\n}\n"
},
{
"textRaw": "`database.open()`",
"name": "open",
"type": "method",
"meta": {
"added": [
"v22.5.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Opens the database specified in the path argument of the DatabaseSync\nconstructor. This method should only be used when the database is not opened via\nthe constructor. An exception is thrown if the database is already open.
Compiles a SQL statement into a prepared statement. This method is a wrapper\naround sqlite3_prepare_v2().
Creates a new SQLTagStore, which is a Least Recently Used (LRU) cache\nfor storing prepared statements. This allows for the efficient reuse of\nprepared statements by tagging them with a unique identifier.
When a tagged SQL literal is executed, the SQLTagStore checks if a prepared\nstatement for the corresponding SQL query string already exists in the cache.\nIf it does, the cached statement is used. If not, a new prepared statement is\ncreated, executed, and then stored in the cache for future use. This mechanism\nhelps to avoid the overhead of repeatedly parsing and preparing the same SQL\nstatements.
Tagged statements bind the placeholder values from the template literal as\nparameters to the underlying prepared statement. For example:
\nsqlTagStore.get`SELECT ${value}`;\n\nis equivalent to:
\ndb.prepare('SELECT ?').get(value);\n\nHowever, in the first example, the tag store will cache the underlying prepared\nstatement for future use.
\n\n\nNote: The
\n${value}syntax in tagged statements binds a parameter to\nthe prepared statement. This differs from its behavior in untagged template\nliterals, where it performs string interpolation.\n// This a safe example of binding a parameter to a tagged statement.\nsqlTagStore.run`INSERT INTO t1 (id) VALUES (${id})`;\n\n// This is an *unsafe* example of an untagged template string.\n// `id` is interpolated into the query text as a string.\n// This can lead to SQL injection and data corruption.\ndb.run(`INSERT INTO t1 (id) VALUES (${id})`);\n
The tag store will match a statement from the cache if the query strings\n(including the positions of any bound placeholders) are identical.
\n// The following statements will match in the cache:\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${12345} AND active = 1`;\n\n// The following statements will not match, as the query strings\n// and bound placeholders differ:\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;\nsqlTagStore.get`SELECT * FROM t1 WHERE id = 12345 AND active = 1`;\n\n// The following statements will not match, as matches are case-sensitive:\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;\nsqlTagStore.get`select * from t1 where id = ${id} and active = 1`;\n\nThe only way of binding parameters in tagged statements is with the ${value}\nsyntax. Do not add parameter binding placeholders (? etc.) to the SQL query\nstring itself.
import { DatabaseSync } from 'node:sqlite';\n\nconst db = new DatabaseSync(':memory:');\nconst sql = db.createTagStore();\n\ndb.exec('CREATE TABLE users (id INT, name TEXT)');\n\n// Using the 'run' method to insert data.\n// The tagged literal is used to identify the prepared statement.\nsql.run`INSERT INTO users VALUES (1, 'Alice')`;\nsql.run`INSERT INTO users VALUES (2, 'Bob')`;\n\n// Using the 'get' method to retrieve a single row.\nconst name = 'Alice';\nconst user = sql.get`SELECT * FROM users WHERE name = ${name}`;\nconsole.log(user); // { id: 1, name: 'Alice' }\n\n// Using the 'all' method to retrieve all rows.\nconst allUsers = sql.all`SELECT * FROM users ORDER BY id`;\nconsole.log(allUsers);\n// [\n// { id: 1, name: 'Alice' },\n// { id: 2, name: 'Bob' }\n// ]\n\nconst { DatabaseSync } = require('node:sqlite');\n\nconst db = new DatabaseSync(':memory:');\nconst sql = db.createTagStore();\n\ndb.exec('CREATE TABLE users (id INT, name TEXT)');\n\n// Using the 'run' method to insert data.\n// The tagged literal is used to identify the prepared statement.\nsql.run`INSERT INTO users VALUES (1, 'Alice')`;\nsql.run`INSERT INTO users VALUES (2, 'Bob')`;\n\n// Using the 'get' method to retrieve a single row.\nconst name = 'Alice';\nconst user = sql.get`SELECT * FROM users WHERE name = ${name}`;\nconsole.log(user); // { id: 1, name: 'Alice' }\n\n// Using the 'all' method to retrieve all rows.\nconst allUsers = sql.all`SELECT * FROM users ORDER BY id`;\nconsole.log(allUsers);\n// [\n// { id: 1, name: 'Alice' },\n// { id: 2, name: 'Bob' }\n// ]\n"
},
{
"textRaw": "`database.createSession([options])`",
"name": "createSession",
"type": "method",
"meta": {
"added": [
"v23.3.0",
"v22.12.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} The configuration options for the session.",
"name": "options",
"type": "Object",
"desc": "The configuration options for the session.",
"options": [
{
"textRaw": "`table` {string} A specific table to track changes for. By default, changes to all tables are tracked.",
"name": "table",
"type": "string",
"desc": "A specific table to track changes for. By default, changes to all tables are tracked."
},
{
"textRaw": "`db` {string} Name of the database to track. This is useful when multiple databases have been added using `ATTACH DATABASE`. **Default**: `'main'`.",
"name": "db",
"type": "string",
"desc": "Name of the database to track. This is useful when multiple databases have been added using `ATTACH DATABASE`. **Default**: `'main'`."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Session} A session handle.",
"name": "return",
"type": "Session",
"desc": "A session handle."
}
}
],
"desc": "Creates and attaches a session to the database. This method is a wrapper around sqlite3session_create() and sqlite3session_attach().
An exception is thrown if the database is not\nopen. This method is a wrapper around sqlite3changeset_apply().
import { DatabaseSync } from 'node:sqlite';\n\nconst sourceDb = new DatabaseSync(':memory:');\nconst targetDb = new DatabaseSync(':memory:');\n\nsourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\ntargetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\n\nconst session = sourceDb.createSession();\n\nconst insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n\nconst changeset = session.changeset();\ntargetDb.applyChangeset(changeset);\n// Now that the changeset has been applied, targetDb contains the same data as sourceDb.\n\nconst { DatabaseSync } = require('node:sqlite');\n\nconst sourceDb = new DatabaseSync(':memory:');\nconst targetDb = new DatabaseSync(':memory:');\n\nsourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\ntargetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\n\nconst session = sourceDb.createSession();\n\nconst insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n\nconst changeset = session.changeset();\ntargetDb.applyChangeset(changeset);\n// Now that the changeset has been applied, targetDb contains the same data as sourceDb.\n"
},
{
"textRaw": "`database[Symbol.dispose]()`",
"name": "[Symbol.dispose]",
"type": "method",
"meta": {
"added": [
"v23.11.0",
"v22.15.0"
],
"changes": [
{
"version": "v24.2.0",
"pr-url": "https://github.com/nodejs/node/pull/58467",
"description": "No longer experimental."
}
]
},
"signatures": [
{
"params": []
}
],
"desc": "Closes the database connection. If the database connection is already closed\nthen this is a no-op.
" } ], "properties": [ { "textRaw": "Type: {boolean} Whether the database is currently open or not.", "name": "isOpen", "type": "boolean", "meta": { "added": [ "v23.11.0", "v22.15.0" ], "changes": [] }, "desc": "Whether the database is currently open or not." }, { "textRaw": "Type: {boolean} Whether the database is currently within a transaction. This method is a wrapper around `sqlite3_get_autocommit()`.", "name": "isTransaction", "type": "boolean", "meta": { "added": [ "v24.0.0", "v22.16.0" ], "changes": [] }, "desc": "Whether the database is currently within a transaction. This method is a wrapper around `sqlite3_get_autocommit()`." }, { "textRaw": "Type: {Object}", "name": "limits", "type": "Object", "meta": { "added": [ "v25.8.0" ], "changes": [] }, "desc": "An object for getting and setting SQLite database limits at runtime.\nEach property corresponds to an SQLite limit and can be read or written.
\nconst db = new DatabaseSync(':memory:');\n\n// Read current limit\nconsole.log(db.limits.length);\n\n// Set a new limit\ndb.limits.sqlLength = 100000;\n\n// Reset a limit to its compile-time maximum\ndb.limits.sqlLength = Infinity;\n\nAvailable properties: length, sqlLength, column, exprDepth,\ncompoundSelect, vdbeOp, functionArg, attach, likePatternLength,\nvariableNumber, triggerDepth.
Setting a property to Infinity resets the limit to its compile-time maximum value.
Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times.\nAn exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_changeset().
Similar to the method above, but generates a more compact patchset. See Changesets and Patchsets\nin the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a\nwrapper around sqlite3session_patchset().
Closes the session. An exception is thrown if the database or the session is not open. This method is a\nwrapper around sqlite3session_delete().
Closes the session. If the session is already closed, does nothing.
" } ] }, { "textRaw": "Class: `StatementSync`", "name": "StatementSync", "type": "class", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "desc": "This class represents a single prepared statement. This class cannot be\ninstantiated via its constructor. Instead, instances are created via the\ndatabase.prepare() method. All APIs exposed by this class execute\nsynchronously.
A prepared statement is an efficient binary representation of the SQL used to\ncreate it. Prepared statements are parameterizable, and can be invoked multiple\ntimes with different bound values. Parameters also offer protection against\nSQL injection attacks. For these reasons, prepared statements are preferred\nover hand-crafted SQL strings when handling user input.
", "methods": [ { "textRaw": "`statement.all([namedParameters][, ...anonymousParameters])`", "name": "all", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": [ "v23.7.0", "v22.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/56385", "description": "Add support for `DataView` and typed array objects for `anonymousParameters`." } ] }, "signatures": [ { "params": [ { "textRaw": "`namedParameters` {Object} An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "name": "namedParameters", "type": "Object", "desc": "An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "optional": true }, { "textRaw": "`...anonymousParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Zero or more values to bind to anonymous parameters.", "name": "...anonymousParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Zero or more values to bind to anonymous parameters.", "optional": true } ], "return": { "textRaw": "Returns: {Array} 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.", "name": "return", "type": "Array", "desc": "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." } } ], "desc": "This method executes a prepared statement and returns all results as an array of\nobjects. If the prepared statement does not return any results, this method\nreturns an empty array. The prepared statement parameters are bound using\nthe values in namedParameters and anonymousParameters.
This method is used to retrieve information about the columns returned by the\nprepared statement.
" }, { "textRaw": "`statement.get([namedParameters][, ...anonymousParameters])`", "name": "get", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": [ "v23.7.0", "v22.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/56385", "description": "Add support for `DataView` and typed array objects for `anonymousParameters`." } ] }, "signatures": [ { "params": [ { "textRaw": "`namedParameters` {Object} An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "name": "namedParameters", "type": "Object", "desc": "An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "optional": true }, { "textRaw": "`...anonymousParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Zero or more values to bind to anonymous parameters.", "name": "...anonymousParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Zero or more values to bind to anonymous parameters.", "optional": true } ], "return": { "textRaw": "Returns: {Object|undefined} 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`.", "name": "return", "type": "Object|undefined", "desc": "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`." } } ], "desc": "This method executes a prepared statement and returns the first result as an\nobject. If the prepared statement does not return any results, this method\nreturns undefined. The prepared statement parameters are bound using the\nvalues in namedParameters and anonymousParameters.
This method executes a prepared statement and returns an iterator of\nobjects. If the prepared statement does not return any results, this method\nreturns an empty iterator. The prepared statement parameters are bound using\nthe values in namedParameters and anonymousParameters.
This method executes a prepared statement and returns an object summarizing the\nresulting changes. The prepared statement parameters are bound using the\nvalues in namedParameters and anonymousParameters.
The names of SQLite parameters begin with a prefix character. By default,\nnode:sqlite requires that this prefix character is present when binding\nparameters. However, with the exception of dollar sign character, these\nprefix characters also require extra quoting when used in object keys.
To improve ergonomics, this method can be used to also allow bare named\nparameters, which do not require the prefix character in JavaScript code. There\nare several caveats to be aware of when enabling bare named parameters:
\n$k and @k, in the same prepared\nstatement will result in an exception as it cannot be determined how to bind\na bare name.By default, if an unknown name is encountered while binding parameters, an\nexception is thrown. This method allows unknown named parameters to be ignored.
" }, { "textRaw": "`statement.setReturnArrays(enabled)`", "name": "setReturnArrays", "type": "method", "meta": { "added": [ "v24.0.0", "v22.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`enabled` {boolean} Enables or disables the return of query results as arrays.", "name": "enabled", "type": "boolean", "desc": "Enables or disables the return of query results as arrays." } ] } ], "desc": "When enabled, query results returned by the all(), get(), and iterate() methods will be returned as arrays instead\nof objects.
When reading from the database, SQLite INTEGERs are mapped to JavaScript\nnumbers by default. However, SQLite INTEGERs can store values larger than\nJavaScript numbers are capable of representing. In such cases, this method can\nbe used to read INTEGER data using JavaScript BigInts. This method has no\nimpact on database write operations where numbers and BigInts are both\nsupported at all times.
The source SQL text of the prepared statement with parameter\nplaceholders replaced by the values that were used during the most recent\nexecution of this prepared statement. This property is a wrapper around\nsqlite3_expanded_sql().
The source SQL text of the prepared statement. This property is a\nwrapper around sqlite3_sql().
This class represents a single LRU (Least Recently Used) cache for storing\nprepared statements.
\nInstances of this class are created via the database.createTagStore()\nmethod, not by using a constructor. The store caches prepared statements based\non the provided SQL query string. When the same query is seen again, the store\nretrieves the cached statement and safely applies the new values through\nparameter binding, thereby preventing attacks like SQL injection.
The cache has a maxSize that defaults to 1000 statements, but a custom size can\nbe provided (e.g., database.createTagStore(100)). All APIs exposed by this\nclass execute synchronously.
Executes the given SQL query and returns all resulting rows as an array of\nobjects.
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.get(stringElements[, ...boundParameters])`", "name": "get", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stringElements` {string[]} Template literal elements containing the SQL query.", "name": "stringElements", "type": "string[]", "desc": "Template literal elements containing the SQL query." }, { "textRaw": "`...boundParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Parameter values to be bound to placeholders in the template string.", "optional": true } ], "return": { "textRaw": "Returns: {Object|undefined} An object representing the first row returned by the query, or `undefined` if no rows are returned.", "name": "return", "type": "Object|undefined", "desc": "An object representing the first row returned by the query, or `undefined` if no rows are returned." } } ], "desc": "Executes the given SQL query and returns the first resulting row as an object.
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.iterate(stringElements[, ...boundParameters])`", "name": "iterate", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stringElements` {string[]} Template literal elements containing the SQL query.", "name": "stringElements", "type": "string[]", "desc": "Template literal elements containing the SQL query." }, { "textRaw": "`...boundParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Parameter values to be bound to placeholders in the template string.", "optional": true } ], "return": { "textRaw": "Returns: {Iterator} An iterator that yields objects representing the rows returned by the query.", "name": "return", "type": "Iterator", "desc": "An iterator that yields objects representing the rows returned by the query." } } ], "desc": "Executes the given SQL query and returns an iterator over the resulting rows.
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.run(stringElements[, ...boundParameters])`", "name": "run", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stringElements` {string[]} Template literal elements containing the SQL query.", "name": "stringElements", "type": "string[]", "desc": "Template literal elements containing the SQL query." }, { "textRaw": "`...boundParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Parameter values to be bound to placeholders in the template string.", "optional": true } ], "return": { "textRaw": "Returns: {Object} An object containing information about the execution, including `changes` and `lastInsertRowid`.", "name": "return", "type": "Object", "desc": "An object containing information about the execution, including `changes` and `lastInsertRowid`." } } ], "desc": "Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE).
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.clear()`", "name": "clear", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Resets the LRU cache, clearing all stored prepared statements.
" } ], "properties": [ { "textRaw": "Type: {integer}", "name": "size", "type": "integer", "meta": { "added": [ "v24.9.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/60246", "description": "Changed from a method to a getter." } ] }, "desc": "A read-only property that returns the number of prepared statements currently in the cache.
" }, { "textRaw": "Type: {integer}", "name": "capacity", "type": "integer", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "desc": "A read-only property that returns the maximum number of prepared statements the cache can hold.
" }, { "textRaw": "Type: {DatabaseSync}", "name": "db", "type": "DatabaseSync", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "desc": "A read-only property that returns the DatabaseSync object associated with this SQLTagStore.
When Node.js writes to or reads from SQLite, it is necessary to convert between\nJavaScript data types and SQLite's data types. Because JavaScript supports\nmore data types than SQLite, only a subset of JavaScript types are supported.\nAttempting to write an unsupported data type to SQLite will result in an\nexception.
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n| Storage class | JavaScript to SQLite | SQLite to JavaScript |
|---|---|---|
NULL | <null> | <null> |
INTEGER | <number> or <bigint> | <number> or <bigint> (configurable) |
REAL | <number> | <number> |
TEXT | <string> | <string> |
BLOB | <TypedArray> or <DataView> | <Uint8Array> |
APIs that read values from SQLite have a configuration option that determines\nwhether INTEGER values are converted to number or bigint in JavaScript,\nsuch as the readBigInts option for statements and the useBigIntArguments\noption for user-defined functions. If Node.js reads an INTEGER value from\nSQLite that is outside the JavaScript safe integer range, and the option to\nread BigInts is not enabled, then an ERR_OUT_OF_RANGE error will be thrown.
This method makes a database backup. This method abstracts the sqlite3_backup_init(), sqlite3_backup_step()\nand sqlite3_backup_finish() functions.
The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same\n<DatabaseSync> - object will be reflected in the backup right away. However, mutations from other connections will cause\nthe backup process to restart.
const { backup, DatabaseSync } = require('node:sqlite');\n\n(async () => {\n const sourceDb = new DatabaseSync('source.db');\n const totalPagesTransferred = await backup(sourceDb, 'backup.db', {\n rate: 1, // Copy one page at a time.\n progress: ({ totalPages, remainingPages }) => {\n console.log('Backup in progress', { totalPages, remainingPages });\n },\n });\n\n console.log('Backup completed', totalPagesTransferred);\n})();\n\nimport { backup, DatabaseSync } from 'node:sqlite';\n\nconst sourceDb = new DatabaseSync('source.db');\nconst totalPagesTransferred = await backup(sourceDb, 'backup.db', {\n rate: 1, // Copy one page at a time.\n progress: ({ totalPages, remainingPages }) => {\n console.log('Backup in progress', { totalPages, remainingPages });\n },\n});\n\nconsole.log('Backup completed', totalPagesTransferred);\n"
}
],
"properties": [
{
"textRaw": "Type: {Object}",
"name": "constants",
"type": "Object",
"meta": {
"added": [
"v23.5.0",
"v22.13.0"
],
"changes": []
},
"desc": "An object containing commonly used constants for SQLite operations.
", "modules": [ { "textRaw": "SQLite constants", "name": "sqlite_constants", "type": "module", "desc": "The following constants are exported by the sqlite.constants object.
One of the following constants is available as an argument to the onConflict\nconflict resolution handler passed to database.applyChangeset(). See also\nConstants Passed To The Conflict Handler in the SQLite documentation.
| Constant | Description |
|---|---|
SQLITE_CHANGESET_DATA | 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. |
SQLITE_CHANGESET_NOTFOUND | 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. |
SQLITE_CHANGESET_CONFLICT | This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. |
SQLITE_CHANGESET_CONSTRAINT | 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. |
SQLITE_CHANGESET_FOREIGN_KEY | If 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 the onConflict conflict\nresolution handler passed to database.applyChangeset(). See also\nConstants Returned From The Conflict Handler in the SQLite documentation.
| Constant | Description |
|---|---|
SQLITE_CHANGESET_OMIT | Conflicting changes are omitted. |
SQLITE_CHANGESET_REPLACE | 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. |
SQLITE_CHANGESET_ABORT | Abort when a change encounters a conflict and roll back database. |
The following constants are used with the database.setAuthorizer() method.
One of the following constants must be returned from the authorizer callback\nfunction passed to database.setAuthorizer().
| Constant | Description |
|---|---|
SQLITE_OK | Allow the operation to proceed normally. |
SQLITE_DENY | Deny the operation and cause an error to be returned. |
SQLITE_IGNORE | Ignore the operation and continue as if it had never been requested. |
The following constants are passed as the first argument to the authorizer\ncallback function to indicate what type of operation is being authorized.
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n| Constant | Description |
|---|---|
SQLITE_CREATE_INDEX | Create an index |
SQLITE_CREATE_TABLE | Create a table |
SQLITE_CREATE_TEMP_INDEX | Create a temporary index |
SQLITE_CREATE_TEMP_TABLE | Create a temporary table |
SQLITE_CREATE_TEMP_TRIGGER | Create a temporary trigger |
SQLITE_CREATE_TEMP_VIEW | Create a temporary view |
SQLITE_CREATE_TRIGGER | Create a trigger |
SQLITE_CREATE_VIEW | Create a view |
SQLITE_DELETE | Delete from a table |
SQLITE_DROP_INDEX | Drop an index |
SQLITE_DROP_TABLE | Drop a table |
SQLITE_DROP_TEMP_INDEX | Drop a temporary index |
SQLITE_DROP_TEMP_TABLE | Drop a temporary table |
SQLITE_DROP_TEMP_TRIGGER | Drop a temporary trigger |
SQLITE_DROP_TEMP_VIEW | Drop a temporary view |
SQLITE_DROP_TRIGGER | Drop a trigger |
SQLITE_DROP_VIEW | Drop a view |
SQLITE_INSERT | Insert into a table |
SQLITE_PRAGMA | Execute a PRAGMA statement |
SQLITE_READ | Read from a table |
SQLITE_SELECT | Execute a SELECT statement |
SQLITE_TRANSACTION | Begin, commit, or rollback a transaction |
SQLITE_UPDATE | Update a table |
SQLITE_ATTACH | Attach a database |
SQLITE_DETACH | Detach a database |
SQLITE_ALTER_TABLE | Alter a table |
SQLITE_REINDEX | Reindex |
SQLITE_ANALYZE | Analyze the database |
SQLITE_CREATE_VTABLE | Create a virtual table |
SQLITE_DROP_VTABLE | Drop a virtual table |
SQLITE_FUNCTION | Use a function |
SQLITE_SAVEPOINT | Create, release, or rollback a savepoint |
SQLITE_COPY | Copy data (legacy) |
SQLITE_RECURSIVE | Recursive query |