- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- bench 基准测试运行器
- 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 文件系统
- FFI 外部函数接口
- 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/iter 可迭代流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vfs 虚拟文件系统
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- zlib/iter 可迭代压缩
Node.js v26.11.1 文档
- Node.js v26.11.1
-
目录
- SQLite
- JavaScript 和 SQLite 之间的类型转换
- 类:
Databasenew Database(path[, options])database.aggregate(name, options)database.close()database.loadExtension(path[, entryPoint])database.enableLoadExtension(allow)database.enableDefensive(active)database.location([dbName])database.exec(sql)database.function(name[, options], fn)database.setAuthorizer(callback)database.isOpendatabase.isTransactiondatabase.limitsdatabase.open()database.serialize([dbName])database.deserialize(buffer[, options])database.prepare(sql[, options])database.createTagStore([maxSize])database.createModule(name, options)database.createSession([options])database.applyChangeset(changeset[, options])database[Symbol.dispose]()
- 类:
Session - 类:
Statement- 绑定参数
statement.all([namedParameters][, ...anonymousParameters])statement.close()statement.columns()statement.expandedSQLstatement.get([namedParameters][, ...anonymousParameters])statement.iterate([namedParameters][, ...anonymousParameters])statement.resetStats()statement.run([namedParameters][, ...anonymousParameters])statement.setAllowBareNamedParameters(enabled)statement.setAllowUnknownNamedParameters(enabled)statement.setReturnArrays(enabled)statement.setReadBigInts(enabled)statement.sourceSQLstatement[Symbol.dispose]()statement.stat(counter)
- 类:
SQLTagStore sqlite.backup(sourceDb, path[, options])sqlite.constants
- SQLite
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- bench 基准测试运行器
- 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 文件系统
- FFI 外部函数接口
- 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/iter 可迭代流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vfs 虚拟文件系统
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- zlib/iter 可迭代压缩
- 其他版本
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: 方案下可用。可以通过 diagnostics_channel 模块观察 SQL 跟踪事件。详情请参见 'sqlite.db.query'。
🌐 This module is only available under the node: scheme. SQL trace events can
be observed via the diagnostics_channel module. See
'sqlite.db.query' for details.
下面的示例展示了 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 { Database } from 'node:sqlite';
const database = new Database(':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');
// Finalize the prepared statement once it is no longer needed.
insert.close();
// 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' } ]
query.close();const { Database } = require('node:sqlite');
const database = new Database(':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');
// Finalize the prepared statement once it is no longer needed.
insert.close();
// 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' } ]
query.close();
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.
| 存储类 | JavaScript 到 SQLite | SQLite 到 JavaScript |
|---|---|---|
NULL | <null> 或 <undefined> | <null> |
INTEGER | <number>、<bigint> 或 <boolean> | <number> 或 <bigint> (可配置) |
REAL | <number> | <number> |
TEXT | <string> | <string> |
BLOB | <TypedArray>、<DataView>、<ArrayBuffer> 或 <SharedArrayBuffer> | <Uint8Array> |
布尔值写作 INTEGER 值 1 和 0。像其他 INTEGER 值一样,它们默认会被读取为 <number>,当启用读取 BigInt 时会被读取为 <bigint> 值(1n 和 0n)。写入一个不适合有符号 64 位整数的 <bigint> 会抛出 ERR_INVALID_ARG_VALUE 错误。
🌐 Booleans are written as the INTEGER values 1 and 0. Like any other
INTEGER value, they are read back as <number> by default, or as <bigint>
values (1n and 0n) when reading BigInts is enabled. Writing a <bigint> that
does not fit in a signed 64-bit integer throws an ERR_INVALID_ARG_VALUE
error.
undefined 被写作 NULL,所以显式传递它等同于省略命名参数。NULL 总是读取回 <null>,从不为 undefined。
从 SQLite 读取值的 API 有一个配置选项,用于确定 INTEGER 值在 JavaScript 中是转换为 number 还是 bigint,例如语句的 readBigInts 选项和用户自定义函数的 useBigIntArguments 选项。如果 Node.js 从 SQLite 读取一个超出 JavaScript 安全整数 范围的 INTEGER 值,且未启用读取 BigInts 的选项,那么将抛出 ERR_OUT_OF_RANGE 错误。
🌐 APIs that read values from SQLite have a configuration option that determines
whether INTEGER values are converted to number or bigint in JavaScript,
such as the readBigInts option for statements and the useBigIntArguments
option for user-defined functions. If Node.js reads an INTEGER value from
SQLite that is outside the JavaScript safe integer range, and the option to
read BigInts is not enabled, then an ERR_OUT_OF_RANGE error will be thrown.
类:Database#>
🌐 Class: Database
该类表示到 SQLite 数据库的单个 连接。该类提供的所有 API 都是同步执行的。
🌐 This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.
DatabaseSync 是 Database 的过时别名,为了与类的以前名称保持向后兼容而保留。参见 DEP0210。
new Database(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。defensive<boolean> 如果true,则启用防御标志。启用防御标志后,允许普通 SQL 故意破坏数据库文件的语言功能将被禁用。防御标志也可以使用enableDefensive()设置。默认值:true。limits<Object> 各种 SQLite 限制的配置。这些限制可以用于防止在处理可能的恶意输入时消耗过多资源。有关详细信息,请参见 SQLite 文档中的 运行时限制 和 极限常量。默认值由 SQLite 的编译时默认值确定,并可能因 SQLite 的构建方式而异。支持以下属性:length<number> 字符串或 BLOB 的最大长度。sqlLength<number> SQL 语句的最大长度。column<number> 最大列数。exprDepth<number> 表达树的最大深度。compoundSelect<number> 复合 SELECT 中的最大条款数。vdbeOp<number> VDBE 指令的最大数量。functionArg<number> 函数参数的最大数量。attach<number> 附加数据库的最大数量。likePatternLength<number> LIKE 模式的最大长度。variableNumber<number> SQL 变量的最大数量。triggerDepth<number> 最大触发递归深度。
构建一个新的 Database 实例。
🌐 Constructs a new Database 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个参数调用,并且它们的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 { Database } = require('node:sqlite');
const db = new Database(':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,
});
using query = db.prepare('SELECT sumint(y) as total FROM t3');
query.get(); // { total: 21 }import { Database } from 'node:sqlite';
const db = new Database(':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,
});
using query = db.prepare('SELECT sumint(y) as total FROM t3');
query.get(); // { total: 21 }
database.close()#>
关闭数据库连接。如果数据库未打开,则会抛出异常。如果在执行语句时调用此方法(例如在用户定义函数、聚合函数、授权回调或 'sqlite.db.query' 订阅者内部),将抛出 ERR_INVALID_STATE 错误。此方法是 sqlite3_close_v2() 的一个封装。
🌐 Closes the database connection. An exception is thrown if the database is not
open. An ERR_INVALID_STATE error is thrown if the method is called while
a statement is executing, such as inside a user-defined function, an aggregate
function, an authorizer callback, or a 'sqlite.db.query' subscriber. This
method is a wrapper around sqlite3_close_v2().
database.loadExtension(path[, entryPoint])#>
path<string> 要加载的共享库路径。entryPoint<string> 扩展入口点函数的名称。省略时,SQLite 会从共享库的文件名推导入口点;当推导的名称不匹配时,请显式传入此参数。
将共享库加载到数据库连接中。此方法是 sqlite3_load_extension() 的一个封装。在构建 Database 实例时,需要启用 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 Database instance.
import { Database } from 'node:sqlite';
const database = new Database(':memory:', { allowExtension: true });
// Load using the entry point derived from the filename.
database.loadExtension('./decimal.dylib');
// Override the entry point when the derived name does not match.
database.loadExtension('./base64.dylib', 'sqlite3_base64_init');const { Database } = require('node:sqlite');
const database = new Database(':memory:', { allowExtension: true });
// Load using the entry point derived from the filename.
database.loadExtension('./decimal.dylib');
// Override the entry point when the derived name does not match.
database.loadExtension('./base64.dylib', 'sqlite3_base64_init');
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.enableDefensive(active)#>
active<boolean> 是否设置防御标志。
启用或禁用防御标志。当防御标志激活时,允许普通 SQL 故意破坏数据库文件的语言功能将被禁用。有关详细信息,请参见 SQLite 文档中的 SQLITE_DBCONFIG_DEFENSIVE。
🌐 Enables or disables the defensive flag. When the defensive flag is active,
language features that allow ordinary SQL to deliberately corrupt the database file are disabled.
See SQLITE_DBCONFIG_DEFENSIVE in the SQLite documentation for details.
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], fn)#>
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。
fn<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- 忽略此操作(静默跳过)。
SQLite 要求授权回调不能修改调用它的数据库连接,这包括准备和执行语句。当回调在栈上时,任何会这么做的方法都会抛出代码为 ERR_INVALID_STATE 的错误,包括 database.prepare()、database.exec()、该连接语句的执行方法、迭代器和标签存储,以及 database.setAuthorizer() 本身。其他连接仍然可以使用。
🌐 SQLite requires that the authorizer callback not modify the database connection
that invoked it, which includes preparing and stepping statements. Methods that
would do so throw an error with code ERR_INVALID_STATE while the callback is
on the stack, including database.prepare(), database.exec(), the execution
methods of that connection's statements, iterators, and tag stores, and
database.setAuthorizer() itself. Other connections remain usable.
回调也可以在 statement.run()、statement.get() 和类似方法内部调用,因为 SQLite 在执行过程中可能会在模式更改后重新准备语句。
🌐 The callback can also be invoked from within statement.run(),
statement.get(), and similar methods, because SQLite may re-prepare a
statement during execution after a schema change.
另外,目前正在执行的语句不能被重新进入。调用 statement.close() 会释放正在运行的虚拟机,而通过 statement.run()、statement.get()、statement.all()、statement.iterate()、iterator.next()、iterator.return() 或等效的标签存储方法重新运行它,会在执行中重置该虚拟机。所有这些操作都会抛出 ERR_INVALID_STATE 错误。这适用于 SQLite 在执行过程中调用的任何回调,比如用户自定义函数。连接上的其他语句仍然可以使用。
🌐 Separately, a statement that is currently being executed cannot be reentered.
Calling statement.close() on it would free the virtual machine that is
running, and re-running it through statement.run(), statement.get(),
statement.all(), statement.iterate(), iterator.next(),
iterator.return(), or the equivalent tag store methods would reset that
virtual machine mid-execution. All of these throw an ERR_INVALID_STATE error
instead. This applies to any callback SQLite invokes during execution, such as a
user-defined function. Other statements on the connection remain usable.
不涉及任何 SQLite 状态的操作仍可从回调中使用:sqlTagStore.clear(),它只会清除缓存的语句;以及在已耗尽的迭代器上使用的 next() 和 return(),它们会继续返回 { done: true }。
🌐 Operations that touch no SQLite state stay available from the callback:
sqlTagStore.clear(), which only drops cached statements, and next() and
return() on an already-drained iterator, which keep returning
{ done: true }.
const { Database, constants } = require('node:sqlite');
const db = new Database(':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
using query = db.prepare('SELECT 1');
query.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 { Database, constants } from 'node:sqlite';
const db = new Database(':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
using query = db.prepare('SELECT 1');
query.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.limits#>
- 类型:<Object>
用于在运行时获取和设置 SQLite 数据库限制的对象。每个属性对应一个 SQLite 限制,可以读取或写入。
🌐 An object for getting and setting SQLite database limits at runtime. Each property corresponds to an SQLite limit and can be read or written.
const db = new Database(':memory:');
// Read current limit
console.log(db.limits.length);
// Set a new limit
db.limits.sqlLength = 100000;
// Reset a limit to its compile-time maximum
db.limits.sqlLength = Infinity;
可用属性:length、sqlLength、column、exprDepth、compoundSelect、vdbeOp、functionArg、attach、likePatternLength、variableNumber、triggerDepth。
🌐 Available properties: length, sqlLength, column, exprDepth,
compoundSelect, vdbeOp, functionArg, attach, likePatternLength,
variableNumber, triggerDepth.
将属性设置为 Infinity 会将限制重置为其编译时的最大值。
🌐 Setting a property to Infinity resets the limit to its compile-time maximum value.
database.open()#>
打开在 Database 构造函数的 path 参数中指定的数据库。只有在数据库没有通过构造函数打开时才应使用此方法。如果数据库已经打开,将抛出异常。
🌐 Opens the database specified in the path argument of the Database
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.serialize([dbName])#>
dbName<string> 要序列化的数据库名称。这可以是'main'(默认的主数据库)或任何已通过ATTACH DATABASE添加的其他数据库。默认值:'main'。- 返回:<Uint8Array> 数据库的二进制表示。
将数据库序列化为二进制表示,返回为 Uint8Array。这对于保存、克隆或传输内存中的数据库非常有用。此方法是 sqlite3_serialize() 的封装器。
🌐 Serializes the database into a binary representation, returned as a
Uint8Array. This is useful for saving, cloning, or transferring an in-memory
database. This method is a wrapper around sqlite3_serialize().
import { Database } from 'node:sqlite';
const db = new Database(':memory:');
db.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');
db.exec("INSERT INTO t VALUES (1, 'hello')");
const buffer = db.serialize();
console.log(buffer.length); // Prints the byte length of the databaseconst { Database } = require('node:sqlite');
const db = new Database(':memory:');
db.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');
db.exec("INSERT INTO t VALUES (1, 'hello')");
const buffer = db.serialize();
console.log(buffer.length); // Prints the byte length of the database
database.deserialize(buffer[, options])#>
buffer<Uint8Array> 数据库的二进制表示,例如database.serialize()的输出。options<Object> 反序列化的可选配置。dbName<string> 要反序列化到的数据库名称。 默认值:'main'。
将序列化的数据库加载到此连接中,替换当前数据库。反序列化后的数据库是可写的。在尝试反序列化之前,会先完成现有的预处理语句,即使操作随后失败。如果在数据库回调堆栈上调用此方法(例如用户定义函数、聚合函数、授权器或变更集过滤器或冲突处理器),会抛出 ERR_INVALID_STATE 错误。此方法是 sqlite3_deserialize() 的一个封装。
🌐 Loads a serialized database into this connection, replacing the current
database. The deserialized database is writable. Existing prepared statements
are finalized before deserialization is attempted, even if the operation
subsequently fails. An ERR_INVALID_STATE error is thrown if the method is
called while a database callback is on the stack, for example a user-defined
function, an aggregate function, an authorizer, or a changeset filter or conflict
handler. This method is a wrapper around sqlite3_deserialize().
import { Database } from 'node:sqlite';
const original = new Database(':memory:');
original.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');
original.exec("INSERT INTO t VALUES (1, 'hello')");
const buffer = original.serialize();
original.close();
const clone = new Database(':memory:');
clone.deserialize(buffer);
using query = clone.prepare('SELECT value FROM t');
console.log(query.get());
// Prints: { value: 'hello' }const { Database } = require('node:sqlite');
const original = new Database(':memory:');
original.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');
original.exec("INSERT INTO t VALUES (1, 'hello')");
const buffer = original.serialize();
original.close();
const clone = new Database(':memory:');
clone.deserialize(buffer);
using query = clone.prepare('SELECT value FROM t');
console.log(query.get());
// Prints: { value: 'hello' }
database.prepare(sql[, options])#>
sql<string> 用于编译为预处理语句的 SQL 字符串。options<Object> 为预处理语句提供的可选配置。readBigInts<boolean> 如果true,整数字段将被读取为BigInt。 默认值: 继承自数据库选项或false。returnArrays<boolean> 如果true,结果将作为数组返回。 默认值: 继承自数据库选项或false。allowBareNamedParameters<boolean> 如果true,允许绑定命名参数而无需前缀字符。**默认值:**继承自数据库选项或true。allowUnknownNamedParameters<boolean> 如果true,未知的命名参数将被忽略。**默认值:**继承自数据库选项或false。persistent<boolean> 如果true,会提示 SQLite 该语句将被长时间保留并可能多次重用。SQLite 当前通过避免使用旁路内存来响应该提示。对应SQLITE_PREPARE_PERSISTENT标志。默认值:false。
- 返回:Statement 准备好的声明。
将 SQL 语句编译成 准备好的声明。此方法是 sqlite3_prepare_v3() 的一个封装。
🌐 Compiles a SQL statement into a prepared statement. This method is a wrapper
around sqlite3_prepare_v3().
database.createTagStore([maxSize])#>
maxSize<integer> 要缓存的最大预处理语句数量。默认值:1000。- 返回:SQLTagStore 一个用于缓存预处理语句的新 SQL 标签存储。
创建一个新的 SQLTagStore,这是一个用于存储预处理语句的最近最少使用(LRU)缓存。通过为预处理语句分配唯一标识符,这可以实现预处理语句的高效重用。
🌐 Creates a new SQLTagStore, which is a Least Recently Used (LRU) 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 the corresponding SQL query 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.
标记语句将模板字面量中的占位符值绑定为底层预处理语句的参数。例如:
🌐 Tagged statements bind the placeholder values from the template literal as parameters to the underlying prepared statement. For example:
sqlTagStore.get`SELECT ${value}`;
等同于:
🌐 is equivalent to:
using statement = db.prepare('SELECT ?');
statement.get(value);
然而,在第一个例子中,标签存储将会缓存底层的预编译语句以供将来使用。
🌐 However, in the first example, the tag store will cache the underlying prepared statement for future use.
注意: 在带标记的语句中,
${value}语法将参数 绑定 到预处理语句。这与其在 无标记 模板字面量中的行为不同,在无标记模板字面量中,它执行字符串插值。// This a safe example of binding a parameter to a tagged statement. sqlTagStore.run`INSERT INTO t1 (id) VALUES (${id})`; // This is an *unsafe* example of an untagged template string. // `id` is interpolated into the query text as a string. // This can lead to SQL injection and data corruption. db.run(`INSERT INTO t1 (id) VALUES (${id})`);
如果查询字符串(包括任何绑定占位符的位置)完全相同,标签存储将匹配缓存中的语句。
🌐 The tag store will match a statement from the cache if the query strings (including the positions of any bound placeholders) are identical.
// The following statements will match in the cache:
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${12345} AND active = 1`;
// The following statements will not match, as the query strings
// and bound placeholders differ:
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;
sqlTagStore.get`SELECT * FROM t1 WHERE id = 12345 AND active = 1`;
// The following statements will not match, as matches are case-sensitive:
sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;
sqlTagStore.get`select * from t1 where id = ${id} and active = 1`;
在标记语句中绑定参数的唯一方法是使用 ${value} 语法。不要在 SQL 查询字符串本身中添加参数绑定占位符(如 ? 等)。
🌐 The only way of binding parameters in tagged statements is with the ${value}
syntax. Do not add parameter binding placeholders (? etc.) to the SQL query
string itself.
import { Database } from 'node:sqlite';
const db = new Database(':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 name = 'Alice';
const user = sql.get`SELECT * FROM users WHERE name = ${name}`;
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' }
// ]const { Database } = require('node:sqlite');
const db = new Database(':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 name = 'Alice';
const user = sql.get`SELECT * FROM users WHERE name = ${name}`;
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.createModule(name, options)#>
name<string> 虚拟表模块的名称。这个名称用于CREATE VIRTUAL TABLE ... USING name语句中,并且用作同名表的名称。options<Object> 模块配置设置。columns<Array> 一组列定义数组。每个元素都是一个对象,具有以下属性:rows<Function> 当虚拟表被查询时,会调用一个函数来生成行。该函数会接收隐藏列(参数)的值作为参数,顺序按照它们被定义的顺序。必须返回一个可迭代对象(比如数组或生成器),其中每个元素都是一组列值数组。directOnly<boolean> 如果true,虚拟表只能在顶层 SQL 语句中使用,不能在触发器或视图中使用。 默认值:false。useBigIntArguments<boolean> 如果true,传递给rows的整数参数会被转换为BigInt。默认值:false。
在数据库中注册一个虚拟表模块。这个方法是 sqlite3_create_module_v2() 的一个封装。虚拟表允许 JavaScript 代码为 SQL 表提供后台数据。注册的模块可以有两种使用方式:
🌐 Registers a virtual table module with the database. This method is a wrapper
around sqlite3_create_module_v2(). Virtual tables allow JavaScript code
to provide the backing data for SQL tables. The registered module can be used
in two ways:
- 同名表:直接查询模块名称而不创建表(例如,
SELECT * FROM module_name)。 - 命名虚拟表:使用
CREATE VIRTUAL TABLE t USING module_name来创建一个持久的虚拟表。
隐藏列可以用来通过表值函数语法(例如 SELECT * FROM module_name(param1, param2))向 rows 函数传递参数。
🌐 Hidden columns can be used to pass parameters to the rows function using
table-valued function syntax (e.g., SELECT * FROM module_name(param1, param2)).
rows 产生的值遵循 JavaScript 和 SQLite 之间的类型转换 中的转换规则:一个 <number> 被存储为 REAL,一个 <bigint> 被存储为 INTEGER,不管列声明的 type 是什么。和普通表不一样,虚拟表不会对返回的值应用列类型偏好,所以在某列需要 INTEGER 存储时,返回一个 <bigint>:
🌐 Values yielded by rows follow the conversion rules in Type conversion between
JavaScript and SQLite: a <number> is stored as REAL and a <bigint> is
stored as INTEGER, regardless of the column's declared type. Unlike an
ordinary table, a virtual table does not apply column affinity to the values it
returns, so yield a <bigint> when a column needs INTEGER storage:
db.createModule('counter', {
columns: [{ name: 'value', type: 'INTEGER' }],
*rows() {
yield [1]; // typeof(value) is 'real'
yield [2n]; // typeof(value) is 'integer'
},
});
const { Database } = require('node:sqlite');
const db = new Database(':memory:');
db.createModule('generate_series', {
columns: [
{ name: 'value', type: 'INTEGER' },
{ name: 'start', type: 'INTEGER', hidden: true },
{ name: 'stop', type: 'INTEGER', hidden: true },
{ name: 'step', type: 'INTEGER', hidden: true },
],
*rows(start, stop, step) {
start ??= 0;
stop ??= 10;
step ??= 1;
for (let i = start; i <= stop; i += step) {
yield [i];
}
},
});
console.log(db.prepare('SELECT * FROM generate_series(1, 5, 1)').all());
// Prints: [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 } ]import { Database } from 'node:sqlite';
const db = new Database(':memory:');
db.createModule('generate_series', {
columns: [
{ name: 'value', type: 'INTEGER' },
{ name: 'start', type: 'INTEGER', hidden: true },
{ name: 'stop', type: 'INTEGER', hidden: true },
{ name: 'step', type: 'INTEGER', hidden: true },
],
*rows(start, stop, step) {
start ??= 0;
stop ??= 10;
step ??= 1;
for (let i = start; i <= stop; i += step) {
yield [i];
}
},
});
console.log(db.prepare('SELECT * FROM generate_series(1, 5, 1)').all());
// Prints: [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 } ]
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> 对于变更集中至少受一次更改影响的每个表,filter回调都会被调用,表名作为第一个参数传入。如果返回值为假值,则不会尝试对该表应用任何更改。否则,如果返回值为真值或未提供filter回调,则会尝试应用该表的所有相关更改。 -
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().
import { Database } from 'node:sqlite';
const sourceDb = new Database(':memory:');
const targetDb = new Database(':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();
using 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.const { Database } = require('node:sqlite');
const sourceDb = new Database(':memory:');
const targetDb = new Database(':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();
using 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()#>
关闭会话。如果数据库或会话未打开,或者会话当前正在生成更改集或补丁集,将会抛出异常。如果这个方法是在 SQLite 调用的回调中调用的,比如授权回调、自定义函数或者订阅者,将会抛出 ERR_INVALID_STATE 错误,因为 SQLite 可能仍在使用会话。这个方法是 sqlite3session_delete() 的一个封装。
🌐 Closes the session. An exception is thrown if the database or the session is not open,
or if the session is currently generating a changeset or patchset. An
ERR_INVALID_STATE error is thrown if the method is called from a callback that
SQLite invoked, such as an authorizer callback, a user-defined function, or a
'sqlite.db.query' subscriber, because SQLite may still be using the session.
This method is a wrapper around sqlite3session_delete().
session[Symbol.dispose]()#>
关闭会话。如果会话已经关闭,那么这不会有任何操作。如果会话当前正在生成更改集或补丁集,或者该方法是在 SQLite 调用的回调中被调用的,将会抛出 ERR_INVALID_STATE 错误,条件和 session.close() 相同。
🌐 Closes the session. If the session is already closed, then this is a no-op. An
ERR_INVALID_STATE error is thrown if the session is currently generating
a changeset or patchset, or if the method is called from a callback that SQLite
invoked, under the same conditions as session.close().
类:Statement#>
🌐 Class: Statement
这个类表示一个单独的 准备好的声明。这个类不能通过其构造函数实例化。相反,实例是通过 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.
StatementSync 是 Statement 的过时别名,为了与类的以前名称保持向后兼容而保留。参见 DEP0211。
预处理语句是用于创建它的 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.
绑定参数#>
🌐 Binding parameters
all()、get()、iterate() 和 run() 方法在执行之前,会把参数绑定到预处理语句的参数上。参数可以是匿名的,也可以是有名字的。
🌐 The all(), get(), iterate(), and run() methods bind their arguments to
the parameters of the prepared statement before executing it. Parameters are
either anonymous or named.
匿名参数在 SQL 中写作 ?,并按传给方法的参数顺序绑定。?NNN 形式会将 SQLite 参数索引 NNN 分配给一个占位符。尽量避免混用编号参数和命名参数,因为它们共享参数索引。
🌐 Anonymous parameters are written as ? in SQL and are bound in order from the
arguments passed to the method. The ?NNN form assigns SQLite parameter index
NNN to a placeholder. Avoid mixing numbered and named parameters because they
share parameter indexes.
db.prepare('SELECT ? AS a, ? AS b').get('x', 42);
// { a: 'x', b: 42 }
db.prepare('SELECT ?2 AS a, ?1 AS b').get('first', 'second');
// { a: 'second', b: 'first' }
命名参数在 SQL 中以前缀字符 $、: 或 @ 开头。它们从作为第一个参数传入的对象中绑定。在 SQL 中重复一个名字会将同一个值绑定到每个出现的位置。
🌐 Named parameters begin with one of the prefix characters $, :, or @ in
SQL. They are bound from an object passed as the first argument. Repeating a
name in the SQL binds the same value to every occurrence.
db.prepare('SELECT $a AS a, $b AS b').get({ $a: 1, $b: 2 });
// { a: 1, b: 2 }
db.prepare('SELECT :a AS a').get({ ':a': 1 });
// { a: 1 }
db.prepare('SELECT @a AS a').get({ '@a': 1 });
// { a: 1 }
db.prepare('SELECT $k AS a, $k AS b').get({ k: 7 });
// { a: 7, b: 7 }
最后一个例子省略了对象键的前缀字符。默认情况下允许使用裸名字;关于它们的注意事项,请参见 statement.setAllowBareNamedParameters()。
🌐 The last example omits the prefix character from the object key. Bare names are
allowed by default; see statement.setAllowBareNamedParameters() for their
caveats.
绑定一个不属于语句参数的键会抛出 ERR_INVALID_STATE 错误,除非忽略未知的命名参数。参见 statement.setAllowUnknownNamedParameters()。
🌐 Binding a key that does not name a parameter of the statement throws an
ERR_INVALID_STATE error unless unknown named parameters are ignored. See
statement.setAllowUnknownNamedParameters().
从未绑定的参数是 NULL,绑定 undefined 也有同样的效果,所以 { $a: undefined } 和 {} 是等效的。因为 undefined 不是对象,把它传给 namedParameters 会把它绑定为匿名参数。
🌐 Parameters that are never bound are NULL, and binding undefined has the same
effect, so { $a: undefined } and {} are equivalent. Because undefined is
not an object, passing it in place of namedParameters binds it as an anonymous
parameter instead.
请参见 JavaScript 和 SQLite 之间的类型转换 获取可以绑定的值。绑定任何其他值都会抛出 ERR_INVALID_ARG_TYPE 错误。
🌐 See Type conversion between JavaScript and SQLite for the values that can be
bound. Binding any other value throws an ERR_INVALID_ARG_TYPE error.
statement.all([namedParameters][, ...anonymousParameters])#>
namedParameters<Object> 一个可选对象,用于绑定命名参数。该对象的键用于配置映射。...anonymousParameters<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 绑定到匿名参数的零个或多个值。- 返回:<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. See
Binding parameters.
statement.close()#>
完成已准备好的语句。如果语句已经被完成,会抛出异常。如果这个语句正在执行,则会抛出 ERR_INVALID_STATE 错误,这种情况发生在从语句自身触发的回调中调用该方法时,比如用户自定义函数、聚合函数或 'sqlite.db.query' 订阅者。从这样的回调中,可以完成同一连接上的空闲语句。这个方法是 sqlite3_finalize() 的一个封装。
🌐 Finalizes the prepared statement. An exception is thrown if the statement is
already finalized. An ERR_INVALID_STATE error is thrown if this statement
is currently executing, which happens when the method is called from a callback
that the statement itself triggered, such as a user-defined function, an
aggregate function, or a 'sqlite.db.query' subscriber. Idle statements
on the same connection can be finalized from such a callback. This method is a
wrapper around sqlite3_finalize().
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<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 绑定到匿名参数的零个或多个值。- 返回:<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. See
Binding parameters.
statement.iterate([namedParameters][, ...anonymousParameters])#>
namedParameters<Object> 一个可选对象,用于绑定命名参数。该对象的键用于配置映射。...anonymousParameters<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 绑定到匿名参数的零个或多个值。- 返回:<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. See
Binding parameters.
statement.resetStats()#>
将 statement.stat() 报告的每个计数器重置为零,除了 memused,它报告当前内存使用情况且无法重置。这个方法是 sqlite3_stmt_status() 的一个封装,对于在不受之前相同预处理语句执行累积计数影响的情况下测量特定工作负载非常有用。
🌐 Resets every counter reported by statement.stat() back to zero, except
memused, which reports current memory usage and cannot be reset. This
method is a wrapper around sqlite3_stmt_status() and is useful for
measuring a specific workload without the counts accumulated by earlier
executions of the same prepared statement.
statement.run([namedParameters][, ...anonymousParameters])#>
namedParameters<Object> 一个可选对象,用于绑定命名参数。该对象的键用于配置映射。...anonymousParameters<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 绑定到匿名参数的零个或多个值。- 返回:<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. See
Binding parameters.
statement.setAllowBareNamedParameters(enabled)#>
enabled<boolean> 启用或禁用对绑定命名参数而不使用前缀字符的支持。
SQLite 参数的名称以一个前缀字符开头。不过,除了美元符号之外,这些前缀字符在用作对象键时还需要额外的引号。
🌐 The names of SQLite parameters begin with a prefix character. However, with the exception of the dollar sign character, these prefix characters also require extra quoting when used in object keys.
为了提高人体工学,node:sqlite 默认允许使用裸命名参数,这些参数在 JavaScript 代码中不需要前缀字符。可以使用这种方法来禁用该行为,在绑定时需要前缀字符。当允许使用裸命名参数时,需要注意几个注意事项:
🌐 To improve ergonomics, node:sqlite allows bare named parameters, which do not
require the prefix character in JavaScript code, by default. This method can be
used to disable that behavior, requiring the prefix character when binding.
There are several caveats to be aware of when bare named parameters are
allowed:
- 在 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().
statement[Symbol.dispose]()#>
完成已准备好的语句。如果语句已经完成,则不会有任何操作。如果该语句正在执行,并且在与 statement.close() 相同的条件下,会抛出 ERR_INVALID_STATE 错误。
🌐 Finalizes the prepared statement. If the prepared statement is already
finalized, then this is a no-op. An ERR_INVALID_STATE error is thrown if
this statement is currently executing, under the same conditions as
statement.close().
statement.stat(counter)#>
counter<string> 要读取的计数器名称。以下之一:'fullscanStep'SQLite 在完整表扫描过程中进入表的次数。'sort'已经发生的排序操作次数。'autoindex'自动创建的临时索引中插入的行数,这些索引用于加快连接操作的执行速度。'vmStep'由准备好的语句执行的虚拟机操作次数。'reprepare'由于模式更改或绑定参数更改,该语句被自动重新准备的次数。'run'由预处理语句启动的执行周期次数。'filterMiss'布隆过滤器返回结果的次数,这些结果需要像平常一样进行连接步骤处理。'filterHit'因为布隆过滤器返回未找到而跳过连接步骤的次数。'memused'用于存储准备语句的大概堆内存字节数。
- 返回:<number> 所请求计数器的当前数值。
返回 SQLite 为这个预处理语句跟踪的运行时计数器之一。这个方法是 sqlite3_stmt_status() 的一个封装,并不会重置计数器。断言一个语句不会执行全表扫描(statement.stat('fullscanStep') === 0)是一个有用的检查,用来防止性能下降。
🌐 Returns one of the runtime counters that SQLite tracks for this prepared
statement. This method is a wrapper around sqlite3_stmt_status() and does
not reset the counter. Asserting that a statement does not perform a full table
scan (statement.stat('fullscanStep') === 0) is a useful check to guard
against degenerate performance.
'filterMiss' 和 'filterHit' 计数器需要 SQLite 3.38.0 或更高版本。链接到老版本 SQLite 的构建(带有 --shared-sqlite)不会暴露它们,传入任意一个名字都会抛出 ERR_INVALID_ARG_VALUE。
🌐 The 'filterMiss' and 'filterHit' counters require SQLite 3.38.0 or later.
Builds linked against an older SQLite with --shared-sqlite do not expose them,
and passing either name throws ERR_INVALID_ARG_VALUE.
类: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.
缓存有一个默认最大大小为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(stringElements[, ...boundParameters])#>
stringElements<string[]> 包含 SQL 查询的模板字面量元素。...boundParameters<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 要绑定到模板字符串占位符的参数值。- 返回:<Array> 表示查询返回的行的对象数组。
执行给定的 SQL 查询并以对象数组的形式返回所有结果行。
🌐 Executes the given SQL query and returns all resulting rows as an array of objects.
此函数旨在用作模板字面量标签,而不是直接调用。
🌐 This function is intended to be used as a template literal tag, not to be called directly.
sqlTagStore.get(stringElements[, ...boundParameters])#>
stringElements<string[]> 包含 SQL 查询的模板字面量元素。...boundParameters<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 要绑定到模板字符串占位符的参数值。- 返回:<Object> | <undefined> 一个表示查询返回的第一行的对象,如果没有返回行,则为
undefined。
执行给定的 SQL 查询并返回结果行的第一个对象。
🌐 Executes the given SQL query and returns the first resulting row as an object.
此函数旨在用作模板字面量标签,而不是直接调用。
🌐 This function is intended to be used as a template literal tag, not to be called directly.
sqlTagStore.iterate(stringElements[, ...boundParameters])#>
stringElements<string[]> 包含 SQL 查询的模板字面量元素。...boundParameters<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 要绑定到模板字符串占位符的参数值。- 返回:<Iterator> 一个迭代器,生成表示查询返回的行的对象。
执行给定的 SQL 查询并返回结果行的迭代器。
🌐 Executes the given SQL query and returns an iterator over the resulting rows.
此函数旨在用作模板字面量标签,而不是直接调用。
🌐 This function is intended to be used as a template literal tag, not to be called directly.
sqlTagStore.run(stringElements[, ...boundParameters])#>
stringElements<string[]> 包含 SQL 查询的模板字面量元素。...boundParameters<undefined> | <null> | <number> | <bigint> | <boolean> | <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 要绑定到模板字符串占位符的参数值。- 返回:<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).
此函数旨在用作模板字面量标签,而不是直接调用。
🌐 This function is intended to be used as a template literal tag, not to be called directly.
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#>
- 类型:Database
一个只读属性,它返回与此 SQLTagStore 关联的 Database 对象。
🌐 A read-only property that returns the Database object associated with this SQLTagStore.
sqlTagStore.clear()#>
重置 LRU 缓存,清除所有已存储的预处理语句。
🌐 Resets the LRU cache, clearing all stored prepared statements.
sqlite.backup(sourceDb, path[, options])#>
sourceDbDatabase 要备份的数据库。源数据库必须处于打开状态。path<string> | <Buffer> | <URL> 将创建备份的路径。如果文件已存在,内容将被覆盖。options<Object> 备份的可选配置。支持以下属性:source<string> 源数据库的名称。可以是'main'(默认主数据库)或任何已通过ATTACH DATABASE添加的其他数据库 默认值:'main'。target<string> 目标数据库的名称。可以是'main'(默认主数据库)或任何已通过ATTACH DATABASE添加的其他数据库 默认值:'main'。rate<integer> 每批备份要传输的正数页数。默认值:100。progress<Function> 一个可选的回调函数,在每个备份步骤之后调用。传递给该回调的参数是一个具有remainingPages和totalPages属性的 <Object>,描述备份操作的当前进度。
- 返回:<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.
在备份过程中,备份的数据库可以正常使用。来自同一连接 - 同一个 Database - 对象的更改会立即反映在备份中。然而,来自其他连接的更改会导致备份过程重新开始。
🌐 The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same Database - object will be reflected in the backup right away. However, mutations from other connections will cause the backup process to restart.
const { backup, Database } = require('node:sqlite');
(async () => {
const sourceDb = new Database('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, Database } from 'node:sqlite';
const sourceDb = new Database('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 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. |
SQLITE_CHANGESET_FOREIGN_KEY |
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. |
必须从传递给 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 |