database.setAuthorizer(callback)
-
callback
<Function> | <null> 要设置的授权器函数,或用于清除当前授权器的null
。¥
callback
<Function> | <null> The authorizer function to set, ornull
to clear the current authorizer.
设置授权器回调函数,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
)。¥
actionCode
<number> The type of operation being performed (e.g.,SQLITE_INSERT
,SQLITE_UPDATE
,SQLITE_SELECT
). -
arg1
<string> | <null> 第一个参数(取决于上下文,通常是表名)。¥
arg1
<string> | <null> The first argument (context-dependent, often a table name). -
arg2
<string> | <null> 第二个参数(取决于上下文,通常是列名)。¥
arg2
<string> | <null> The second argument (context-dependent, often a column name). -
triggerOrView
<string> | <null> 导致访问的触发器或视图的名称。¥
triggerOrView
<string> | <null> The name of the trigger or view causing the access.
回调函数必须返回以下常量之一:
¥The callback must return one of the following constants:
-
SQLITE_OK
- 允许操作。¥
SQLITE_OK
- Allow the operation. -
SQLITE_DENY
- 拒绝操作(导致错误)。¥
SQLITE_DENY
- Deny the operation (causes an error). -
SQLITE_IGNORE
- 忽略操作(静默跳过)。¥
SQLITE_IGNORE
- Ignore the operation (silently skip).
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);
}