feat: v0.1.13 — 事务回滚 + 子查询 + 外键级联 + 连接池
CI / test (18.x) (push) Successful in 9m54s
CI / test (20.x) (push) Successful in 9m52s
CI / test (22.x) (push) Successful in 9m54s
CI / test (24.x) (push) Successful in 9m47s

This commit is contained in:
thzxx
2026-07-26 16:31:15 +08:00
parent 7a53cfd530
commit 0f128da34a
24 changed files with 2264 additions and 166 deletions
+518 -39
View File
@@ -31,7 +31,7 @@ class DatabaseError extends Error {
// ---------------------------------------------------------------------------
// 版本
// ---------------------------------------------------------------------------
const VERSION = '0.1.12';
const VERSION = '0.1.13';
/**
* metona-sqlark Shared WHERE Matcher — 统一的条件匹配逻辑
@@ -200,6 +200,8 @@ class MemoryEngine {
this.schemas = new Map();
this.indexes = new Map();
this.opened = false;
// ---- 事务快照 ----
this.snapshot = null;
}
// ---- 生命周期 ----
async open(_dbName, _version) { this.opened = true; }
@@ -293,9 +295,16 @@ class MemoryEngine {
toDelete.push(pk);
}
}
// 级联删除:检查引用此表的其他表
let cascadeCount = 0;
for (const pk of toDelete) {
const row = table.get(pk);
if (row)
cascadeCount += await this.cascadeDelete(tableName, pk, row);
}
for (const pk of toDelete)
table.delete(pk);
return toDelete.length;
return toDelete.length + cascadeCount;
}
async count(tableName, query) {
this.ensureTable(tableName);
@@ -317,6 +326,54 @@ class MemoryEngine {
for (const colIndex of tableIndexes.values())
colIndex.clear();
}
// ---- 事务 ----
async beginTransaction() {
if (this.snapshot)
throw new DatabaseError('Transaction already in progress', 'TX_ACTIVE');
this.snapshot = {
tables: this.deepCloneMapMap(this.tables),
schemas: new Map(this.schemas),
indexes: this.deepCloneIndexes(this.indexes),
};
}
async commitTransaction() {
if (!this.snapshot)
throw new DatabaseError('No active transaction', 'TX_NONE');
this.snapshot = null;
}
async rollbackTransaction() {
if (!this.snapshot)
throw new DatabaseError('No active transaction', 'TX_NONE');
this.tables = this.snapshot.tables;
this.schemas = this.snapshot.schemas;
this.indexes = this.snapshot.indexes;
this.snapshot = null;
}
// ---- 事务快照辅助 ----
deepCloneMapMap(source) {
const clone = new Map();
for (const [k, v] of source) {
const innerClone = new Map();
for (const [ik, iv] of v)
innerClone.set(ik, { ...iv });
clone.set(k, innerClone);
}
return clone;
}
deepCloneIndexes(source) {
const clone = new Map();
for (const [tableName, tableIndexes] of source) {
const tableClone = new Map();
for (const [col, colIndex] of tableIndexes) {
const colClone = new Map();
for (const [val, pkSet] of colIndex)
colClone.set(val, new Set(pkSet));
tableClone.set(col, colClone);
}
clone.set(tableName, tableClone);
}
return clone;
}
// ---- 内部辅助 ----
ensureTable(tableName) {
if (!this.tables.has(tableName))
@@ -423,11 +480,62 @@ class MemoryEngine {
}
}
}
// ---- 外键级联 ----
/**
* 级联删除:查找引用 tableName.pkValue 的所有表的行并删除。
* @returns 级联删除的行数
*/
async cascadeDelete(tableName, pkValue, _row) {
let totalCascade = 0;
for (const [refTableName, refSchema] of this.schemas) {
if (refTableName === tableName)
continue;
for (const [colName, colDef] of Object.entries(refSchema.columns)) {
if (!colDef.references || !colDef.onDelete || colDef.onDelete === 'RESTRICT')
continue;
const [refTable, refCol] = colDef.references.split('.');
if (refTable !== tableName)
continue;
const refTableData = this.tables.get(refTableName);
if (!refTableData)
continue;
// 查找所有引用此主键的行
const toDelete = [];
for (const [refPk, refRow] of refTableData) {
if (String(refRow[colName]) === pkValue) {
toDelete.push(refPk);
}
}
if (colDef.onDelete === 'CASCADE') {
// 递归级联
for (const refPk of toDelete) {
const refRow = refTableData.get(refPk);
if (refRow) {
totalCascade += await this.cascadeDelete(refTableName, refPk, refRow);
}
refTableData.delete(refPk);
totalCascade++;
}
}
else if (colDef.onDelete === 'SET NULL') {
for (const refPk of toDelete) {
const refRow = refTableData.get(refPk);
if (refRow) {
refRow[colName] = null;
}
}
}
}
}
return totalCascade;
}
}
/**
* metona-sqlark IndexedDB Engine — 基于 IndexedDB 的持久化存储引擎
* @module engine/indexeddb
*
* v0.1.13: 支持事务 — beginTransaction 延迟 IDB 写入,commit 批量刷盘,rollback 恢复快照。
*/
class IndexedDBEngine {
constructor() {
@@ -436,6 +544,8 @@ class IndexedDBEngine {
this.dbName = '';
this.version = 1;
this.memoryCache = new MemoryEngine();
// ---- 事务状态 ----
this.txActive = false;
}
async open(dbName, version) {
this.dbName = dbName;
@@ -459,6 +569,85 @@ class IndexedDBEngine {
// ---- 表管理 ----
async createTable(schema) {
await this.memoryCache.createTable(schema);
if (this.txActive)
return; // 事务中延迟 IDB 操作
await this.idbCreateTable(schema);
}
async dropTable(tableName) {
await this.memoryCache.dropTable(tableName);
if (this.txActive)
return;
await this.idbDropTable(tableName);
}
async hasTable(tableName) { return this.ensureDB().objectStoreNames.contains(tableName); }
async getTableNames() { return Array.from(this.ensureDB().objectStoreNames); }
async getTableSchema(tableName) { return this.memoryCache.getTableSchema(tableName); }
// ---- CRUD ----
async insert(tableName, rows) {
const pks = await this.memoryCache.insert(tableName, rows);
if (this.txActive)
return pks; // 事务中延迟写入
await this.idbInsert(tableName, rows);
return pks;
}
async find(tableName, query) {
// 事务中从内存缓存读取(保证读到未提交的变更),否则走 IDB
if (this.txActive)
return this.memoryCache.find(tableName, query);
return this.idbFind(tableName, query);
}
async update(tableName, query, updates) {
const count = await this.memoryCache.update(tableName, query, updates);
if (this.txActive)
return count;
await this.idbUpdate(tableName, query, updates);
return count;
}
async delete(tableName, query) {
const count = await this.memoryCache.delete(tableName, query);
if (this.txActive)
return count;
await this.idbDelete(tableName, query);
return count;
}
async count(tableName, query) {
if (this.txActive)
return this.memoryCache.count(tableName, query);
const results = await this.idbFind(tableName, { table: tableName, where: query?.where ?? {} });
return results.length;
}
async clear(tableName) {
await this.memoryCache.clear(tableName);
if (this.txActive)
return;
await this.idbClear(tableName);
}
// ---- 事务 ----
async beginTransaction() {
if (this.txActive)
throw new DatabaseError('Transaction already in progress', 'TX_ACTIVE');
this.txActive = true;
// 保存内存快照到 MemoryEngine 内部的 beginTransaction
await this.memoryCache.beginTransaction();
}
async commitTransaction() {
if (!this.txActive)
throw new DatabaseError('No active transaction', 'TX_NONE');
// 确认内存层的变更
await this.memoryCache.commitTransaction();
// 批量将内存数据刷到 IndexedDB
await this.flushToIDB();
this.txActive = false;
}
async rollbackTransaction() {
if (!this.txActive)
throw new DatabaseError('No active transaction', 'TX_NONE');
// 恢复内存层到快照状态
await this.memoryCache.rollbackTransaction();
this.txActive = false;
}
// ---- IDB 原生操作 ----
async idbCreateTable(schema) {
const db = this.ensureDB();
return new Promise((resolve, reject) => {
const newVersion = db.version + 1;
@@ -478,8 +667,7 @@ class IndexedDBEngine {
request.onerror = () => reject(new DatabaseError(`Failed to create table "${schema.name}"`, 'IDB_UPGRADE_ERROR', request.error));
});
}
async dropTable(tableName) {
await this.memoryCache.dropTable(tableName);
async idbDropTable(tableName) {
const db = this.ensureDB();
return new Promise((resolve, reject) => {
const newVersion = db.version + 1;
@@ -494,27 +682,18 @@ class IndexedDBEngine {
request.onerror = () => reject(new DatabaseError(`Failed to drop table "${tableName}"`, 'IDB_UPGRADE_ERROR', request.error));
});
}
async hasTable(tableName) { return this.ensureDB().objectStoreNames.contains(tableName); }
async getTableNames() { return Array.from(this.ensureDB().objectStoreNames); }
async getTableSchema(tableName) { return this.memoryCache.getTableSchema(tableName); }
// ---- CRUD ----
async insert(tableName, rows) {
await this.memoryCache.insert(tableName, rows);
async idbInsert(tableName, rows) {
const db = this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(tableName, 'readwrite');
const store = tx.objectStore(tableName);
const pks = [];
for (const row of rows) {
const req = store.add(row);
req.onsuccess = () => pks.push(String(req.result));
req.onerror = () => { }; // 内存层已校验,忽略 IDB 重复键
}
tx.oncomplete = () => resolve(pks);
for (const row of rows)
store.add(row);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(new DatabaseError(`Insert failed for "${tableName}"`, 'IDB_TX_ERROR', tx.error));
});
}
async find(tableName, query) {
async idbFind(tableName, query) {
const db = this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(tableName, 'readonly');
@@ -538,29 +717,25 @@ class IndexedDBEngine {
req.onerror = () => reject(new DatabaseError(`Find failed for "${tableName}"`, 'IDB_READ_ERROR', req.error));
});
}
async update(tableName, query, updates) {
await this.memoryCache.update(tableName, query, updates);
async idbUpdate(tableName, query, updates) {
const db = this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(tableName, 'readwrite');
const store = tx.objectStore(tableName);
const getAllReq = store.getAll();
let count = 0;
getAllReq.onsuccess = () => {
for (const row of getAllReq.result ?? []) {
if (!query.where || Object.keys(query.where).length === 0 || matchWhere(row, query.where)) {
Object.assign(row, updates);
store.put(row);
count++;
}
}
};
tx.oncomplete = () => resolve(count);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(new DatabaseError(`Update failed for "${tableName}"`, 'IDB_TX_ERROR', tx.error));
});
}
async delete(tableName, query) {
await this.memoryCache.delete(tableName, query);
async idbDelete(tableName, query) {
const db = this.ensureDB();
const schema = await this.memoryCache.getTableSchema(tableName);
if (!schema)
@@ -570,25 +745,18 @@ class IndexedDBEngine {
const tx = db.transaction(tableName, 'readwrite');
const store = tx.objectStore(tableName);
const getAllReq = store.getAll();
let count = 0;
getAllReq.onsuccess = () => {
for (const row of getAllReq.result ?? []) {
if (!query.where || Object.keys(query.where).length === 0 || matchWhere(row, query.where)) {
store.delete(row[pkColumn]);
count++;
}
}
};
tx.oncomplete = () => resolve(count);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(new DatabaseError(`Delete failed for "${tableName}"`, 'IDB_TX_ERROR', tx.error));
});
}
async count(tableName, query) {
const results = await this.find(tableName, { table: tableName, where: query?.where ?? {} });
return results.length;
}
async clear(tableName) {
await this.memoryCache.clear(tableName);
async idbClear(tableName) {
const db = this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(tableName, 'readwrite');
@@ -597,6 +765,18 @@ class IndexedDBEngine {
tx.onerror = () => reject(new DatabaseError(`Clear failed for "${tableName}"`, 'IDB_TX_ERROR', tx.error));
});
}
/** 将内存缓存中的所有表数据刷新到 IndexedDB */
async flushToIDB() {
const tableNames = await this.memoryCache.getTableNames();
for (const tableName of tableNames) {
const rows = await this.memoryCache.find(tableName, { table: tableName });
// Clear + bulk insert for simplicity
await this.idbClear(tableName);
if (rows.length > 0) {
await this.idbInsert(tableName, rows);
}
}
}
ensureDB() {
if (!this.db)
throw new DatabaseError('Database not opened', 'DB_NOT_OPEN');
@@ -712,6 +892,22 @@ class OPFSEngine {
await this.memoryCache.clear(tableName);
await this.writeTableData(tableName, []);
}
// ---- 事务 ----
async beginTransaction() {
await this.memoryCache.beginTransaction();
}
async commitTransaction() {
await this.memoryCache.commitTransaction();
// 将内存数据刷到 OPFS
const tableNames = await this.memoryCache.getTableNames();
for (const tableName of tableNames) {
const rows = await this.memoryCache.find(tableName, { table: tableName });
await this.writeTableData(tableName, rows);
}
}
async rollbackTransaction() {
await this.memoryCache.rollbackTransaction();
}
// ---- 内部辅助 ----
ensureDir() {
if (!this.tablesDir) {
@@ -854,6 +1050,19 @@ class HybridEngine {
await this.memoryEngine.clear(tableName);
await this.diskEngine.clear(tableName);
}
// ---- 事务 ----
async beginTransaction() {
await this.memoryEngine.beginTransaction();
await this.diskEngine.beginTransaction();
}
async commitTransaction() {
await this.memoryEngine.commitTransaction();
await this.diskEngine.commitTransaction();
}
async rollbackTransaction() {
await this.memoryEngine.rollbackTransaction();
await this.diskEngine.rollbackTransaction();
}
// ---- 引擎信息 ----
/** 获取磁盘引擎类型 */
getDiskEngineType() {
@@ -1111,6 +1320,9 @@ function astColumnToColumnDef(astCol) {
maxLength: astCol.maxLength,
min: astCol.min,
max: astCol.max,
references: astCol.references,
onDelete: astCol.onDelete,
onUpdate: astCol.onUpdate,
};
}
@@ -1191,6 +1403,10 @@ class QueryExecutor {
// SELECT
// ===================================================================
async executeSelect(stmt) {
// 先解析子查询
if (stmt.where && Object.keys(stmt.where).length > 0) {
stmt.where = await this.resolveSubqueries(stmt.where);
}
const hasGroupBy = !!(stmt.groupBy && stmt.groupBy.length > 0);
let rows;
if (!stmt.joins || stmt.joins.length === 0) {
@@ -1371,6 +1587,87 @@ class QueryExecutor {
return this.engine.dropTable(stmt.name);
}
getEngine() { return this.engine; }
// ===================================================================
// 子查询解析
// ===================================================================
/**
* 递归扫描 WHERE 条件,找到 $subquery 标记并执行子查询,
* 将结果替换为具体值。
*/
async resolveSubqueries(where) {
const resolved = {};
for (const [key, value] of Object.entries(where)) {
// 逻辑组合操作符
if (key === '$and' && Array.isArray(value)) {
resolved.$and = await Promise.all(value.map((sub) => this.resolveSubqueries(sub)));
continue;
}
if (key === '$or' && Array.isArray(value)) {
resolved.$or = await Promise.all(value.map((sub) => this.resolveSubqueries(sub)));
continue;
}
if (key === '$not' && typeof value === 'object' && value !== null) {
resolved.$not = await this.resolveSubqueries(value);
continue;
}
// 字段条件
if (typeof value === 'object' && value !== null) {
resolved[key] = await this.resolveOperatorSubqueries(value);
}
else {
resolved[key] = value;
}
}
return resolved;
}
/**
* 解析操作符值中嵌套的子查询
*/
async resolveOperatorSubqueries(ops) {
const resolved = {};
for (const [op, operand] of Object.entries(ops)) {
// 处理嵌套 $and/$or(在字段级条件中)
if (op === '$and' && Array.isArray(operand)) {
resolved.$and = await Promise.all(operand.map((sub) => this.resolveSubqueries(sub)));
continue;
}
if (op === '$or' && Array.isArray(operand)) {
resolved.$or = await Promise.all(operand.map((sub) => this.resolveSubqueries(sub)));
continue;
}
if (op === '$not') {
resolved.$not = typeof operand === 'object' && operand !== null
? await this.resolveOperatorSubqueries(operand)
: operand;
continue;
}
// 子查询检测
if (typeof operand === 'object' && operand !== null && '$subquery' in operand) {
const subStmt = operand.$subquery;
const subResult = await this.executeSelect(subStmt);
if (op === '$in' || op === '$nin') {
// IN 子查询 → 提取第一列的值列表
const colName = Object.keys(subResult[0] || {})[0];
const values = subResult.map((row) => row[colName]);
resolved[op] = values;
}
else {
// 标量子查询 → 取第一行第一列
if (subResult.length === 0) {
resolved[op] = null;
}
else {
const colName = Object.keys(subResult[0])[0];
resolved[op] = subResult[0][colName];
}
}
}
else {
resolved[op] = operand;
}
}
return resolved;
}
}
/**
@@ -1412,6 +1709,8 @@ var TokenType;
TokenType["DEFAULT"] = "DEFAULT";
TokenType["NULL"] = "NULL";
TokenType["TRUE"] = "TRUE";
TokenType["REFERENCES"] = "REFERENCES";
TokenType["CASCADE"] = "CASCADE";
TokenType["FALSE"] = "FALSE";
// JOIN 相关
TokenType["INNER"] = "INNER";
@@ -1486,6 +1785,8 @@ const KEYWORDS = {
'NULL': TokenType.NULL,
'TRUE': TokenType.TRUE,
'FALSE': TokenType.FALSE,
'REFERENCES': TokenType.REFERENCES,
'CASCADE': TokenType.CASCADE,
// JOIN
'INNER': TokenType.INNER,
'LEFT': TokenType.LEFT,
@@ -1994,7 +2295,8 @@ class Parser {
while (this.curTokenIs(TokenType.PRIMARY) ||
this.curTokenIs(TokenType.UNIQUE) ||
this.curTokenIs(TokenType.NOT) ||
this.curTokenIs(TokenType.DEFAULT)) {
this.curTokenIs(TokenType.DEFAULT) ||
this.curTokenIs(TokenType.REFERENCES)) {
if (this.curTokenIs(TokenType.PRIMARY)) {
this.nextToken();
this.expect(TokenType.KEY);
@@ -2006,7 +2308,6 @@ class Parser {
}
else if (this.curTokenIs(TokenType.NOT)) {
this.nextToken();
// 支持 NOT NULL → required
this.expect(TokenType.NULL);
col.required = true;
}
@@ -2014,12 +2315,53 @@ class Parser {
this.nextToken();
col.default = this.parseValue();
}
else if (this.curTokenIs(TokenType.REFERENCES)) {
this.nextToken();
const refTable = this.expectIdentifier('referenced table');
this.expect(TokenType.LPAREN);
const refCol = this.expectIdentifier('referenced column');
this.expect(TokenType.RPAREN);
col.references = `${refTable}.${refCol}`;
// ON DELETE / ON UPDATE
while (this.curTokenIs(TokenType.ON)) {
this.nextToken();
if (this.curTokenIs(TokenType.DELETE)) {
this.nextToken();
col.onDelete = this.parseCascadeAction();
}
else if (this.curTokenIs(TokenType.UPDATE)) {
this.nextToken();
col.onUpdate = this.parseCascadeAction();
}
else {
break;
}
}
}
else {
break;
}
}
return col;
}
/** 解析 CASCADE | SET NULL | RESTRICT */
parseCascadeAction() {
if (this.curTokenIs(TokenType.CASCADE)) {
this.nextToken();
return 'CASCADE';
}
if (this.curTokenIs(TokenType.SET)) {
this.nextToken();
this.expect(TokenType.NULL);
return 'SET NULL';
}
// RESTRICT 或默认
if (this.curToken.type === TokenType.IDENTIFIER && this.curToken.value.toUpperCase() === 'RESTRICT') {
this.nextToken();
return 'RESTRICT';
}
return 'RESTRICT';
}
// ===================================================================
// DROP TABLE
// ===================================================================
@@ -2090,6 +2432,14 @@ class Parser {
if (this.curTokenIs(TokenType.IN)) {
this.nextToken();
this.expect(TokenType.LPAREN);
// 子查询: IN (SELECT ...)
if (this.curTokenIs(TokenType.SELECT)) {
const subquery = this.parseSelect();
this.expect(TokenType.RPAREN);
const result = {};
result[column] = { $in: { $subquery: subquery } };
return result;
}
const values = this.parseValueList();
this.expect(TokenType.RPAREN);
const result = {};
@@ -2098,6 +2448,15 @@ class Parser {
}
// 比较运算符
const op = this.parseComparisonOp();
// 子查询: op (SELECT ...)
if (this.curTokenIs(TokenType.LPAREN) && this.peekTokenIs(TokenType.SELECT)) {
this.nextToken(); // skip (
const subquery = this.parseSelect();
this.expect(TokenType.RPAREN);
const result = {};
result[column] = { [op]: { $subquery: subquery } };
return result;
}
// 尝试解析列引用(identifier DOT identifier 格式)
let value;
if ((this.curToken.type === TokenType.IDENTIFIER || this._isKeywordAsIdent()) &&
@@ -2336,8 +2695,7 @@ function parse(sql) {
* metona-sqlark Transaction — 事务管理
* @module transaction
*
* 封装多操作事务,保证原子性。
* v0.0.1: 基于引擎层操作实现,IndexedDB 引擎利用原生事务。
* v0.1.13: 支持真正的回滚 — 利用引擎层 begin/commit/rollback 实现原子性。
*/
// ---------------------------------------------------------------------------
// Transaction
@@ -2373,15 +2731,21 @@ class TransactionManager {
constructor(engine) {
this.engine = engine;
}
/** 执行事务 */
/** 执行事务 — 支持自动回滚 */
async execute(fn) {
const trx = new Transaction(this.engine);
// 开始引擎层事务
await this.engine.beginTransaction();
try {
const result = await fn(trx);
// 成功 → 提交
await this.engine.commitTransaction();
trx._markCompleted();
return result;
}
catch (error) {
// 失败 → 回滚
await this.engine.rollbackTransaction();
if (error instanceof DatabaseError)
throw error;
throw new DatabaseError(`Transaction failed: ${error.message}`, 'TRANSACTION_ERROR', error);
@@ -2664,6 +3028,121 @@ class MetonaSqlark {
}
}
/**
* metona-sqlark Connection Manager — 数据库实例连接池
* @module connection-manager
*
* v0.1.13: 避免重复创建同名数据库实例,通过 connect() 复用已有连接。
* 管理实例生命周期,防止重复 open IndexedDB。
*/
// ---------------------------------------------------------------------------
// ConnectionManager
// ---------------------------------------------------------------------------
class ConnectionManager {
constructor() {
/** 活跃连接:dbName → MetonaSqlark */
this.connections = new Map();
/** 连接引用计数:dbName → count */
this.refCount = new Map();
}
/**
* 获取或创建数据库实例
*
* 如果同名数据库已打开,复用已有实例并增加引用计数。
* 否则创建新实例。
*
* @example
* ```ts
* const db = await MetonaSqlark.connect({ name: 'my-app', mode: 'hybrid' });
* // ... use db
* await db.disconnect(); // 引用计数 -1,归零时自动关闭
* ```
*/
async connect(config) {
const name = config.name;
// 已有连接 → 复用
const existing = this.connections.get(name);
if (existing && existing.isReady()) {
const count = (this.refCount.get(name) ?? 0) + 1;
this.refCount.set(name, count);
return existing;
}
// 创建新连接
const db = new MetonaSqlark(config);
await db.init();
this.connections.set(name, db);
this.refCount.set(name, 1);
// 注入 disconnect 方法
db.disconnect = async () => {
await this.release(name);
};
return db;
}
/**
* 释放连接引用。引用计数归零时自动关闭数据库。
*/
async release(dbName) {
const count = (this.refCount.get(dbName) ?? 1) - 1;
if (count <= 0) {
const db = this.connections.get(dbName);
if (db) {
await db.close();
this.connections.delete(dbName);
}
this.refCount.delete(dbName);
}
else {
this.refCount.set(dbName, count);
}
}
/**
* 强制关闭指定数据库(忽略引用计数)
*/
async forceClose(dbName) {
const db = this.connections.get(dbName);
if (db) {
await db.close();
this.connections.delete(dbName);
}
this.refCount.delete(dbName);
}
/**
* 强制关闭所有连接
*/
async closeAll() {
for (const [, db] of this.connections) {
try {
await db.close();
}
catch { /* ignore */ }
}
this.connections.clear();
this.refCount.clear();
}
/**
* 获取所有活跃连接名
*/
getActiveConnections() {
return Array.from(this.connections.keys());
}
/**
* 获取连接的引用计数
*/
getRefCount(dbName) {
return this.refCount.get(dbName) ?? 0;
}
}
// ---------------------------------------------------------------------------
// 全局单例
// ---------------------------------------------------------------------------
const manager = new ConnectionManager();
// 挂载到 MetonaSqlark 静态方法(通过 any 绕过 TS 类型检查)
const M = MetonaSqlark;
M.connect = (config) => manager.connect(config);
M.disconnect = (dbName) => manager.release(dbName);
M.disconnectAll = () => manager.closeAll();
M.getActiveConnections = () => manager.getActiveConnections();
/**
* metona-sqlark — 入口文件
* @module metona-sqlark