- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- sqlite 轻型数据库
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v25.3.0 文档
- Node.js v25.3.0
-
目录
- SQLite
- 类:
DatabaseSyncnew DatabaseSync(path[, options])database.aggregate(name, options)database.close()database.loadExtension(path)database.enableLoadExtension(allow)database.location([dbName])database.exec(sql)database.function(name[, options], function)database.setAuthorizer(callback)database.isOpendatabase.isTransactiondatabase.open()database.prepare(sql)database.createTagStore([maxSize])database.createSession([options])database.applyChangeset(changeset[, options])database[Symbol.dispose]()
- 类:
Session - 类:
StatementSync - 类:
SQLTagStoresqlTagStore.all(sqlTemplate[, ...values])sqlTagStore.get(sqlTemplate[, ...values])sqlTagStore.iterate(sqlTemplate[, ...values])sqlTagStore.run(sqlTemplate[, ...values])sqlTagStore.size()sqlTagStore.capacitysqlTagStore.dbsqlTagStore.reset()sqlTagStore.clear()statement.all([namedParameters][, ...anonymousParameters])statement.columns()statement.expandedSQLstatement.get([namedParameters][, ...anonymousParameters])statement.iterate([namedParameters][, ...anonymousParameters])statement.run([namedParameters][, ...anonymousParameters])statement.setAllowBareNamedParameters(enabled)statement.setAllowUnknownNamedParameters(enabled)statement.setReturnArrays(enabled)statement.setReadBigInts(enabled)statement.sourceSQL- JavaScript 和 SQLite 之间的类型转换
sqlite.backup(sourceDb, path[, options])sqlite.constants
- 类:
- SQLite
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- sqlite 轻型数据库
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- 其他版本
SQLite#>
源代码: lib/sqlite.js
node:sqlite 模块便于操作 SQLite 数据库。要访问它:
【The node:sqlite module facilitates working with SQLite databases.
To access it:】
import sqlite from 'node:sqlite';const sqlite = require('node:sqlite');
此模块仅在 node: 方案下可用。
【This module is only available under the node: scheme.】
下面的示例展示了 node:sqlite 模块的基本用法,包括打开内存数据库、向数据库写入数据,然后再读取数据。
【The following example shows the basic usage of the node:sqlite module to open
an in-memory database, write data to the database, and then read the data back.】
import { DatabaseSync } from 'node:sqlite';
const database = new DatabaseSync(':memory:');
// Execute SQL statements from strings.
database.exec(`
CREATE TABLE data(
key INTEGER PRIMARY KEY,
value TEXT
) STRICT
`);
// Create a prepared statement to insert data into the database.
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
// Execute the prepared statement with bound values.
insert.run(1, 'hello');
insert.run(2, 'world');
// Create a prepared statement to read data from the database.
const query = database.prepare('SELECT * FROM data ORDER BY key');
// Execute the prepared statement and log the result set.
console.log(query.all());
// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]'use strict';
const { DatabaseSync } = require('node:sqlite');
const database = new DatabaseSync(':memory:');
// Execute SQL statements from strings.
database.exec(`
CREATE TABLE data(
key INTEGER PRIMARY KEY,
value TEXT
) STRICT
`);
// Create a prepared statement to insert data into the database.
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
// Execute the prepared statement with bound values.
insert.run(1, 'hello');
insert.run(2, 'world');
// Create a prepared statement to read data from the database.
const query = database.prepare('SELECT * FROM data ORDER BY key');
// Execute the prepared statement and log the result set.
console.log(query.all());
// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]
类:DatabaseSync#>
【Class: DatabaseSync】
该类表示到 SQLite 数据库的单个 连接。该类提供的所有 API 都是同步执行的。
【This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.】
new DatabaseSync(path[, options])#>
path<string> | <Buffer> | <URL> 数据库的路径。SQLite 数据库可以存储在文件中,也可以完全 纪念。要使用基于文件的数据库,路径应为文件路径。要使用内存数据库,路径应为特殊名称':memory:'。options<Object> 数据库连接的配置选项。支持以下选项:open<boolean> 如果为true,数据库将在构造函数中打开。当该值为false时,必须通过open()方法打开数据库。默认值:true。readOnly<boolean> 如果为true,数据库将以只读模式打开。如果数据库不存在,打开将失败。默认值:false。enableForeignKeyConstraints<boolean> 如果为true,则启用外键约束。推荐启用,但为了兼容旧的数据库架构可以禁用。在打开数据库后,可以使用PRAGMA foreign_keys启用或禁用外键约束的执行。默认值:true。enableDoubleQuotedStringLiterals<boolean> 如果设置为true,SQLite 将接受 双引号字符串字面量。这不推荐使用,但可以为了兼容旧的数据库模式而启用。默认值:false。allowExtension<boolean> 如果为true,则启用loadExtensionSQL 函数和loadExtension()方法。你可以稍后调用enableLoadExtension(false)来禁用此功能。默认值:false。timeout<number> 以毫秒为单位的 忙时超时。这是 SQLite 等待数据库锁释放前的最长时间,然后才返回错误。默认值:0。readBigInts<boolean> 如果为true,整数字段将作为 JavaScriptBigInt值读取。如果为false,整数字段将作为 JavaScript 数字读取。默认值:false。returnArrays<boolean> 如果为true,查询结果将以数组形式返回,而不是对象形式。 默认值:false。allowBareNamedParameters<boolean> 如果为true,则允许绑定命名参数而无需前缀字符(例如,使用foo而不是:foo)。默认值:true。allowUnknownNamedParameters<boolean> 如果为true,在绑定时会忽略未知的命名参数。 如果为false,遇到未知的命名参数会抛出异常。默认值:false。
构建一个新的 DatabaseSync 实例。
【Constructs a new DatabaseSync instance.】
database.aggregate(name, options)#>
在 SQLite 数据库中注册一个新的聚合函数。此方法是 sqlite3_create_window_function() 的封装。
【Registers a new aggregate function with the SQLite database. This method is a wrapper around
sqlite3_create_window_function().】
name<string> 要创建的 SQLite 函数的名称。options<Object> 功能配置设置。deterministic<boolean> 如果为true,则在创建的函数上设置SQLITE_DETERMINISTIC标志。默认值:false。directOnly<boolean> 如果为true,则在创建的函数上设置SQLITE_DIRECTONLY标志。默认值:false。useBigIntArguments<boolean> 如果为true,则传给options.step和options.inverse的整数参数会被转换为BigInt。如果为false,整数参数会作为 JavaScript 数字传递。默认值:false。varargs<boolean> 如果为true,options.step和options.inverse可以使用任意数量的参数(从零到SQLITE_MAX_FUNCTION_ARG)调用。如果为false,inverse和step必须使用准确的length个参数调用。默认值:false。start<number> | <string> | <null> | <Array> | <Object> | <Function> 聚合函数的初始值。该值在聚合函数初始化时使用。当传入 <Function> 时,初始值将作为其返回值。step<Function> 每行聚合时调用的函数。该函数接收当前状态和行的值。此函数的返回值应为新的状态。result<Function> 用于获取聚合结果的函数。该函数接收最终状态,并应返回聚合的结果。inverse<Function> 当提供此函数时,aggregate方法将作为窗口函数运行。该函数接收当前状态和被丢弃的行的值。此函数的返回值应为新的状态。
当作为窗口函数使用时,result 函数会被调用多次。
【When used as a window function, the result function will be called multiple times.】
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(':memory:');
db.exec(`
CREATE TABLE t3(x, y);
INSERT INTO t3 VALUES ('a', 4),
('b', 5),
('c', 3),
('d', 8),
('e', 1);
`);
db.aggregate('sumint', {
start: 0,
step: (acc, value) => acc + value,
});
db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }import { DatabaseSync } from 'node:sqlite';
const db = new DatabaseSync(':memory:');
db.exec(`
CREATE TABLE t3(x, y);
INSERT INTO t3 VALUES ('a', 4),
('b', 5),
('c', 3),
('d', 8),
('e', 1);
`);
db.aggregate('sumint', {
start: 0,
step: (acc, value) => acc + value,
});
db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }
database.close()#>
关闭数据库连接。如果数据库未打开,将抛出异常。此方法是 sqlite3_close_v2() 的封装器。
【Closes the database connection. An exception is thrown if the database is not
open. This method is a wrapper around sqlite3_close_v2().】
database.loadExtension(path)#>
path<string> 要加载的共享库的路径。
将共享库加载到数据库连接中。此方法是 sqlite3_load_extension() 的封装。在构建 DatabaseSync 实例时,需要启用 allowExtension 选项。
【Loads a shared library into the database connection. This method is a wrapper
around sqlite3_load_extension(). It is required to enable the
allowExtension option when constructing the DatabaseSync instance.】
database.enableLoadExtension(allow)#>
allow<boolean> 是否允许加载扩展。
启用或禁用 loadExtension SQL 函数和 loadExtension() 方法。当在构建时 allowExtension 为 false 时,出于安全原因,你无法启用加载扩展功能。
【Enables or disables the loadExtension SQL function, and the loadExtension()
method. When allowExtension is false when constructing, you cannot enable
loading extensions for security reasons.】
database.location([dbName])#>
dbName<string> 数据库名称。可以是'main'(默认的主数据库)或任何已使用ATTACH DATABASE添加的其他数据库。默认值:'main'。- 返回值:<string> | <null> 数据库文件的位置。当使用内存数据库时,此方法返回 null。
此方法是 sqlite3_db_filename() 的一个封装
【This method is a wrapper around sqlite3_db_filename()】
database.exec(sql)#>
sql<string> 要执行的 SQL 字符串。
此方法允许执行一个或多个 SQL 语句而不返回任何结果。当执行从文件中读取的 SQL 语句时,此方法非常有用。此方法是 sqlite3_exec() 的一个封装。
【This method allows one or more SQL statements to be executed without returning
any results. This method is useful when executing SQL statements read from a
file. This method is a wrapper around sqlite3_exec().】
database.function(name[, options], function)#>
name<string> 要创建的 SQLite 函数的名称。options<Object> 函数的可选配置设置。支持以下属性:deterministic<boolean> 如果为true,则在创建的函数上设置SQLITE_DETERMINISTIC标志。默认值:false。directOnly<boolean> 如果为true,则在创建的函数上设置SQLITE_DIRECTONLY标志。默认值:false。useBigIntArguments<boolean> 如果为true,传递给function的整数参数将被转换为BigInt。如果为false,整数参数将作为 JavaScript 数字传递。默认值:false。varargs<boolean> 如果为true,则function可以用任意数量的参数(在零到SQLITE_MAX_FUNCTION_ARG之间)调用。如果为false,function必须精确使用function.length个参数调用。默认值:false。
function<Function> 当调用 SQLite 函数时要执行的 JavaScript 函数。此函数的返回值应为有效的 SQLite 数据类型:见 JavaScript 和 SQLite 之间的类型转换。如果返回值为undefined,结果默认是NULL。
此方法用于创建 SQLite 用户自定义函数。此方法是 sqlite3_create_function_v2() 的一个封装。
【This method is used to create SQLite user-defined functions. This method is a
wrapper around sqlite3_create_function_v2().】
database.setAuthorizer(callback)#>
callback<Function> | <null> 要设置的授权器函数,或null以清除当前的授权器。
设置一个授权回调,当 SQLite 尝试通过预处理语句访问数据或修改数据库模式时将调用该回调。可以用它来实现安全策略、审核访问或限制某些操作。此方法是 sqlite3_set_authorizer() 的封装。
【Sets an authorizer callback that SQLite will invoke whenever it attempts to
access data or modify the database schema through prepared statements.
This can be used to implement security policies, audit access, or restrict certain operations.
This method is a wrapper around sqlite3_set_authorizer().】
调用时,回调函数会接收五个参数:
【When invoked, the callback receives five arguments:】
actionCode<number> 执行的操作类型(例如,SQLITE_INSERT、SQLITE_UPDATE、SQLITE_SELECT)。arg1<string> | <null> 第一个参数(依赖上下文,通常是表名)。arg2<string> | <null> 第二个参数(依赖于上下文,通常是列名)。dbName<string> | <null> 数据库的名称。triggerOrView<string> | <null> 导致访问的触发器或视图的名称。
回调函数必须返回以下常量之一:
【The callback must return one of the following constants:】
SQLITE_OK- 允许该操作。SQLITE_DENY- 拒绝操作(会导致错误)。SQLITE_IGNORE- 忽略该操作(静默跳过)。
const { DatabaseSync, constants } = require('node:sqlite');
const db = new DatabaseSync(':memory:');
// Set up an authorizer that denies all table creation
db.setAuthorizer((actionCode) => {
if (actionCode === constants.SQLITE_CREATE_TABLE) {
return constants.SQLITE_DENY;
}
return constants.SQLITE_OK;
});
// This will work
db.prepare('SELECT 1').get();
// This will throw an error due to authorization denial
try {
db.exec('CREATE TABLE blocked (id INTEGER)');
} catch (err) {
console.log('Operation blocked:', err.message);
}import { DatabaseSync, constants } from 'node:sqlite';
const db = new DatabaseSync(':memory:');
// Set up an authorizer that denies all table creation
db.setAuthorizer((actionCode) => {
if (actionCode === constants.SQLITE_CREATE_TABLE) {
return constants.SQLITE_DENY;
}
return constants.SQLITE_OK;
});
// This will work
db.prepare('SELECT 1').get();
// This will throw an error due to authorization denial
try {
db.exec('CREATE TABLE blocked (id INTEGER)');
} catch (err) {
console.log('Operation blocked:', err.message);
}
database.isOpen#>
- 类型:<boolean> 数据库当前是否已打开。
database.isTransaction#>
- 类型:<boolean> 数据库当前是否处于事务中。此方法是
sqlite3_get_autocommit()的封装器。
database.open()#>
打开在 DatabaseSync 构造函数的 path 参数中指定的数据库。只有在数据库未通过构造函数打开时才应使用此方法。如果数据库已经打开,将抛出异常。
【Opens the database specified in the path argument of the DatabaseSync
constructor. This method should only be used when the database is not opened via
the constructor. An exception is thrown if the database is already open.】
database.prepare(sql)#>
sql<string> 一个要编译为预处理语句的 SQL 字符串。- 返回:StatementSync 已准备的语句。
将 SQL 语句编译成 准备好的声明。此方法是 sqlite3_prepare_v2() 的一个封装。
【Compiles a SQL statement into a prepared statement. This method is a wrapper
around sqlite3_prepare_v2().】
database.createTagStore([maxSize])#>
maxSize<integer> 缓存的预编译语句的最大数量。默认值:1000。- 返回:SQLTagStore 一个用于缓存预处理语句的新 SQL 标签存储。
创建一个新的 SQLTagStore,它是用于存储预编译语句的 LRU(最近最少使用)缓存。这允许通过给预编译语句打上唯一标识符来高效地重复使用它们。
【Creates a new SQLTagStore, which is an LRU (Least Recently Used) cache for
storing prepared statements. This allows for the efficient reuse of prepared
statements by tagging them with a unique identifier.】
当执行带标签的 SQL 字面量时,SQLTagStore 会检查缓存中是否已有针对该特定 SQL 字符串的预处理语句。如果存在,则使用缓存中的语句。如果不存在,则会创建一个新的预处理语句,执行它,然后将其存储在缓存中以便将来使用。这一机制有助于避免重复解析和准备相同 SQL 语句的开销。
【When a tagged SQL literal is executed, the SQLTagStore checks if a prepared
statement for that specific SQL string already exists in the cache. If it does,
the cached statement is used. If not, a new prepared statement is created,
executed, and then stored in the cache for future use. This mechanism helps to
avoid the overhead of repeatedly parsing and preparing the same SQL statements.】
import { DatabaseSync } from 'node:sqlite';
const db = new DatabaseSync(':memory:');
const sql = db.createTagStore();
db.exec('CREATE TABLE users (id INT, name TEXT)');
// Using the 'run' method to insert data.
// The tagged literal is used to identify the prepared statement.
sql.run`INSERT INTO users VALUES (1, 'Alice')`;
sql.run`INSERT INTO users VALUES (2, 'Bob')`;
// Using the 'get' method to retrieve a single row.
const id = 1;
const user = sql.get`SELECT * FROM users WHERE id = ${id}`;
console.log(user); // { id: 1, name: 'Alice' }
// Using the 'all' method to retrieve all rows.
const allUsers = sql.all`SELECT * FROM users ORDER BY id`;
console.log(allUsers);
// [
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Bob' }
// ]
database.createSession([options])#>
options<Object> 会话的配置选项。table<string> 一个用于跟踪特定表格更改的表。默认情况下,会跟踪所有表格的更改。db<string> 要跟踪的数据库名称。当使用ATTACH DATABASE添加了多个数据库时,这很有用。默认:'main'。
- 返回:Session 一个会话句柄。
创建并将会话附加到数据库。此方法是 sqlite3session_create() 和 sqlite3session_attach() 的封装。
【Creates and attaches a session to the database. This method is a wrapper around sqlite3session_create() and sqlite3session_attach().】
database.applyChangeset(changeset[, options])#>
changeset<Uint8Array> 一个二进制变更集或补丁集。options<Object> 配置选项,用于设置变更将如何应用。-
filter<Function> 跳过那些在向此函数提供目标表名时返回真值的更改。默认情况下,会尝试所有更改。 -
onConflict<Function> 一个用于确定如何处理冲突的函数。该函数接收一个参数,该参数可以是以下值之一:SQLITE_CHANGESET_DATA:DELETE或UPDATE变更不包含预期的“之前”值。SQLITE_CHANGESET_NOTFOUND:与DELETE或UPDATE更改的主键匹配的行不存在。SQLITE_CHANGESET_CONFLICT:INSERT操作导致主键重复。SQLITE_CHANGESET_FOREIGN_KEY: 应用更改会导致外键冲突。SQLITE_CHANGESET_CONSTRAINT:应用更改会导致UNIQUE、CHECK或NOT NULL约束违规。
该函数应返回以下值之一:
SQLITE_CHANGESET_OMIT:省略冲突的更改。SQLITE_CHANGESET_REPLACE:用冲突的更改替换现有值(仅在SQLITE_CHANGESET_DATA或SQLITE_CHANGESET_CONFLICT冲突中有效)。SQLITE_CHANGESET_ABORT:在冲突时中止操作并回滚数据库。
当在冲突处理程序中抛出错误或从处理程序返回任何其他值时,应用更改集将被中止,数据库将回滚。
默认:一个返回
SQLITE_CHANGESET_ABORT的函数。
-
- 返回:<boolean> 变更集是否成功应用且未被中止。
如果数据库未打开,将抛出异常。此方法是 sqlite3changeset_apply() 的一个封装。
【An exception is thrown if the database is not
open. This method is a wrapper around sqlite3changeset_apply().】
const sourceDb = new DatabaseSync(':memory:');
const targetDb = new DatabaseSync(':memory:');
sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
const session = sourceDb.createSession();
const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
insert.run(1, 'hello');
insert.run(2, 'world');
const changeset = session.changeset();
targetDb.applyChangeset(changeset);
// Now that the changeset has been applied, targetDb contains the same data as sourceDb.
database[Symbol.dispose]()#>
关闭数据库连接。如果数据库连接已经关闭,则此操作不会产生任何效果。
【Closes the database connection. If the database connection is already closed then this is a no-op.】
类:Session#>
【Class: Session】
session.changeset()#>
- 返回:<Uint8Array> 可应用于其他数据库的二进制变更集。
检索自该变更集创建以来的所有更改的变更集。可以多次调用。如果数据库或会话未打开,将抛出异常。此方法是 sqlite3session_changeset() 的封装。
【Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times.
An exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_changeset().】
session.patchset()#>
- 返回:<Uint8Array> 可应用于其他数据库的二进制补丁集。
类似于上面的方法,但生成更紧凑的补丁集。请参见 SQLite 的文档中的 变更集和补丁集。如果数据库或会话未打开,将抛出异常。此方法是 sqlite3session_patchset() 的一个封装器。
【Similar to the method above, but generates a more compact patchset. See Changesets and Patchsets
in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a
wrapper around sqlite3session_patchset().】
session.close()。#>
【session.close().】
关闭会话。如果数据库或会话未打开,将抛出异常。此方法是对 sqlite3session_delete() 的封装。
【Closes the session. An exception is thrown if the database or the session is not open. This method is a
wrapper around sqlite3session_delete().】
类:StatementSync#>
【Class: StatementSync】
这个类表示一个单独的 准备好的声明。这个类不能通过其构造函数实例化。相反,实例是通过 database.prepare() 方法创建的。该类提供的所有 API 都是同步执行的。
【This class represents a single prepared statement. This class cannot be
instantiated via its constructor. Instead, instances are created via the
database.prepare() method. All APIs exposed by this class execute
synchronously.】
预处理语句是用于创建它的 SQL 的高效二进制表示。预处理语句是可参数化的,可以使用不同的绑定值多次调用。参数还可以提供对 SQL 注入 攻击的保护。因此,在处理用户输入时,比起手工编写的 SQL 字符串,预处理语句更为推荐。
【A prepared statement is an efficient binary representation of the SQL used to create it. Prepared statements are parameterizable, and can be invoked multiple times with different bound values. Parameters also offer protection against SQL injection attacks. For these reasons, prepared statements are preferred over hand-crafted SQL strings when handling user input.】
类:SQLTagStore#>
【Class: SQLTagStore】
此类表示用于存储预处理语句的单个 LRU(最近最少使用)缓存。
【This class represents a single LRU (Least Recently Used) cache for storing prepared statements.】
该类的实例是通过 database.createTagStore() 方法创建的,而不是使用构造函数。该存储会根据提供的 SQL 查询字符串缓存准备好的语句。当再次遇到相同的查询时,存储会检索缓存的语句,并通过参数绑定安全地应用新值,从而防止 SQL 注入等攻击。
【Instances of this class are created via the database.createTagStore() method, not by using a constructor. The store caches prepared statements based on the provided SQL query string. When the same query is seen again, the store retrieves the cached statement and safely applies the new values through parameter binding, thereby preventing attacks like SQL injection.】
缓存的最大容量(maxSize)默认是 1000 条语句,但可以提供自定义大小(例如,database.createTagStore(100))。该类提供的所有 API 都是同步执行的。
【The cache has a maxSize that defaults to 1000 statements, but a custom size can be provided (e.g., database.createTagStore(100)). All APIs exposed by this class execute synchronously.】
sqlTagStore.all(sqlTemplate[, ...values])#>
sqlTemplateTemplate Literal 一个包含 SQL 查询的模板字面量。...values<any> 要插入到模板字面量中的值。- 返回值:<Array> 一个对象数组,表示查询返回的行。
执行给定的 SQL 查询并将所有结果行作为对象数组返回。
【Executes the given SQL query and returns all resulting rows as an array of objects.】
sqlTagStore.get(sqlTemplate[, ...values])#>
sqlTemplateTemplate Literal 一个包含 SQL 查询的模板字面量。...values<any> 要插入到模板字面量中的值。- 返回值:<Object> | <undefined> 表示查询返回的第一行的对象,如果没有返回任何行,则为
undefined。
执行给定的 SQL 查询并返回结果行的第一个对象。
【Executes the given SQL query and returns the first resulting row as an object.】
sqlTagStore.iterate(sqlTemplate[, ...values])#>
sqlTemplateTemplate Literal 一个包含 SQL 查询的模板字面量。...values<any> 要插入到模板字面量中的值。- 返回:<Iterator> 一个迭代器,生成表示查询返回行的对象。
执行给定的 SQL 查询并返回结果行的迭代器。
【Executes the given SQL query and returns an iterator over the resulting rows.】
sqlTagStore.run(sqlTemplate[, ...values])#>
sqlTemplateTemplate Literal 一个包含 SQL 查询的模板字面量。...values<any> 要插入到模板字面量中的值。- 返回:<Object> 一个包含执行信息的对象,包括
changes和lastInsertRowid。
执行给定的 SQL 查询,该查询预计不会返回任何行(例如,INSERT、UPDATE、DELETE)。
【Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE).】
sqlTagStore.size()#>
- 返回:<integer> 当前缓存中的预处理语句数量。
一个只读属性,返回缓存中当前预处理语句的数量。
【A read-only property that returns the number of prepared statements currently in the cache.】
sqlTagStore.capacity#>
- 返回:<integer> 缓存可以容纳的最大预准备语句数量。
一个只读属性,返回缓存中可容纳的最大预处理语句数量。
【A read-only property that returns the maximum number of prepared statements the cache can hold.】
sqlTagStore.db#>
- DatabaseSync 创建此
SQLTagStore的DatabaseSync实例。
一个只读属性,返回与此 SQLTagStore 关联的 DatabaseSync 对象。
【A read-only property that returns the DatabaseSync object associated with this SQLTagStore.】
sqlTagStore.reset()#>
重置 LRU 缓存,清除所有已存储的预处理语句。
【Resets the LRU cache, clearing all stored prepared statements.】
sqlTagStore.clear()#>
sqlTagStore.reset() 的别名。
【An alias for sqlTagStore.reset().】
statement.all([namedParameters][, ...anonymousParameters])#>
namedParameters<Object> 一个可选对象,用于绑定命名参数。该对象的键用于配置映射。...anonymousParameters<null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> 零个或多个值,用于绑定到匿名参数。- 返回值:<Array> 一个对象数组。每个对象对应执行预处理语句返回的一行。每个对象的键和值对应该行的列名和列值。
此方法执行一个预处理语句,并将所有结果作为对象数组返回。如果预处理语句没有返回任何结果,则此方法返回一个空数组。预处理语句 参数已绑定 使用 namedParameters 和 anonymousParameters 中的值。
【This method executes a prepared statement and returns all results as an array of
objects. If the prepared statement does not return any results, this method
returns an empty array. The prepared statement parameters are bound using
the values in namedParameters and anonymousParameters.】
statement.columns()#>
- 返回值:<Array> 一个对象数组。每个对象对应于预处理语句中的一列,并包含以下属性:
column<string> | <null> 原始表中列的未别名名称,如果该列是表达式或子查询的结果,则为null。此属性是sqlite3_column_origin_name()的结果。database<string> | <null> 源数据库的未别名名称,如果列是表达式或子查询的结果,则为null。此属性是sqlite3_column_database_name()的结果。name<string> 在SELECT语句的结果集中分配给列的名称。该属性是sqlite3_column_name()的结果。table<string> | <null> 源表的未别名名称,如果列是表达式或子查询的结果,则为null。此属性是sqlite3_column_table_name()的结果。type<string> | <null> 列声明的数据类型,如果列是表达式或子查询的结果,则为null。该属性是sqlite3_column_decltype()的结果。
此方法用于检索关于预处理语句返回的列的信息。
【This method is used to retrieve information about the columns returned by the prepared statement.】
statement.expandedSQL#>
- 类型:<string> 源 SQL 已扩展以包含参数值。
准备语句的源 SQL 文本,其中的参数占位符已被在最近一次执行此准备语句时使用的值所替换。此属性是 sqlite3_expanded_sql() 的一个封装。
【The source SQL text of the prepared statement with parameter
placeholders replaced by the values that were used during the most recent
execution of this prepared statement. This property is a wrapper around
sqlite3_expanded_sql().】
statement.get([namedParameters][, ...anonymousParameters])#>
namedParameters<Object> 一个可选对象,用于绑定命名参数。该对象的键用于配置映射。...anonymousParameters<null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> 零个或多个值,用于绑定到匿名参数。- 返回值:<Object> | <undefined> 执行准备语句后返回的第一行对应的对象。该对象的键和值分别对应行的列名和列值。如果数据库没有返回任何行,则此方法返回
undefined。
此方法执行一个预处理语句并返回第一个结果作为对象。如果预处理语句没有返回任何结果,该方法返回 undefined。预处理语句 参数已绑定 使用 namedParameters 和 anonymousParameters 中的值。
【This method executes a prepared statement and returns the first result as an
object. If the prepared statement does not return any results, this method
returns undefined. The prepared statement parameters are bound using the
values in namedParameters and anonymousParameters.】
statement.iterate([namedParameters][, ...anonymousParameters])#>
namedParameters<Object> 一个可选对象,用于绑定命名参数。该对象的键用于配置映射。...anonymousParameters<null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> 零个或多个值,用于绑定到匿名参数。- 返回:<Iterator> 可迭代对象的迭代器。每个对象对应执行准备语句后返回的一行数据。每个对象的键和值对应该行的列名和值。
此方法执行一个预处理语句并返回一个对象迭代器。如果预处理语句没有返回任何结果,该方法将返回一个空的迭代器。预处理语句 参数已绑定 使用 namedParameters 和 anonymousParameters 中的值。
【This method executes a prepared statement and returns an iterator of
objects. If the prepared statement does not return any results, this method
returns an empty iterator. The prepared statement parameters are bound using
the values in namedParameters and anonymousParameters.】
statement.run([namedParameters][, ...anonymousParameters])#>
namedParameters<Object> 一个可选对象,用于绑定命名参数。该对象的键用于配置映射。...anonymousParameters<null> | <number> | <bigint> | <string> | <Buffer> | <TypedArray> | <DataView> 零个或多个值,用于绑定到匿名参数。- 返回:<Object>
changes<number> | <bigint> 最近完成的INSERT、UPDATE或DELETE语句所修改、插入或删除的行数。该字段根据预处理语句的配置,可以是数字或BigInt。该属性是sqlite3_changes64()的结果。lastInsertRowid<number> | <bigint> 最近插入的 rowid。根据预处理语句的配置,该字段可以是数字或BigInt。此属性是sqlite3_last_insert_rowid()的结果。
此方法执行一个预处理语句,并返回一个总结结果更改的对象。预处理语句 参数已绑定 使用 namedParameters 和 anonymousParameters 中的值。
【This method executes a prepared statement and returns an object summarizing the
resulting changes. The prepared statement parameters are bound using the
values in namedParameters and anonymousParameters.】
statement.setAllowBareNamedParameters(enabled)#>
enabled<boolean> 启用或禁用对绑定命名参数(无需前缀字符)的支持。
SQLite 参数的名称以前缀字符开头。默认情况下,node:sqlite 要求在绑定参数时必须出现该前缀字符。然而,除了美元符号字符之外,当这些前缀字符用作对象键时,还需要额外的引号。
【The names of SQLite parameters begin with a prefix character. By default,
node:sqlite requires that this prefix character is present when binding
parameters. However, with the exception of dollar sign character, these
prefix characters also require extra quoting when used in object keys.】
为了改善人机工程学,这种方法还可以用于允许裸命名参数,这些参数在 JavaScript 代码中不需要前缀字符。在启用裸命名参数时,需要注意几个事项:
【To improve ergonomics, this method can be used to also allow bare named parameters, which do not require the prefix character in JavaScript code. There are several caveats to be aware of when enabling bare named parameters:】
- 在 SQL 中仍然需要前缀字符。
- 在 JavaScript 中仍然允许使用前缀字符。事实上,带前缀的名称绑定性能会略好一些。
- 在同一准备语句中使用模糊命名参数,如
$k和@k,将导致异常,因为无法确定如何绑定一个裸名称。
statement.setAllowUnknownNamedParameters(enabled)#>
enabled<boolean> 启用或禁用对未知命名参数的支持。
默认情况下,如果在绑定参数时遇到未知名称,将抛出异常。此方法允许忽略未知的命名参数。
【By default, if an unknown name is encountered while binding parameters, an exception is thrown. This method allows unknown named parameters to be ignored.】
statement.setReturnArrays(enabled)#>
enabled<boolean> 启用或禁用将查询结果作为数组返回。
启用后,通过 all()、get() 和 iterate() 方法返回的查询结果将以数组形式返回,而不是对象形式。
【When enabled, query results returned by the all(), get(), and iterate() methods will be returned as arrays instead
of objects.】
statement.setReadBigInts(enabled)#>
enabled<boolean> 启用或禁用在从数据库读取INTEGER字段时使用BigInt。
从数据库读取时,SQLite 的 INTEGER 默认会映射为 JavaScript 数字。然而,SQLite 的 INTEGER 可以存储比 JavaScript 数字能够表示的更大的值。在这种情况下,可以使用此方法通过 JavaScript BigInt 来读取 INTEGER 数据。此方法不会影响数据库的写操作,因为数字和 BigInt 在任何时候都是支持的。
【When reading from the database, SQLite INTEGERs are mapped to JavaScript
numbers by default. However, SQLite INTEGERs can store values larger than
JavaScript numbers are capable of representing. In such cases, this method can
be used to read INTEGER data using JavaScript BigInts. This method has no
impact on database write operations where numbers and BigInts are both
supported at all times.】
statement.sourceSQL#>
- 类型:<string> 用于创建此预处理语句的源 SQL。
预处理语句的源 SQL 文本。此属性是对 sqlite3_sql() 的封装。
【The source SQL text of the prepared statement. This property is a
wrapper around sqlite3_sql().】
JavaScript 和 SQLite 之间的类型转换#>
【Type conversion between JavaScript and SQLite】
当 Node.js 向 SQLite 写入或从 SQLite 读取数据时,有必要在 JavaScript 数据类型和 SQLite 的 数据类型 之间进行转换。由于 JavaScript 支持的数据类型比 SQLite 多,因此只支持 JavaScript 类型的一个子集。试图向 SQLite 写入不受支持的数据类型会导致异常。
【When Node.js writes to or reads from SQLite it is necessary to convert between JavaScript data types and SQLite's data types. Because JavaScript supports more data types than SQLite, only a subset of JavaScript types are supported. Attempting to write an unsupported data type to SQLite will result in an exception.】
| SQLite | JavaScript |
|---|---|
NULL | <null> |
INTEGER | <number> 或 <bigint> |
REAL | <number> |
TEXT | <string> |
BLOB | <TypedArray> 或 <DataView> |
sqlite.backup(sourceDb, path[, options])#>
sourceDbDatabaseSync 要备份的数据库。源数据库必须打开。path<string> | <Buffer> | <URL> 将创建备份的路径。如果文件已存在,其内容将被覆盖。options<Object> 备份的可选配置。支持以下属性:source<string> 源数据库的名称。可以是'main'(默认主数据库)或任何已使用ATTACH DATABASE添加的其他数据库。默认值:'main'。target<string> 目标数据库的名称。可以是'main'(默认的主数据库),也可以是通过ATTACH DATABASE添加的其他数据库。默认值:'main'。rate<number> 每批备份要传输的页面数量。默认值:100。progress<Function> 一个可选的回调函数,在每个备份步骤完成后调用。传递给此回调的参数是一个 <Object>,包含remainingPages和totalPages属性,用于描述备份操作的当前进度。
- 返回值:<Promise> 一个在完成时返回备份页面总数的 Promise,如果发生错误则拒绝。
此方法用于进行数据库备份。此方法对 sqlite3_backup_init()、sqlite3_backup_step() 和 sqlite3_backup_finish() 功能进行了抽象。
【This method makes a database backup. This method abstracts the sqlite3_backup_init(), sqlite3_backup_step()
and sqlite3_backup_finish() functions.】
在备份过程中,已备份的数据库可以正常使用。来自同一连接——相同的 DatabaseSync——对象的修改会立即反映在备份中。但是,来自其他连接的修改会导致备份过程重启。
【The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same DatabaseSync - object will be reflected in the backup right away. However, mutations from other connections will cause the backup process to restart.】
const { backup, DatabaseSync } = require('node:sqlite');
(async () => {
const sourceDb = new DatabaseSync('source.db');
const totalPagesTransferred = await backup(sourceDb, 'backup.db', {
rate: 1, // Copy one page at a time.
progress: ({ totalPages, remainingPages }) => {
console.log('Backup in progress', { totalPages, remainingPages });
},
});
console.log('Backup completed', totalPagesTransferred);
})();import { backup, DatabaseSync } from 'node:sqlite';
const sourceDb = new DatabaseSync('source.db');
const totalPagesTransferred = await backup(sourceDb, 'backup.db', {
rate: 1, // Copy one page at a time.
progress: ({ totalPages, remainingPages }) => {
console.log('Backup in progress', { totalPages, remainingPages });
},
});
console.log('Backup completed', totalPagesTransferred);
sqlite.constants#>
- 类型: <Object>
包含 SQLite 操作常用常量的对象。
【An object containing commonly used constants for SQLite operations.】
SQLite 常量#>
【SQLite constants】
sqlite.constants 对象导出了以下常量。
【The following constants are exported by the sqlite.constants object.】
冲突解决常量#>
【Conflict resolution constants】
以下常量之一可以作为传递给 database.applyChangeset() 的 onConflict 冲突解决处理程序的参数。另请参阅 SQLite 文档中的 传递给冲突处理程序的常量。
【One of the following constants is available as an argument to the onConflict
conflict resolution handler passed to database.applyChangeset(). See also
Constants Passed To The Conflict Handler in the SQLite documentation.】
| Constant | Description |
|---|---|
SQLITE_CHANGESET_DATA |
The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. |
SQLITE_CHANGESET_NOTFOUND |
The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. |
SQLITE_CHANGESET_CONFLICT |
This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. |
SQLITE_CHANGESET_CONSTRAINT |
If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns SQLITE_CHANGESET_OMIT, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns SQLITE_CHANGESET_ABORT, the changeset is rolled back. |
SQLITE_CHANGESET_FOREIGN_KEY |
If any other constraint violation occurs while applying a change (i.e. a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is invoked with this constant. |
必须从传递给 database.applyChangeset() 的 onConflict 冲突解决处理程序中返回以下常量之一。另请参见 SQLite 文档中的 来自冲突处理程序的常量。
【One of the following constants must be returned from the onConflict conflict
resolution handler passed to database.applyChangeset(). See also
Constants Returned From The Conflict Handler in the SQLite documentation.】
| 常量 | 描述 |
|---|---|
SQLITE_CHANGESET_OMIT |
冲突的更改将被忽略。 |
SQLITE_CHANGESET_REPLACE |
冲突的更改将替换现有值。请注意,当冲突类型为 SQLITE_CHANGESET_DATA 或 SQLITE_CHANGESET_CONFLICT 时才可以返回此值。 |
SQLITE_CHANGESET_ABORT |
在更改遇到冲突时中止,并回滚数据库。 |
授权常量#>
【Authorization constants】
以下常量用于 database.setAuthorizer() 方法。
【The following constants are used with the database.setAuthorizer() method.】
授权结果代码#>
【Authorization result codes】
必须从传递给 database.setAuthorizer() 的授权回调函数返回以下常量之一。
【One of the following constants must be returned from the authorizer callback
function passed to database.setAuthorizer().】
| 常量 | 说明 |
|---|---|
SQLITE_OK |
允许操作正常进行。 |
SQLITE_DENY |
拒绝操作并返回错误。 |
SQLITE_IGNORE |
忽略操作并继续,就像从未请求过一样。 |
授权操作代码#>
【Authorization action codes】
以下常量作为第一个参数传递给授权器回调函数,用于指示正在授权的操作类型。
【The following constants are passed as the first argument to the authorizer callback function to indicate what type of operation is being authorized.】
| Constant | Description |
|---|---|
SQLITE_CREATE_INDEX |
Create an index |
SQLITE_CREATE_TABLE |
Create a table |
SQLITE_CREATE_TEMP_INDEX |
Create a temporary index |
SQLITE_CREATE_TEMP_TABLE |
Create a temporary table |
SQLITE_CREATE_TEMP_TRIGGER |
Create a temporary trigger |
SQLITE_CREATE_TEMP_VIEW |
Create a temporary view |
SQLITE_CREATE_TRIGGER |
Create a trigger |
SQLITE_CREATE_VIEW |
Create a view |
SQLITE_DELETE |
Delete from a table |
SQLITE_DROP_INDEX |
Drop an index |
SQLITE_DROP_TABLE |
Drop a table |
SQLITE_DROP_TEMP_INDEX |
Drop a temporary index |
SQLITE_DROP_TEMP_TABLE |
Drop a temporary table |
SQLITE_DROP_TEMP_TRIGGER |
Drop a temporary trigger |
SQLITE_DROP_TEMP_VIEW |
Drop a temporary view |
SQLITE_DROP_TRIGGER |
Drop a trigger |
SQLITE_DROP_VIEW |
Drop a view |
SQLITE_INSERT |
Insert into a table |
SQLITE_PRAGMA |
Execute a PRAGMA statement |
SQLITE_READ |
Read from a table |
SQLITE_SELECT |
Execute a SELECT statement |
SQLITE_TRANSACTION |
Begin, commit, or rollback a transaction |
SQLITE_UPDATE |
Update a table |
SQLITE_ATTACH |
Attach a database |
SQLITE_DETACH |
Detach a database |
SQLITE_ALTER_TABLE |
Alter a table |
SQLITE_REINDEX |
Reindex |
SQLITE_ANALYZE |
Analyze the database |
SQLITE_CREATE_VTABLE |
Create a virtual table |
SQLITE_DROP_VTABLE |
Drop a virtual table |
SQLITE_FUNCTION |
Use a function |
SQLITE_SAVEPOINT |
Create, release, or rollback a savepoint |
SQLITE_COPY |
Copy data (legacy) |
SQLITE_RECURSIVE |
Recursive query |