feat: v0.7.0 参数化查询 + 事务增量 flush + 复合主键语义硬化 + EXPLAIN 真实索引信息
CI / test (22.x) (push) Successful in 17m29s
CI / test (24.x) (push) Failing after 17m32s
CI / e2e (push) Successful in 9m53s
CI / test (18.x) (push) Successful in 19m17s
CI / test (20.x) (push) Successful in 18m15s

- 参数化查询 db.query(sql, params):词法层 ? 绑定 + SQL 字面量安全编码
  ('' 转义/注入防护);参数计数不匹配 PARAM_ERROR;对象参数显式拒绝
- KVStoreEngine 事务增量 flush:行级变更追踪,commit 仅写改动行
  (1000 行表改 1 行:日志 1 条目 vs 整表 1000 条目);级联影响表漏写修复
  (txFullTables 同步加入 txDirtyTables);移除每次 commit 全量 checkpoint
  (阈值自动 checkpoint + close 统一截断)
- 复合主键显式拒绝:createSchema 校验期 SCHEMA_ERROR + ALTER ADD 主键列防护
  (此前静默取第一个主键,其余标记失效)
- EXPLAIN usingIndex 真实命中信息:pk / index:col / none

测试 1126 → 1147(72 套件);行覆盖率 89.8%;版本 0.7.0
This commit is contained in:
thzxx
2026-08-13 10:57:26 +08:00
parent f97c5a6001
commit 57415975ea
20 changed files with 1542 additions and 69 deletions
+264 -13
View File
@@ -34,7 +34,7 @@ class DatabaseError extends Error {
// ---------------------------------------------------------------------------
// 版本
// ---------------------------------------------------------------------------
const VERSION = '0.6.3';
const VERSION = '0.7.0';
/**
* metona-sqlark Shared WHERE Matcher 统一的条件匹配逻辑
@@ -1858,6 +1858,15 @@ class KVStoreEngine {
this.txDirtyTables = new Set();
/** 事务中发生 schema 变更(DDL)—— commit 时持久化 schema */
this.txSchemaChanged = false;
/**
* v0.7.0: 事务行级变更记录table pk put/delete
* commit 时按行增量 flush此前整表 diff大表事务改 1 行也重写全表
*/
this.txChanges = new Map();
/** v0.7.0: 无法行级追踪的表(主键变更/级联影响表)→ commit 时整表 diff */
this.txFullTables = new Set();
/** v0.7.0: 事务内 clear 的表 → commit 时清空 KV 行 */
this.txClearedTables = new Set();
this.kv = new KVStore(medium, checkpointThreshold);
}
// ---- 行 key 编解码 ----
@@ -1931,6 +1940,12 @@ class KVStoreEngine {
}
catch { /* ignore */ }
}
// v0.7.0: 关闭前 checkpoint(截断日志,重开更快)。
// 失败不阻塞关闭(日志已持久,重开可全量重放)。
try {
await this.kv.checkpoint();
}
catch { /* 数据在日志中,重开放心重放 */ }
await this.kv.close();
await this.memory.close();
this.opened = false;
@@ -2033,6 +2048,20 @@ class KVStoreEngine {
const pks = await this.memory.insert(tableName, rows);
if (this.txActive) {
this.txDirtyTables.add(tableName);
// v0.7.0: 事务内 clear 后又写入 → 清空语义被覆盖,整表 diff 兜底
if (this.txClearedTables.has(tableName)) {
this.txClearedTables.delete(tableName);
this.txFullTables.add(tableName);
return pks;
}
// v0.7.0: 行级变更记录(增量 flush)
let changes = this.txChanges.get(tableName);
if (!changes) {
changes = new Map();
this.txChanges.set(tableName, changes);
}
for (const pk of pks)
changes.set(pk, 'put');
return pks;
}
// 增量持久化(原子 putMany
@@ -2067,6 +2096,30 @@ class KVStoreEngine {
const count = await this.memory.update(tableName, query, updates);
if (this.txActive) {
this.txDirtyTables.add(tableName);
// v0.7.0: 行级变更记录 —— 主键变更无法行级追踪(旧键删除+新键落盘+级联),
// 相关表整表 diff 兜底;普通更新记录受影响行
if (pkChanged) {
for (const t of await this.affectedTables(tableName)) {
this.txFullTables.add(t);
this.txDirtyTables.add(t);
}
}
else {
let changes = this.txChanges.get(tableName);
if (!changes) {
changes = new Map();
this.txChanges.set(tableName, changes);
}
for (const pk of affected)
changes.set(pk, 'put');
// 级联影响表(理论上非主键更新不级联,防御性兜底)
for (const t of await this.affectedTables(tableName)) {
if (t !== tableName) {
this.txFullTables.add(t);
this.txDirtyTables.add(t);
}
}
}
return count;
}
const puts = {};
@@ -2116,6 +2169,20 @@ class KVStoreEngine {
const count = await this.memory.delete(tableName, query);
if (this.txActive) {
this.txDirtyTables.add(tableName);
// v0.7.0: 行级变更记录 —— 删除行记录 delete;级联影响表整表 diff 兜底
let changes = this.txChanges.get(tableName);
if (!changes) {
changes = new Map();
this.txChanges.set(tableName, changes);
}
for (const pk of pks)
changes.set(pk, 'delete');
for (const t of await this.affectedTables(tableName)) {
if (t !== tableName) {
this.txFullTables.add(t);
this.txDirtyTables.add(t);
}
}
return count;
}
const puts = {};
@@ -2140,6 +2207,9 @@ class KVStoreEngine {
await this.memory.clear(tableName);
if (this.txActive) {
this.txDirtyTables.add(tableName);
// v0.7.0: 事务内清空 → commit 时删除全部 KV 行(比整表 diff 更高效)
this.txClearedTables.add(tableName);
this.txChanges.delete(tableName);
return;
}
const diff = await this.collectTableDiff(tableName);
@@ -2173,22 +2243,23 @@ class KVStoreEngine {
this.txActive = true;
this.txDirtyTables = new Set();
this.txSchemaChanged = false;
this.txChanges = new Map();
this.txFullTables = new Set();
this.txClearedTables = new Set();
}
async commitTransaction() {
this.ensureOpen();
if (!this.txActive)
throw new DatabaseError('No active transaction', 'TX_NONE');
// v0.6.1: 全部 dirty 表合并为单次原子 flush(一条日志记录 = 真原子,
// 多表事务中途崩溃/失败不会出现"部分表已提交")
// 多表事务中途崩溃/失败不会出现"部分表已提交")
// v0.7.0: 行级增量 flush —— 普通 insert/update/delete 仅写事务内改动的行
// (此前 collectTableDiff 整表重写:大表事务改 1 行也 O(表大小));
// 主键变更/级联影响表整表 diff 兜底;clear/drop 表只删 KV 行。
const puts = {};
const deletes = [];
for (const table of this.txDirtyTables) {
if (await this.memory.hasTable(table)) {
const diff = await this.collectTableDiff(table);
Object.assign(puts, diff.puts);
deletes.push(...diff.deletes);
}
else {
if (!(await this.memory.hasTable(table))) {
// 事务内 drop 的表:清理 KV 残留行
const all = await this.kv.getAll();
const prefix = this.rowPrefix(table);
@@ -2196,6 +2267,49 @@ class KVStoreEngine {
if (key.startsWith(prefix))
deletes.push(key);
}
continue;
}
if (this.txClearedTables.has(table)) {
// 事务内 clear 的表:删除全部 KV 行
const all = await this.kv.getAll();
const prefix = this.rowPrefix(table);
for (const [key] of all) {
if (key.startsWith(prefix))
deletes.push(key);
}
continue;
}
if (this.txFullTables.has(table)) {
const diff = await this.collectTableDiff(table);
Object.assign(puts, diff.puts);
deletes.push(...diff.deletes);
continue;
}
const changes = this.txChanges.get(table);
if (changes && changes.size > 0) {
// v0.7.0: 增量 flush —— 单次全表扫描 + 变更集合过滤
const schema = await this.memory.getTableSchema(table);
if (!schema)
continue;
const pkCol = this.getPK(schema);
const pending = new Map(changes);
const rows = await this.memory.find(table, { table: table });
for (const row of rows) {
const pkStr = String(row[pkCol]);
const kind = pending.get(pkStr);
if (kind !== undefined) {
if (kind === 'put')
puts[this.rowKey(table, pkStr)] = enc(JSON.stringify(row));
else
deletes.push(this.rowKey(table, pkStr));
pending.delete(pkStr);
}
}
// 内存中已不存在的行(后续操作删除)→ KV 行删除
for (const [pk, kind] of pending) {
if (kind === 'delete')
deletes.push(this.rowKey(table, pk));
}
}
}
await this.kv.writeBatch(puts, deletes);
@@ -2203,10 +2317,15 @@ class KVStoreEngine {
if (this.txSchemaChanged) {
await this.persistSchema();
}
await this.kv.checkpoint();
// v0.7.0-perf: 移除每次 commit 的强制全量 checkpoint —— KVStore 按日志阈值
// 自动 checkpoint(日志重放保证崩溃恢复正确),大库高频事务不再 O(库大小)。
// close() 时统一 checkpoint(截断日志,重开更快)。
await this.memory.commitTransaction();
this.txActive = false;
this.txDirtyTables = new Set();
this.txChanges = new Map();
this.txFullTables = new Set();
this.txClearedTables = new Set();
}
async rollbackTransaction() {
this.ensureOpen();
@@ -2216,6 +2335,9 @@ class KVStoreEngine {
this.txActive = false;
this.txDirtyTables = new Set();
this.txSchemaChanged = false;
this.txChanges = new Map();
this.txFullTables = new Set();
this.txClearedTables = new Set();
}
// ---- 内部 ----
ensureOpen() {
@@ -2347,6 +2469,13 @@ function validateColumns(columns) {
if (primaryKeyCount === 0) {
throw new DatabaseError('Table must have at least one primary key column', 'SCHEMA_ERROR');
}
// v0.7.0: 复合主键(多列 primaryKey)当前不支持 —— 所有引擎的存储布局与
// 外键引用均为单主键假设(此前静默取第一个主键,其余标记被忽略 → 语义陷阱)。
// 显式拒绝避免用户误用;复合主键列入 v0.8 路线图。
if (primaryKeyCount > 1) {
throw new DatabaseError(`Composite primary keys are not supported yet: table has ${primaryKeyCount} primary key columns. ` +
'Use a single primary key column (or a unique column combination) instead.', 'SCHEMA_ERROR');
}
}
/** 检查字段类型(含约束校验) */
function checkFieldType(tableName, colName, type, value, colDef) {
@@ -10313,6 +10442,32 @@ class QueryExecutor {
plan = compileStatement(stmt.query);
}
catch { /* 非查询语句无 QueryPlan */ }
// v0.7.0: 真实索引命中信息(此前 usingIndex 恒为 'auto' 占位)。
// 引擎无关启发式:WHERE 中存在主键/索引/唯一列条件 → 对应引擎索引路径。
let usingIndex = plan?.table ? 'none' : 'none';
if (plan && plan.table && plan.where && Object.keys(plan.where).length > 0) {
try {
const schema = await this.engine.getTableSchema(plan.table);
if (schema) {
for (const col of Object.keys(plan.where)) {
if (col.startsWith('$'))
continue;
const colDef = schema.columns[col];
if (!colDef)
continue;
if (colDef.primaryKey) {
usingIndex = 'pk';
break;
}
if (colDef.index || colDef.unique) {
usingIndex = `index:${col}`;
break;
}
}
}
}
catch { /* schema 读取失败保持 none */ }
}
return {
type: stmt.query.type,
table: plan?.table,
@@ -10321,7 +10476,7 @@ class QueryExecutor {
orderBy: plan?.orderBy || [],
limit: plan?.limit,
offset: plan?.offset,
usingIndex: plan?.table ? 'auto' : 'none',
usingIndex,
estimatedRows: rows,
actualTimeMs: elapsed,
};
@@ -10826,6 +10981,14 @@ class QueryExecutor {
const schema = await this.engine.getTableSchema(stmt.name);
if (!schema)
return;
// v0.7.0: ALTER ADD 主键列防护 —— 复合主键不支持(与 createSchema 校验对齐),
// 避免绕过建表校验添加第二个主键列导致语义陷阱
if (stmt.action === 'ADD' && stmt.column.primaryKey) {
const hasPk = Object.values(schema.columns).some((c) => c.primaryKey);
if (hasPk) {
throw new DatabaseError(`Composite primary keys are not supported yet: table "${stmt.name}" already has a primary key column`, 'SCHEMA_ERROR');
}
}
// v0.4.1: 引擎级 alterTableAria 需重写存储行 + 持久化 schema;其余引擎走通用引用路径)
if (typeof this.engine.alterTable === 'function') {
return this.engine.alterTable(stmt.name, stmt.action, { ...astColumnToColumnDef(stmt.column), name: stmt.column.name });
@@ -11441,6 +11604,88 @@ class QueryExecutor {
}
}
/**
* metona-sqlark SQL Parameters 参数化查询绑定
* @module sql/params
*
* v0.7.0: `db.query(sql, params)` 位置参数`?`支持
* 绑定在词法层面完成仅替换字符串字面量之外的 `?`
* 值按 SQL 字面量编码字符串 `''` 转义数字/布尔/JSON 直出
* 从根上规避 SQL 注入不经过字符串拼接由用户自行转义
*/
/** 将单个参数值编码为 SQL 字面量 */
function encodeParam(value) {
if (value === null || value === undefined)
return 'NULL';
if (typeof value === 'number') {
if (Number.isFinite(value))
return String(value);
return 'NULL'; // NaN/Infinity 无 SQL 字面量 → NULL
}
if (typeof value === 'boolean')
return value ? 'TRUE' : 'FALSE';
if (typeof value === 'string')
return `'${value.replace(/'/g, "''")}'`;
// 对象/数组无 SQL 字面量(SQL 方言不支持 json 字面量),显式拒绝而非静默错配
throw new DatabaseError('Object/array query parameters are not supported by SQL binding (pass JSON strings explicitly)', 'PARAM_ERROR');
}
/**
* SQL 中的位置参数 `?`字符串字面量之外替换为编码后的字面量
* @param sql `?` 占位符的 SQL
* @param params 位置参数数组
* @throws PARAM_ERROR 参数数量不匹配
*/
function bindParameters(sql, params) {
// undefined = 不启用绑定;[] + 含 ? 的 SQL 由循环内报 PARAM_ERROR
if (!params)
return sql;
let out = '';
let i = 0;
let pIdx = 0;
let quote = null;
while (i < sql.length) {
const ch = sql[i];
if (quote !== null) {
out += ch;
if (ch === quote) {
// SQL 标准 '' 转义:两个连续引号 = 一个引号(原样保留)
if (sql[i + 1] === quote) {
out += sql[i + 1];
i += 2;
continue;
}
quote = null;
}
i++;
continue;
}
if (ch === "'" || ch === '"') {
quote = ch;
out += ch;
i++;
continue;
}
if (ch === '?') {
if (pIdx >= params.length) {
throw new DatabaseError(`Too few query parameters: placeholder #${pIdx + 1} has no value (got ${params.length} total)`, 'PARAM_ERROR');
}
out += encodeParam(params[pIdx]);
pIdx++;
i++;
continue;
}
out += ch;
i++;
}
if (quote !== null) {
throw new DatabaseError('Unterminated string literal in SQL', 'PARSE_ERROR');
}
if (pIdx < params.length) {
throw new DatabaseError(`Too many query parameters: ${params.length} provided but only ${pIdx} placeholders`, 'PARAM_ERROR');
}
return out;
}
/**
* metona-sqlark Transaction 事务管理
* @module transaction
@@ -11716,15 +11961,21 @@ class MetonaSqlark {
return this.engine.getTableNames();
}
// ---- SQL 查询 ----
/** 执行 SQL 字符串查询 */
async query(sql) {
/**
* 执行 SQL 字符串查询
* v0.7.0: 支持位置参数`?` `db.query('SELECT * FROM t WHERE id = ?', ['1'])`
* 参数按 SQL 字面量安全编码字符串 '' 转义杜绝 SQL 注入
*/
async query(sql, params) {
this.ensureReady();
const startTime = this.debug ? Date.now() : 0;
await this.pluginManager.trigger('beforeQuery', sql);
let result;
try {
// v0.7.0: 参数绑定(仅替换字符串字面量之外的 ?)
const boundSql = bindParameters(sql, params);
// v0.3.0: 支持分号分隔的多语句,逐条顺序执行,返回最后一条的结果
const statements = parseAll(sql);
const statements = parseAll(boundSql);
for (const stmt of statements) {
// v0.5.1: SQL 写语句触发 CRUD 生命周期钩子(与 Table API 路径一致)
await this.triggerStatementHooks(stmt, 'before');