{ "type": "module", "source": "doc/api/sqlite.md", "modules": [ { "textRaw": "SQLite", "name": "sqlite", "introduced_in": "v22.5.0", "type": "module", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/61262", "description": "SQLite is now a release candidate." }, { "version": [ "v23.4.0", "v22.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/55890", "description": "SQLite is no longer behind `--experimental-sqlite` but still experimental." } ] }, "stability": 1.2, "stabilityText": "Release candidate.", "desc": "
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. SQL trace events can\nbe observed via the diagnostics_channel module. See\n'sqlite.db.query' for details.
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// Finalize the prepared statement once it is no longer needed.\ninsert.close();\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' } ]\nquery.close();\n\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// Finalize the prepared statement once it is no longer needed.\ninsert.close();\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' } ]\nquery.close();\n",
"modules": [
{
"textRaw": "Type conversion between JavaScript and SQLite",
"name": "type_conversion_between_javascript_and_sqlite",
"type": "module",
"desc": "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| Storage class | \nJavaScript to SQLite | \nSQLite to JavaScript | \n
|---|---|---|
NULL | \nnull | \nnull | \n
INTEGER | \nnumber, bigint, or boolean | \nnumber or bigint (configurable) | \n
REAL | \nnumber | \nnumber | \n
TEXT | \nstring | \nstring | \n
BLOB | \nTypedArray, DataView, ArrayBuffer, or SharedArrayBuffer | \nUint8Array | \n
Booleans are written as the INTEGER values 1 and 0. Like any other\nINTEGER value, they are read back as number by default, or as bigint\nvalues (1n and 0n) when reading BigInts is enabled. Writing a bigint that\ndoes not fit in a signed 64-bit integer throws an ERR_INVALID_ARG_VALUE\nerror.
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 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", "v24.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/61266", "description": "Enable `defensive` by default." }, { "version": [ "v25.1.0", "v24.12.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\nusing query = db.prepare('SELECT sumint(y) as total FROM t3');\nquery.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\nusing query = db.prepare('SELECT sumint(y) as total FROM t3');\nquery.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. An ERR_INVALID_STATE error is thrown if the method is called while\na statement is executing, such as inside a user-defined function, an aggregate\nfunction, an authorizer callback, or a 'sqlite.db.query' subscriber. This\nmethod 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.
import { DatabaseSync } from 'node:sqlite';\nconst database = new DatabaseSync(':memory:', { allowExtension: true });\n\n// Load using the entry point derived from the filename.\ndatabase.loadExtension('./decimal.dylib');\n\n// Override the entry point when the derived name does not match.\ndatabase.loadExtension('./base64.dylib', 'sqlite3_base64_init');\n\nconst { DatabaseSync } = require('node:sqlite');\nconst database = new DatabaseSync(':memory:', { allowExtension: true });\n\n// Load using the entry point derived from the filename.\ndatabase.loadExtension('./decimal.dylib');\n\n// Override the entry point when the derived name does not match.\ndatabase.loadExtension('./base64.dylib', 'sqlite3_base64_init');\n"
},
{
"textRaw": "`database.enableLoadExtension(allow)`",
"name": "enableLoadExtension",
"type": "method",
"meta": {
"added": [
"v23.5.0",
"v22.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`allow` {boolean} Whether to allow loading extensions.",
"name": "allow",
"type": "boolean",
"desc": "Whether to allow loading extensions."
}
]
}
],
"desc": "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.,\nSQLITE_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).SQLite requires that the authorizer callback not modify the database connection\nthat invoked it, which includes preparing and stepping statements. Methods that\nwould do so throw an error with code ERR_INVALID_STATE while the callback is\non the stack, including database.prepare(), database.exec(), the execution\nmethods of that connection's statements, iterators, and tag stores, and\ndatabase.setAuthorizer() itself. Other connections remain usable.
The callback can also be invoked from within statement.run(),\nstatement.get(), and similar methods, because SQLite may re-prepare a\nstatement during execution after a schema change.
Separately, a statement that is currently being executed cannot be reentered.\nCalling statement.close() on it would free the virtual machine that is\nrunning, and re-running it through statement.run(), statement.get(),\nstatement.all(), statement.iterate(), iterator.next(),\niterator.return(), or the equivalent tag store methods would reset that\nvirtual machine mid-execution. All of these throw an ERR_INVALID_STATE error\ninstead. This applies to any callback SQLite invokes during execution, such as a\nuser-defined function. Other statements on the connection remain usable.
Operations that touch no SQLite state stay available from the callback:\nsqlTagStore.clear(), which only drops cached statements, and next() and\nreturn() on an already-drained iterator, which keep returning\n{ done: true }.
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\nusing query = db.prepare('SELECT 1');\nquery.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\nusing query = db.prepare('SELECT 1');\nquery.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.
Serializes the database into a binary representation, returned as a\nUint8Array. This is useful for saving, cloning, or transferring an in-memory\ndatabase. This method is a wrapper around sqlite3_serialize().
import { DatabaseSync } from 'node:sqlite';\n\nconst db = new DatabaseSync(':memory:');\ndb.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');\ndb.exec(\"INSERT INTO t VALUES (1, 'hello')\");\nconst buffer = db.serialize();\nconsole.log(buffer.length); // Prints the byte length of the database\n\nconst { DatabaseSync } = require('node:sqlite');\n\nconst db = new DatabaseSync(':memory:');\ndb.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');\ndb.exec(\"INSERT INTO t VALUES (1, 'hello')\");\nconst buffer = db.serialize();\nconsole.log(buffer.length); // Prints the byte length of the database\n"
},
{
"textRaw": "`database.deserialize(buffer[, options])`",
"name": "deserialize",
"type": "method",
"meta": {
"added": [
"v26.1.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`buffer` {Uint8Array} A binary representation of a database, such as the output of `database.serialize()`.",
"name": "buffer",
"type": "Uint8Array",
"desc": "A binary representation of a database, such as the output of `database.serialize()`."
},
{
"textRaw": "`options` {Object} Optional configuration for the deserialization.",
"name": "options",
"type": "Object",
"desc": "Optional configuration for the deserialization.",
"options": [
{
"textRaw": "`dbName` {string} Name of the database to deserialize into. **Default:** `'main'`.",
"name": "dbName",
"type": "string",
"default": "`'main'`",
"desc": "Name of the database to deserialize into."
}
],
"optional": true
}
]
}
],
"desc": "Loads a serialized database into this connection, replacing the current\ndatabase. The deserialized database is writable. Existing prepared statements\nare finalized before deserialization is attempted, even if the operation\nsubsequently fails. An ERR_INVALID_STATE error is thrown if the method is\ncalled while a database callback is on the stack, for example a user-defined\nfunction, an aggregate function, an authorizer, or a changeset filter or conflict\nhandler. This method is a wrapper around sqlite3_deserialize().
import { DatabaseSync } from 'node:sqlite';\n\nconst original = new DatabaseSync(':memory:');\noriginal.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');\noriginal.exec(\"INSERT INTO t VALUES (1, 'hello')\");\nconst buffer = original.serialize();\noriginal.close();\n\nconst clone = new DatabaseSync(':memory:');\nclone.deserialize(buffer);\nusing query = clone.prepare('SELECT value FROM t');\nconsole.log(query.get());\n// Prints: { value: 'hello' }\n\nconst { DatabaseSync } = require('node:sqlite');\n\nconst original = new DatabaseSync(':memory:');\noriginal.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');\noriginal.exec(\"INSERT INTO t VALUES (1, 'hello')\");\nconst buffer = original.serialize();\noriginal.close();\n\nconst clone = new DatabaseSync(':memory:');\nclone.deserialize(buffer);\nusing query = clone.prepare('SELECT value FROM t');\nconsole.log(query.get());\n// Prints: { value: 'hello' }\n"
},
{
"textRaw": "`database.prepare(sql[, options])`",
"name": "prepare",
"type": "method",
"meta": {
"added": [
"v22.5.0"
],
"changes": [
{
"version": "v26.8.0",
"pr-url": "https://github.com/nodejs/node/pull/62757",
"description": "Add the `persistent` option."
},
{
"version": "v26.8.0",
"pr-url": "https://github.com/nodejs/node/pull/65157",
"description": "Throw `ERR_INVALID_ARG_VALUE` if `sql` contains no statements."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`sql` {string} A SQL string to compile to a prepared statement.",
"name": "sql",
"type": "string",
"desc": "A SQL string to compile to a prepared statement."
},
{
"textRaw": "`options` {Object} Optional configuration for the prepared statement.",
"name": "options",
"type": "Object",
"desc": "Optional configuration for the prepared statement.",
"options": [
{
"textRaw": "`readBigInts` {boolean} If `true`, integer fields are read as `BigInt`s. **Default:** inherited from database options or `false`.",
"name": "readBigInts",
"type": "boolean",
"default": "inherited from database options or `false`",
"desc": "If `true`, integer fields are read as `BigInt`s."
},
{
"textRaw": "`returnArrays` {boolean} If `true`, results are returned as arrays. **Default:** inherited from database options or `false`.",
"name": "returnArrays",
"type": "boolean",
"default": "inherited from database options or `false`",
"desc": "If `true`, results are returned as arrays."
},
{
"textRaw": "`allowBareNamedParameters` {boolean} If `true`, allows binding named parameters without the prefix character. **Default:** inherited from database options or `true`.",
"name": "allowBareNamedParameters",
"type": "boolean",
"default": "inherited from database options or `true`",
"desc": "If `true`, allows binding named parameters without the prefix character."
},
{
"textRaw": "`allowUnknownNamedParameters` {boolean} If `true`, unknown named parameters are ignored. **Default:** inherited from database options or `false`.",
"name": "allowUnknownNamedParameters",
"type": "boolean",
"default": "inherited from database options or `false`",
"desc": "If `true`, unknown named parameters are ignored."
},
{
"textRaw": "`persistent` {boolean} If `true`, hints to SQLite that this statement will be retained for a long time and likely reused many times. SQLite currently responds to this hint by avoiding lookaside memory. Corresponds to the `SQLITE_PREPARE_PERSISTENT` flag. **Default:** `false`.",
"name": "persistent",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, hints to SQLite that this statement will be retained for a long time and likely reused many times. SQLite currently responds to this hint by avoiding lookaside memory. Corresponds to the `SQLITE_PREPARE_PERSISTENT` flag."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {StatementSync} The prepared statement.",
"name": "return",
"type": "StatementSync",
"desc": "The prepared statement."
}
}
],
"desc": "Compiles a SQL statement into a prepared statement. This method is a wrapper\naround sqlite3_prepare_v3().
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:
\nusing statement = db.prepare('SELECT ?');\nstatement.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\nusing 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\nusing 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,\nor if the session is currently generating a changeset or patchset. 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.
", "modules": [ { "textRaw": "Binding parameters", "name": "binding_parameters", "type": "module", "desc": "The all(), get(), iterate(), and run() methods bind their arguments to\nthe parameters of the prepared statement before executing it. Parameters are\neither anonymous or named.
Anonymous parameters are written as ? in SQL and are bound in order from the\narguments passed to the method. The ?NNN form assigns SQLite parameter index\nNNN to a placeholder. Avoid mixing numbered and named parameters because they\nshare parameter indexes.
db.prepare('SELECT ? AS a, ? AS b').get('x', 42);\n// { a: 'x', b: 42 }\ndb.prepare('SELECT ?2 AS a, ?1 AS b').get('first', 'second');\n// { a: 'second', b: 'first' }\n\nNamed parameters begin with one of the prefix characters $, :, or @ in\nSQL. They are bound from an object passed as the first argument. Repeating a\nname in the SQL binds the same value to every occurrence.
db.prepare('SELECT $a AS a, $b AS b').get({ $a: 1, $b: 2 });\n// { a: 1, b: 2 }\ndb.prepare('SELECT :a AS a').get({ ':a': 1 });\n// { a: 1 }\ndb.prepare('SELECT @a AS a').get({ '@a': 1 });\n// { a: 1 }\ndb.prepare('SELECT $k AS a, $k AS b').get({ k: 7 });\n// { a: 7, b: 7 }\n\nThe last example omits the prefix character from the object key. Bare names are\nallowed by default; see statement.setAllowBareNamedParameters() for their\ncaveats.
Binding a key that does not name a parameter of the statement throws an\nERR_INVALID_STATE error unless unknown named parameters are ignored. See\nstatement.setAllowUnknownNamedParameters().
See Type conversion between JavaScript and SQLite for the values that can be\nbound. Binding any other value throws an ERR_INVALID_ARG_TYPE error.
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. See\nBinding parameters.
Finalizes the prepared statement. An exception is thrown if the statement is\nalready finalized. An ERR_INVALID_STATE error is thrown if this statement\nis currently executing, which happens when the method is called from a callback\nthat the statement itself triggered, such as a user-defined function, an\naggregate function, or a 'sqlite.db.query' subscriber. Idle statements\non the same connection can be finalized from such a callback. This method is a\nwrapper around sqlite3_finalize().
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": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62001", "description": "Add support for boolean values in bound parameters." }, { "version": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62061", "description": "Add support for `ArrayBuffer` and `SharedArrayBuffer` objects in bound parameters." }, { "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 | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer} Zero or more values to bind to anonymous parameters.", "name": "...anonymousParameters", "type": "null | number | bigint | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer", "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. See\nBinding parameters.
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. See\nBinding parameters.
Resets every counter reported by statement.stat() back to zero, except\nmemused, which reports current memory usage and cannot be reset. This\nmethod is a wrapper around sqlite3_stmt_status() and is useful for\nmeasuring a specific workload without the counts accumulated by earlier\nexecutions of the same prepared statement.
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. See\nBinding parameters.
The names of SQLite parameters begin with a prefix character. However, with the\nexception of the dollar sign character, these prefix characters also require\nextra quoting when used in object keys.
\nTo improve ergonomics, node:sqlite allows bare named parameters, which do not\nrequire the prefix character in JavaScript code, by default. This method can be\nused to disable that behavior, requiring the prefix character when binding.\nThere are several caveats to be aware of when bare named parameters are\nallowed:
$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.
Finalizes the prepared statement. If the prepared statement is already\nfinalized, then this is a no-op. An ERR_INVALID_STATE error is thrown if\nthis statement is currently executing, under the same conditions as\nstatement.close().
Returns one of the runtime counters that SQLite tracks for this prepared\nstatement. This method is a wrapper around sqlite3_stmt_status() and does\nnot reset the counter. Asserting that a statement does not perform a full table\nscan (statement.stat('fullscanStep') === 0) is a useful check to guard\nagainst degenerate performance.
The 'filterMiss' and 'filterHit' counters require SQLite 3.38.0 or later.\nBuilds linked against an older SQLite with --shared-sqlite do not expose them,\nand passing either name throws ERR_INVALID_ARG_VALUE.
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": [ { "version": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62001", "description": "Add support for boolean values in bound parameters." }, { "version": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62061", "description": "Add support for `ArrayBuffer` and `SharedArrayBuffer` objects in bound parameters." } ] }, "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 | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null | number | bigint | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer", "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": [ { "version": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62001", "description": "Add support for boolean values in bound parameters." }, { "version": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62061", "description": "Add support for `ArrayBuffer` and `SharedArrayBuffer` objects in bound parameters." } ] }, "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 | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null | number | bigint | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer", "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": [ { "version": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62001", "description": "Add support for boolean values in bound parameters." }, { "version": "v26.8.0", "pr-url": "https://github.com/nodejs/node/pull/62061", "description": "Add support for `ArrayBuffer` and `SharedArrayBuffer` objects in bound parameters." } ] }, "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 | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null | number | bigint | boolean | string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer", "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.5.0", "v24.13.1" ], "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.
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\nDatabaseSync - 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 | \nDescription | \n
|---|---|
SQLITE_CHANGESET_DATA | \n 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. | \n
SQLITE_CHANGESET_NOTFOUND | \n 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. | \n
SQLITE_CHANGESET_CONFLICT | \n This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. | \n
SQLITE_CHANGESET_CONSTRAINT | \n 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. | \n
SQLITE_CHANGESET_FOREIGN_KEY | \n 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. | \n
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 | \nDescription | \n
|---|---|
SQLITE_CHANGESET_OMIT | \n Conflicting changes are omitted. | \n
SQLITE_CHANGESET_REPLACE | \n 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. | \n
SQLITE_CHANGESET_ABORT | \n Abort when a change encounters a conflict and roll back database. | \n
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 | \nDescription | \n
|---|---|
SQLITE_OK | \n Allow the operation to proceed normally. | \n
SQLITE_DENY | \n Deny the operation and cause an error to be returned. | \n
SQLITE_IGNORE | \n Ignore the operation and continue as if it had never been requested. | \n
The following constants are passed as the first argument to the authorizer\ncallback function to indicate what type of operation is being authorized.
\n| Constant | \nDescription | \n
|---|---|
SQLITE_CREATE_INDEX | \n Create an index | \n
SQLITE_CREATE_TABLE | \n Create a table | \n
SQLITE_CREATE_TEMP_INDEX | \n Create a temporary index | \n
SQLITE_CREATE_TEMP_TABLE | \n Create a temporary table | \n
SQLITE_CREATE_TEMP_TRIGGER | \n Create a temporary trigger | \n
SQLITE_CREATE_TEMP_VIEW | \n Create a temporary view | \n
SQLITE_CREATE_TRIGGER | \n Create a trigger | \n
SQLITE_CREATE_VIEW | \n Create a view | \n
SQLITE_DELETE | \n Delete from a table | \n
SQLITE_DROP_INDEX | \n Drop an index | \n
SQLITE_DROP_TABLE | \n Drop a table | \n
SQLITE_DROP_TEMP_INDEX | \n Drop a temporary index | \n
SQLITE_DROP_TEMP_TABLE | \n Drop a temporary table | \n
SQLITE_DROP_TEMP_TRIGGER | \n Drop a temporary trigger | \n
SQLITE_DROP_TEMP_VIEW | \n Drop a temporary view | \n
SQLITE_DROP_TRIGGER | \n Drop a trigger | \n
SQLITE_DROP_VIEW | \n Drop a view | \n
SQLITE_INSERT | \n Insert into a table | \n
SQLITE_PRAGMA | \n Execute a PRAGMA statement | \n
SQLITE_READ | \n Read from a table | \n
SQLITE_SELECT | \n Execute a SELECT statement | \n
SQLITE_TRANSACTION | \n Begin, commit, or rollback a transaction | \n
SQLITE_UPDATE | \n Update a table | \n
SQLITE_ATTACH | \n Attach a database | \n
SQLITE_DETACH | \n Detach a database | \n
SQLITE_ALTER_TABLE | \n Alter a table | \n
SQLITE_REINDEX | \n Reindex | \n
SQLITE_ANALYZE | \n Analyze the database | \n
SQLITE_CREATE_VTABLE | \n Create a virtual table | \n
SQLITE_DROP_VTABLE | \n Drop a virtual table | \n
SQLITE_FUNCTION | \n Use a function | \n
SQLITE_SAVEPOINT | \n Create, release, or rollback a savepoint | \n
SQLITE_COPY | \n Copy data (legacy) | \n
SQLITE_RECURSIVE | \n Recursive query | \n