两个 SQLite 只读请求,为什么会报“cannot start a transaction within a transaction”?

May 6, 2025

开发资产管理页面时,我碰到过一个费解的 SQLite 错误。为了显示用户列表,后端要统计用户总数、读取当前页,再查出本页用户的权限。我把三条查询放进同一个事务,让它们看到同一时刻的数据。两个请求一旦重叠,SQLite 就报 SQLITE_ERROR: cannot start a transaction within a transaction。明明两个请求都只读。

为什么第二个请求的第一条 SQL 就失败了?

在 Node.js 里,每个请求各自调用一次查询函数,但两次调用用的是同一个 db 对象。语句可能按下面的顺序抵达这个连接。

BEGIN;                        -- Request A starts
SELECT COUNT(*) FROM users;   -- A has the count and still needs the page of users
BEGIN;                        -- Request B starts while A's transaction is still open

SQLite 文档写道:“Transactions created using BEGIN...COMMIT do not nest.” 也就是说,用 BEGIN...COMMIT 创建的事务不能嵌套。事务属于连接。如果 A 尚未提交,B 就发出 BEGIN,等于要求 SQLite 在 A 的事务里再开启一个事务。即使驱动严格按上面顺序逐条执行,第三条也会失败。增加 busy_timeout 没有用。这个共享连接已经有一个开启的事务,B 根本还没走到需要等待其他连接释放锁的阶段。1

要让 B 立即开始读取,就为它分配另一个连接。如果 A 和 B 必须共享一个连接,让 B 等 A 的整个事务结束后再开始。

用连接池让两个请求并发读取

连接池保有多个连接,都指向同一个数据库文件。A 借连接 1,B 借连接 2,各自在自己的连接上执行 BEGIN。SQLite 允许多个读事务同时进行。每个请求看到的是自己首次读取时的快照,因此该请求得到的总数和分页数据是相符的。两个请求看到的快照则可能略有不同。1

下列 Node.js 示例能放进同一个 CommonJS 模块,使用 sqlite3@5.1.7 以及管理连接借还的 sequelize-pool@7.1.0。服务启动时只创建一次连接池,各个请求共用。2

const sqlite3 = require('sqlite3');
const { Pool } = require('sequelize-pool');
const { promisify } = require('node:util');

function createPool(filename, max) {
  return new Pool({
    min: 0,
    max,
    create: () => new Promise((resolve, reject) => {
      const db = new sqlite3.Database(filename, err => {
        if (err) reject(err);
        else resolve(db);
      });
    }),
    validate: db => db.open,
    destroy: db => promisify(db.close).call(db),
  });
}

async function withTransaction(pool, work) {
  const db = await pool.acquire();
  const exec = promisify(db.exec).bind(db);
  try {
    await exec('BEGIN');
    const result = await work(db);
    await exec('COMMIT');
    pool.release(db);
    return result;
  } catch (error) {
    await pool.destroy(db);
    throw error;
  }
}

如果某条查询或提交失败,示例会关闭连接。连接关闭时 SQLite 会回滚尚未提交的事务,因此下个借用者拿到干净的连接。成功时,只有等 COMMIT 完成,函数才把连接归还池中。3

const userPool = createPool('users.sqlite', 4);

async function readUserPage(db) {
  const get = promisify(db.get).bind(db);
  const all = promisify(db.all).bind(db);
  const { total } = await get('SELECT COUNT(*) AS total FROM users');
  const users = await all(
    'SELECT user_id, user_name FROM users ORDER BY user_id LIMIT 20'
  );
  return { total, users };
}

function listUsers() {
  return withTransaction(userPool, readUserPage);
}

这个例子读取总数和第一页。如果还要取权限,在 readUserPage(db) 内使用同一个 db,等权限查询完成后再返回。中间若再借一个连接,权限查询可能看到较新的更新。池大小是四时,同时最多四个事务持有连接,第五个请求等待空闲连接。

共享一个连接时,让整个事务排队

用户列表访问量不大时,一个连接也许够用。把连接池大小设为一。A 一旦借到连接,B 就会自动排队。两个请求仍能使用前面的事务函数。2

const transactionQueue = createPool('users.sqlite', 1);

function listUsersInOrder() {
  return withTransaction(transactionQueue, readUserPage);
}

两个请求同时调用 listUsersInOrder() 时,B 会停在 pool.acquire(),连 BEGIN 都还没发。A 在各条查询之间的每个 await 期间都保有连接。仅给 db.serialize() 传一个异步函数无法保证这一点。驱动能排好回调中直接提交的语句,但回调返回之后才提交的 SQL 可能与其他请求交错。这个连接上的所有操作都要走同一条队列。4

用信号量只让写事务排队

只有一个连接时,就算两个人都只查看列表,第二位读者也得等。换回四个连接会怎样?假设 A、B 各持一个连接,正分别修改两个用户的权限。SQLite 对同一个数据库文件同一时刻只允许一个写事务。 如果 A 先拿到写锁,B 可能要等。针对这种锁竞争,Node 驱动 sqlite3@5.1.7 会给每个新连接设置一秒的默认等待时间。如果 A 及时提交,B 就能继续。如果等完仍拿不到锁,B 可能收到 SQLITE_BUSY。开启预写日志(WAL)后,写入期间读者可以继续读取各自的快照,写入者依然轮流执行。56

当时读到的一个 Stack Overflow 问题里,UI 线程和后台线程都在批量写入。有回答建议把写任务送进同一条队列。7 Node.js 里可以用信号量落实这条规则。信号量有固定数量的名额,拿到的任务运行,其余排队。只给写入者一个名额,写事务就会轮流进行。

run() 会等待传入的任务完成。它的 finally 块把名额直接交给等待时间最长的任务。任务覆盖整个事务,所以下一项只有在提交完成或错误清理结束后才会开始。

class Semaphore {
  constructor(permits) {
    this.available = permits;
    this.waiters = [];
  }

  async run(task) {
    if (this.available > 0) {
      this.available--;
    } else {
      await new Promise(resolve => this.waiters.push(resolve));
    }

    try {
      return await task();
    } finally {
      const next = this.waiters.shift();
      if (next) next();
      else this.available++;
    }
  }
}

在每个进程内只创建一次 writes 信号量。查看列表的请求仍然直接从有四个连接的 userPool 借连接。撤销权限的请求先获取写入名额,再从同一个池借连接。

const writes = new Semaphore(1);

function revokePrivilege(userId, privilege) {
  return writes.run(() => withTransaction(userPool, async db => {
    const run = promisify(db.run).bind(db);
    await run('DELETE FROM user_privileges WHERE user_id = ? AND priv_name = ?',
              [userId, privilege]);
  }));
}

顺序很重要。假设 A 正在更新权限,B、C、D 也都请求修改。三者都在 writes.run() 处等待,没有占用任何连接。这时打开列表的人仍能借到空闲连接。如果写入者先借连接再等名额,四个写请求就可能占满整个池,让读者也跟着等。

池大小为四,决定了同一时刻能借出多少连接。单个写入名额,决定了该进程同一时刻能启动多少写事务。分别设置这两个上限,读者就能绕过写入队列。如果另一个进程也写同一文件,它有自己的信号量。进程之间的文件锁仍由 SQLite 协调。5

Footnotes

  1. SQLite. (2026, February 18). Transaction, §§ 2–2.2. 引文来自第 2 节关于嵌套事务的段落。 SQLite Documentation. Transactions. ↩ ↩2

  2. Sequelize contributors. (n.d.). Sequelize Pool (v7.1.0), “Create pool using a factory object” and “Use pool in your code to acquire/release resources.” GitHub. 连接池示例. ↩ ↩2

  3. SQLite. (n.d.). Closing a database connection, 末段. SQLite C Interface. 关闭连接时回滚. ↩

  4. Tan, A. (2016, November 29). Control flow, “Database#serialize([callback]).” node-sqlite3 Wiki. 语句何时进入队列. ↩

  5. SQLite. (n.d.). Isolation in SQLite, “Isolation between database connections” and “Isolation and concurrency.” SQLite Documentation. 单写入者与 WAL 快照. ↩ ↩2

  6. node-sqlite3 contributors. (n.d.). database.cc (v5.1.7), Database::Work_Open. GitHub. 新连接的 1,000 毫秒默认值. SQLite. (n.d.). Set a busy timeout. SQLite C Interface. 等待与 SQLITE_BUSY. ↩

  7. Vasilyev, K. (2018, November 29). Answer to “Concurrency issue with two SQLite connections in two different Threads”, 写入队列方案的第 1–4 步. Stack Overflow. 让两个线程的写入排入同一队列. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-06). 两个 SQLite 只读请求,为什么会报“cannot start a transaction within a transaction”?. https://caiborui.com/blog/2025-05-06-en-sqlite-concurrent-requests-begin-transaction-zhtrans

@misc{borui2025-0215ff80,
  author = {borui},
  title = {{两个 SQLite 只读请求,为什么会报“cannot start a transaction within a transaction”?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-06-en-sqlite-concurrent-requests-begin-transaction-zhtrans}
}