X Tutup
{ "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:

\n
import sqlite from 'node:sqlite';\n
\n
const sqlite = require('node:sqlite');\n
\n

This module is only available under the node: scheme.

\n

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.

\n
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.

" } ], "methods": [ { "textRaw": "`database.aggregate(name, options)`", "name": "aggregate", "type": "method", "meta": { "added": [ "v24.0.0", "v22.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string} The name of the SQLite function to create.", "name": "name", "type": "string", "desc": "The name of the SQLite function to create." }, { "textRaw": "`options` {Object} Function configuration settings.", "name": "options", "type": "Object", "desc": "Function configuration settings.", "options": [ { "textRaw": "`deterministic` {boolean} If `true`, the `SQLITE_DETERMINISTIC` flag is set on the created function. **Default:** `false`.", "name": "deterministic", "type": "boolean", "default": "`false`", "desc": "If `true`, the `SQLITE_DETERMINISTIC` flag is set on the created function." }, { "textRaw": "`directOnly` {boolean} If `true`, the `SQLITE_DIRECTONLY` flag is set on the created function. **Default:** `false`.", "name": "directOnly", "type": "boolean", "default": "`false`", "desc": "If `true`, the `SQLITE_DIRECTONLY` flag is set on the created function." }, { "textRaw": "`useBigIntArguments` {boolean} If `true`, integer arguments to `options.step` and `options.inverse` are converted to `BigInt`s. If `false`, integer arguments are passed as JavaScript numbers. **Default:** `false`.", "name": "useBigIntArguments", "type": "boolean", "default": "`false`", "desc": "If `true`, integer arguments to `options.step` and `options.inverse` are converted to `BigInt`s. If `false`, integer arguments are passed as JavaScript numbers." }, { "textRaw": "`varargs` {boolean} If `true`, `options.step` and `options.inverse` may be invoked with any number of arguments (between zero and `SQLITE_MAX_FUNCTION_ARG`). If `false`, `inverse` and `step` must be invoked with exactly `length` arguments. **Default:** `false`.", "name": "varargs", "type": "boolean", "default": "`false`", "desc": "If `true`, `options.step` and `options.inverse` may be invoked with any number of arguments (between zero and `SQLITE_MAX_FUNCTION_ARG`). If `false`, `inverse` and `step` must be invoked with exactly `length` arguments." }, { "textRaw": "`start` {number|string|null|Array|Object|Function} The identity value for the aggregation function. This value is used when the aggregation function is initialized. When a {Function} is passed the identity will be its return value.", "name": "start", "type": "number|string|null|Array|Object|Function", "desc": "The identity value for the aggregation function. This value is used when the aggregation function is initialized. When a {Function} is passed the identity will be its return value." }, { "textRaw": "`step` {Function} The function to call for each row in the aggregation. The function receives the current state and the row value. The return value of this function should be the new state.", "name": "step", "type": "Function", "desc": "The function to call for each row in the aggregation. The function receives the current state and the row value. The return value of this function should be the new state." }, { "textRaw": "`result` {Function} The function to call to get the result of the aggregation. The function receives the final state and should return the result of the aggregation.", "name": "result", "type": "Function", "desc": "The function to call to get the result of the aggregation. The function receives the final state and should return the result of the aggregation." }, { "textRaw": "`inverse` {Function} When this function is provided, the `aggregate` method will work as a window function. The function receives the current state and the dropped row value. The return value of this function should be the new state.", "name": "inverse", "type": "Function", "desc": "When this function is provided, the `aggregate` method will work as a window function. The function receives the current state and the dropped row value. The return value of this function should be the new state." } ] } ] } ], "desc": "

Registers a new aggregate function with the SQLite database. This method is a wrapper around\nsqlite3_create_window_function().

\n

When used as a window function, the result function will be called multiple times.

\n
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
\n
import { 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().

" }, { "textRaw": "`database.loadExtension(path)`", "name": "loadExtension", "type": "method", "meta": { "added": [ "v23.5.0", "v22.13.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string} The path to the shared library to load.", "name": "path", "type": "string", "desc": "The path to the shared library to load." } ] } ], "desc": "

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.

" }, { "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.

" }, { "textRaw": "`database.enableDefensive(active)`", "name": "enableDefensive", "type": "method", "meta": { "added": [ "v25.1.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`active` {boolean} Whether to set the defensive flag.", "name": "active", "type": "boolean", "desc": "Whether to set the defensive flag." } ] } ], "desc": "

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.

" }, { "textRaw": "`database.location([dbName])`", "name": "location", "type": "method", "meta": { "added": [ "v24.0.0", "v22.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`dbName` {string} Name of the database. This can be `'main'` (the default primary database) or any other database that has been added with `ATTACH DATABASE` **Default:** `'main'`.", "name": "dbName", "type": "string", "default": "`'main'`", "desc": "Name of the database. This can be `'main'` (the default primary database) or any other database that has been added with `ATTACH DATABASE`", "optional": true } ], "return": { "textRaw": "Returns: {string|null} The location of the database file. When using an in-memory database, this method returns null.", "name": "return", "type": "string|null", "desc": "The location of the database file. When using an in-memory database, this method returns null." } } ], "desc": "

This method is a wrapper around sqlite3_db_filename()

" }, { "textRaw": "`database.exec(sql)`", "name": "exec", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`sql` {string} A SQL string to execute.", "name": "sql", "type": "string", "desc": "A SQL string to execute." } ] } ], "desc": "

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

" }, { "textRaw": "`database.function(name[, options], fn)`", "name": "function", "type": "method", "meta": { "added": [ "v23.5.0", "v22.13.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string} The name of the SQLite function to create.", "name": "name", "type": "string", "desc": "The name of the SQLite function to create." }, { "textRaw": "`options` {Object} Optional configuration settings for the function. The following properties are supported:", "name": "options", "type": "Object", "desc": "Optional configuration settings for the function. The following properties are supported:", "options": [ { "textRaw": "`deterministic` {boolean} If `true`, the `SQLITE_DETERMINISTIC` flag is set on the created function. **Default:** `false`.", "name": "deterministic", "type": "boolean", "default": "`false`", "desc": "If `true`, the `SQLITE_DETERMINISTIC` flag is set on the created function." }, { "textRaw": "`directOnly` {boolean} If `true`, the `SQLITE_DIRECTONLY` flag is set on the created function. **Default:** `false`.", "name": "directOnly", "type": "boolean", "default": "`false`", "desc": "If `true`, the `SQLITE_DIRECTONLY` flag is set on the created function." }, { "textRaw": "`useBigIntArguments` {boolean} If `true`, integer arguments to `function` are converted to `BigInt`s. If `false`, integer arguments are passed as JavaScript numbers. **Default:** `false`.", "name": "useBigIntArguments", "type": "boolean", "default": "`false`", "desc": "If `true`, integer arguments to `function` are converted to `BigInt`s. If `false`, integer arguments are passed as JavaScript numbers." }, { "textRaw": "`varargs` {boolean} If `true`, `function` may be invoked with any number of arguments (between zero and `SQLITE_MAX_FUNCTION_ARG`). If `false`, `function` must be invoked with exactly `function.length` arguments. **Default:** `false`.", "name": "varargs", "type": "boolean", "default": "`false`", "desc": "If `true`, `function` may be invoked with any number of arguments (between zero and `SQLITE_MAX_FUNCTION_ARG`). If `false`, `function` must be invoked with exactly `function.length` arguments." } ], "optional": true }, { "textRaw": "`fn` {Function} The JavaScript function to call when the SQLite function is invoked. The return value of this function should be a valid SQLite data type: see Type conversion between JavaScript and SQLite. The result defaults to `NULL` if the return value is `undefined`.", "name": "fn", "type": "Function", "desc": "The JavaScript function to call when the SQLite function is invoked. The return value of this function should be a valid SQLite data type: see Type conversion between JavaScript and SQLite. The result defaults to `NULL` if the return value is `undefined`." } ] } ], "desc": "

This method is used to create SQLite user-defined functions. This method is a\nwrapper around sqlite3_create_function_v2().

" }, { "textRaw": "`database.setAuthorizer(callback)`", "name": "setAuthorizer", "type": "method", "meta": { "added": [ "v24.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function|null} The authorizer function to set, or `null` to clear the current authorizer.", "name": "callback", "type": "Function|null", "desc": "The authorizer function to set, or `null` to clear the current authorizer." } ] } ], "desc": "

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

\n

When invoked, the callback receives five arguments:

\n\n

The callback must return one of the following constants:

\n\n
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
\n
import { 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.

" }, { "textRaw": "`database.prepare(sql[, options])`", "name": "prepare", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "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." } ], "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_v2().

" }, { "textRaw": "`database.createTagStore([maxSize])`", "name": "createTagStore", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`maxSize` {integer} The maximum number of prepared statements to cache. **Default:** `1000`.", "name": "maxSize", "type": "integer", "default": "`1000`", "desc": "The maximum number of prepared statements to cache.", "optional": true } ], "return": { "textRaw": "Returns: {SQLTagStore} A new SQL tag store for caching prepared statements.", "name": "return", "type": "SQLTagStore", "desc": "A new SQL tag store for caching prepared statements." } } ], "desc": "

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.

\n

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.

\n

Tagged statements bind the placeholder values from the template literal as\nparameters to the underlying prepared statement. For example:

\n
sqlTagStore.get`SELECT ${value}`;\n
\n

is equivalent to:

\n
db.prepare('SELECT ?').get(value);\n
\n

However, in the first example, the tag store will cache the underlying prepared\nstatement for future use.

\n
\n

Note: The ${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
\n
\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
\n

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

\n
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
\n
const { 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().

" }, { "textRaw": "`database.applyChangeset(changeset[, options])`", "name": "applyChangeset", "type": "method", "meta": { "added": [ "v23.3.0", "v22.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`changeset` {Uint8Array} A binary changeset or patchset.", "name": "changeset", "type": "Uint8Array", "desc": "A binary changeset or patchset." }, { "textRaw": "`options` {Object} The configuration options for how the changes will be applied.", "name": "options", "type": "Object", "desc": "The configuration options for how the changes will be applied.", "options": [ { "textRaw": "`filter` {Function} Skip changes that, when targeted table name is supplied to this function, return a truthy value. By default, all changes are attempted.", "name": "filter", "type": "Function", "desc": "Skip changes that, when targeted table name is supplied to this function, return a truthy value. By default, all changes are attempted." }, { "textRaw": "`onConflict` {Function} A function that determines how to handle conflicts. The function receives one argument, which can be one of the following values:The function should return one of the following values:`SQLITE_CHANGESET_OMIT`: Omit conflicting changes.`SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts).`SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database.When an error is thrown in the conflict handler or when any other value is returned from the handler, applying the changeset is aborted and the database is rolled back.**Default**: A function that returns `SQLITE_CHANGESET_ABORT`.", "name": "onConflict", "type": "Function", "desc": "A function that determines how to handle conflicts. The function receives one argument, which can be one of the following values:The function should return one of the following values:`SQLITE_CHANGESET_OMIT`: Omit conflicting changes.`SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts).`SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database.When an error is thrown in the conflict handler or when any other value is returned from the handler, applying the changeset is aborted and the database is rolled back.**Default**: A function that returns `SQLITE_CHANGESET_ABORT`.", "options": [ { "textRaw": "`SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected \"before\" values.", "name": "SQLITE_CHANGESET_DATA", "desc": "A `DELETE` or `UPDATE` change does not contain the expected \"before\" values." }, { "textRaw": "`SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist.", "name": "SQLITE_CHANGESET_NOTFOUND", "desc": "A row matching the primary key of the `DELETE` or `UPDATE` change does not exist." }, { "textRaw": "`SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key.", "name": "SQLITE_CHANGESET_CONFLICT", "desc": "An `INSERT` change results in a duplicate primary key." }, { "textRaw": "`SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation.", "name": "SQLITE_CHANGESET_FOREIGN_KEY", "desc": "Applying a change would result in a foreign key violation." }, { "textRaw": "`SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint violation.", "name": "SQLITE_CHANGESET_CONSTRAINT", "desc": "Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint violation." } ] } ], "optional": true } ], "return": { "textRaw": "Returns: {boolean} Whether the changeset was applied successfully without being aborted.", "name": "return", "type": "boolean", "desc": "Whether the changeset was applied successfully without being aborted." } } ], "desc": "

An exception is thrown if the database is not\nopen. This method is a wrapper around sqlite3changeset_apply().

\n
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
\n
const { 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.

\n
const 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
\n

Available properties: length, sqlLength, column, exprDepth,\ncompoundSelect, vdbeOp, functionArg, attach, likePatternLength,\nvariableNumber, triggerDepth.

\n

Setting a property to Infinity resets the limit to its compile-time maximum value.

" } ] }, { "textRaw": "Class: `Session`", "name": "Session", "type": "class", "meta": { "added": [ "v23.3.0", "v22.12.0" ], "changes": [] }, "methods": [ { "textRaw": "`session.changeset()`", "name": "changeset", "type": "method", "meta": { "added": [ "v23.3.0", "v22.12.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Uint8Array} Binary changeset that can be applied to other databases.", "name": "return", "type": "Uint8Array", "desc": "Binary changeset that can be applied to other databases." } } ], "desc": "

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

" }, { "textRaw": "`session.patchset()`", "name": "patchset", "type": "method", "meta": { "added": [ "v23.3.0", "v22.12.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Uint8Array} Binary patchset that can be applied to other databases.", "name": "return", "type": "Uint8Array", "desc": "Binary patchset that can be applied to other databases." } } ], "desc": "

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

" }, { "textRaw": "`session.close()`", "name": "close", "type": "method", "signatures": [ { "params": [] } ], "desc": "

Closes the session. An exception is thrown if the database or the session is not open. This method is a\nwrapper around sqlite3session_delete().

" }, { "textRaw": "`session[Symbol.dispose]()`", "name": "[Symbol.dispose]", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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.

\n

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.

" }, { "textRaw": "`statement.columns()`", "name": "columns", "type": "method", "meta": { "added": [ "v23.11.0", "v22.16.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Array} An array of objects. Each object corresponds to a column in the prepared statement, and contains the following properties:", "name": "return", "type": "Array", "desc": "An array of objects. Each object corresponds to a column in the prepared statement, and contains the following properties:", "options": [ { "textRaw": "`column` {string|null} The unaliased name of the column in the origin table, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_origin_name()`.", "name": "column", "type": "string|null", "desc": "The unaliased name of the column in the origin table, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_origin_name()`." }, { "textRaw": "`database` {string|null} The unaliased name of the origin database, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_database_name()`.", "name": "database", "type": "string|null", "desc": "The unaliased name of the origin database, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_database_name()`." }, { "textRaw": "`name` {string} The name assigned to the column in the result set of a `SELECT` statement. This property is the result of `sqlite3_column_name()`.", "name": "name", "type": "string", "desc": "The name assigned to the column in the result set of a `SELECT` statement. This property is the result of `sqlite3_column_name()`." }, { "textRaw": "`table` {string|null} The unaliased name of the origin table, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_table_name()`.", "name": "table", "type": "string|null", "desc": "The unaliased name of the origin table, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_table_name()`." }, { "textRaw": "`type` {string|null} The declared data type of the column, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_decltype()`.", "name": "type", "type": "string|null", "desc": "The declared data type of the column, or `null` if the column is the result of an expression or subquery. This property is the result of `sqlite3_column_decltype()`." } ] } } ], "desc": "

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.

" }, { "textRaw": "`statement.iterate([namedParameters][, ...anonymousParameters])`", "name": "iterate", "type": "method", "meta": { "added": [ "v23.4.0", "v22.13.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: {Iterator} An iterable iterator of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.", "name": "return", "type": "Iterator", "desc": "An iterable iterator of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row." } } ], "desc": "

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.

" }, { "textRaw": "`statement.run([namedParameters][, ...anonymousParameters])`", "name": "run", "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}", "name": "return", "type": "Object", "options": [ { "textRaw": "`changes` {number|bigint} The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. This field is either a number or a `BigInt` depending on the prepared statement's configuration. This property is the result of `sqlite3_changes64()`.", "name": "changes", "type": "number|bigint", "desc": "The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. This field is either a number or a `BigInt` depending on the prepared statement's configuration. This property is the result of `sqlite3_changes64()`." }, { "textRaw": "`lastInsertRowid` {number|bigint} The most recently inserted rowid. This field is either a number or a `BigInt` depending on the prepared statement's configuration. This property is the result of `sqlite3_last_insert_rowid()`.", "name": "lastInsertRowid", "type": "number|bigint", "desc": "The most recently inserted rowid. This field is either a number or a `BigInt` depending on the prepared statement's configuration. This property is the result of `sqlite3_last_insert_rowid()`." } ] } } ], "desc": "

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.

" }, { "textRaw": "`statement.setAllowBareNamedParameters(enabled)`", "name": "setAllowBareNamedParameters", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`enabled` {boolean} Enables or disables support for binding named parameters without the prefix character.", "name": "enabled", "type": "boolean", "desc": "Enables or disables support for binding named parameters without the prefix character." } ] } ], "desc": "

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.

\n

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" }, { "textRaw": "`statement.setAllowUnknownNamedParameters(enabled)`", "name": "setAllowUnknownNamedParameters", "type": "method", "meta": { "added": [ "v23.11.0", "v22.15.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`enabled` {boolean} Enables or disables support for unknown named parameters.", "name": "enabled", "type": "boolean", "desc": "Enables or disables support for unknown named parameters." } ] } ], "desc": "

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.

" }, { "textRaw": "`statement.setReadBigInts(enabled)`", "name": "setReadBigInts", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`enabled` {boolean} Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database.", "name": "enabled", "type": "boolean", "desc": "Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database." } ] } ], "desc": "

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.

" } ], "properties": [ { "textRaw": "Type: {string} The source SQL expanded to include parameter values.", "name": "expandedSQL", "type": "string", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "desc": "

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

", "shortDesc": "The source SQL expanded to include parameter values." }, { "textRaw": "Type: {string} The source SQL used to create this prepared statement.", "name": "sourceSQL", "type": "string", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "desc": "

The source SQL text of the prepared statement. This property is a\nwrapper around sqlite3_sql().

", "shortDesc": "The source SQL used to create this prepared statement." } ] }, { "textRaw": "Class: `SQLTagStore`", "name": "SQLTagStore", "type": "class", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "desc": "

This class represents a single LRU (Least Recently Used) cache for storing\nprepared statements.

\n

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

\n

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.

", "methods": [ { "textRaw": "`sqlTagStore.all(stringElements[, ...boundParameters])`", "name": "all", "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: {Array} An array of objects representing the rows returned by the query.", "name": "return", "type": "Array", "desc": "An array of objects representing the rows returned by the query." } } ], "desc": "

Executes the given SQL query and returns all resulting rows as an array of\nobjects.

\n

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

\n

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

\n

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

\n

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

" } ], "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\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 classJavaScript to SQLiteSQLite to JavaScript
NULL<null><null>
INTEGER<number> or <bigint><number> or <bigint> (configurable)
REAL<number><number>
TEXT<string><string>
BLOB<TypedArray> or <DataView><Uint8Array>
\n

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.

", "displayName": "Type conversion between JavaScript and SQLite" } ] } ], "methods": [ { "textRaw": "`sqlite.backup(sourceDb, path[, options])`", "name": "backup", "type": "method", "meta": { "added": [ "v23.8.0", "v22.16.0" ], "changes": [ { "version": "v23.10.0", "pr-url": "https://github.com/nodejs/node/pull/56991", "description": "The `path` argument now supports Buffer and URL objects." } ] }, "signatures": [ { "params": [ { "textRaw": "`sourceDb` {DatabaseSync} The database to backup. The source database must be open.", "name": "sourceDb", "type": "DatabaseSync", "desc": "The database to backup. The source database must be open." }, { "textRaw": "`path` {string|Buffer|URL} The path where the backup will be created. If the file already exists, the contents will be overwritten.", "name": "path", "type": "string|Buffer|URL", "desc": "The path where the backup will be created. If the file already exists, the contents will be overwritten." }, { "textRaw": "`options` {Object} Optional configuration for the backup. The following properties are supported:", "name": "options", "type": "Object", "desc": "Optional configuration for the backup. The following properties are supported:", "options": [ { "textRaw": "`source` {string} Name of the source database. This can be `'main'` (the default primary database) or any other database that have been added with `ATTACH DATABASE` **Default:** `'main'`.", "name": "source", "type": "string", "default": "`'main'`", "desc": "Name of the source database. This can be `'main'` (the default primary database) or any other database that have been added with `ATTACH DATABASE`" }, { "textRaw": "`target` {string} Name of the target database. This can be `'main'` (the default primary database) or any other database that have been added with `ATTACH DATABASE` **Default:** `'main'`.", "name": "target", "type": "string", "default": "`'main'`", "desc": "Name of the target database. This can be `'main'` (the default primary database) or any other database that have been added with `ATTACH DATABASE`" }, { "textRaw": "`rate` {number} Number of pages to be transmitted in each batch of the backup. **Default:** `100`.", "name": "rate", "type": "number", "default": "`100`", "desc": "Number of pages to be transmitted in each batch of the backup." }, { "textRaw": "`progress` {Function} An optional callback function that will be called after each backup step. The argument passed to this callback is an {Object} with `remainingPages` and `totalPages` properties, describing the current progress of the backup operation.", "name": "progress", "type": "Function", "desc": "An optional callback function that will be called after each backup step. The argument passed to this callback is an {Object} with `remainingPages` and `totalPages` properties, describing the current progress of the backup operation." } ], "optional": true } ], "return": { "textRaw": "Returns: {Promise} A promise that fulfills with the total number of backed-up pages upon completion, or rejects if an error occurs.", "name": "return", "type": "Promise", "desc": "A promise that fulfills with the total number of backed-up pages upon completion, or rejects if an error occurs." } } ], "desc": "

This method makes a database backup. This method abstracts the sqlite3_backup_init(), sqlite3_backup_step()\nand sqlite3_backup_finish() functions.

\n

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.

\n
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
\n
import { 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.

", "modules": [ { "textRaw": "Conflict resolution constants", "name": "conflict_resolution_constants", "type": "module", "desc": "

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.

\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
ConstantDescription
SQLITE_CHANGESET_DATAThe 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_NOTFOUNDThe 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_CONFLICTThis constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.
SQLITE_CHANGESET_CONSTRAINTIf 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_KEYIf 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

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.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
SQLITE_CHANGESET_OMITConflicting changes are omitted.
SQLITE_CHANGESET_REPLACEConflicting 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_ABORTAbort when a change encounters a conflict and roll back database.
", "displayName": "Conflict resolution constants" }, { "textRaw": "Authorization constants", "name": "authorization_constants", "type": "module", "desc": "

The following constants are used with the database.setAuthorizer() method.

", "modules": [ { "textRaw": "Authorization result codes", "name": "authorization_result_codes", "type": "module", "desc": "

One of the following constants must be returned from the authorizer callback\nfunction passed to database.setAuthorizer().

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
SQLITE_OKAllow the operation to proceed normally.
SQLITE_DENYDeny the operation and cause an error to be returned.
SQLITE_IGNOREIgnore the operation and continue as if it had never been requested.
", "displayName": "Authorization result codes" }, { "textRaw": "Authorization action codes", "name": "authorization_action_codes", "type": "module", "desc": "

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
ConstantDescription
SQLITE_CREATE_INDEXCreate an index
SQLITE_CREATE_TABLECreate a table
SQLITE_CREATE_TEMP_INDEXCreate a temporary index
SQLITE_CREATE_TEMP_TABLECreate a temporary table
SQLITE_CREATE_TEMP_TRIGGERCreate a temporary trigger
SQLITE_CREATE_TEMP_VIEWCreate a temporary view
SQLITE_CREATE_TRIGGERCreate a trigger
SQLITE_CREATE_VIEWCreate a view
SQLITE_DELETEDelete from a table
SQLITE_DROP_INDEXDrop an index
SQLITE_DROP_TABLEDrop a table
SQLITE_DROP_TEMP_INDEXDrop a temporary index
SQLITE_DROP_TEMP_TABLEDrop a temporary table
SQLITE_DROP_TEMP_TRIGGERDrop a temporary trigger
SQLITE_DROP_TEMP_VIEWDrop a temporary view
SQLITE_DROP_TRIGGERDrop a trigger
SQLITE_DROP_VIEWDrop a view
SQLITE_INSERTInsert into a table
SQLITE_PRAGMAExecute a PRAGMA statement
SQLITE_READRead from a table
SQLITE_SELECTExecute a SELECT statement
SQLITE_TRANSACTIONBegin, commit, or rollback a transaction
SQLITE_UPDATEUpdate a table
SQLITE_ATTACHAttach a database
SQLITE_DETACHDetach a database
SQLITE_ALTER_TABLEAlter a table
SQLITE_REINDEXReindex
SQLITE_ANALYZEAnalyze the database
SQLITE_CREATE_VTABLECreate a virtual table
SQLITE_DROP_VTABLEDrop a virtual table
SQLITE_FUNCTIONUse a function
SQLITE_SAVEPOINTCreate, release, or rollback a savepoint
SQLITE_COPYCopy data (legacy)
SQLITE_RECURSIVERecursive query
", "displayName": "Authorization action codes" } ], "displayName": "Authorization constants" } ], "displayName": "SQLite constants" } ] } ], "displayName": "SQLite" } ] }
X Tutup