Python sqlite3 账户汇总缓存实战:触发器、对账与原子回滚
账户页经常需要显示交易笔数与净额。把这些数字放进一张汇总表很容易,难的是在交易被修改、移到另一个账户、删除或整批撤销之后,仍然保证它与明细相符。本教程使用 Python 标准库 sqlite3,把这个问题拆成可检验的不变量、三类触发器和独立的对账流程。交易明细始终是真值,缓存只是可以重建的派生数据;本文讨论正确性,不提供未经测量的性能结论。

适用范围:Python 3.12 及以上,SQLite 3.24.0 及以上。本文实测环境为 Python 3.12.14、SQLite 3.53.1;版本号指本次运行环境,不代表读者机器已经具备相同版本。以下恰好九段 Python 示例均可单独保存为脚本运行,不依赖前一段变量、文件或第三方包。每段都使用新的内存数据库,示例中的重复建表是为了便于复制验证。
所有连接显式使用 autocommit=True,再用 SQL 的 BEGIN、COMMIT、ROLLBACK 控制需要成组提交的工作。这个参数从 Python 3.12 引入;在此模式下,连接的 commit()、rollback() 方法不会替你结束手动开启的 SQL 事务。连接用 contextlib.closing 关闭,不能把 with con 误认为自动关闭连接。相关行为见 Python sqlite3 事务控制文档。
一、先决定金额单位与 NULL 的含义
本例的 amount_cents 表示同一种货币的最小单位,收入为正,支出为负,零也算一笔交易。不要先用二进制浮点数计算金额再乘一百;如果入口是十进制文本,应在业务边界明确精度、舍入和拒绝规则。多币种系统则需要把币种纳入分组键,不能直接把不同货币相加。
Python 边界检查使用 type(value) is int,因此会拒绝布尔值,避免 True 被当作一分。数据库的 NOT NULL 拒绝未知金额,typeof 检查约束存储后的类型。需要注意,SQLite 的 INTEGER 亲和性可能把可无损转换的文本或浮点值转成整数,所以数据库检查并不等同于检查调用方原始的 Python 类型。两层约束解决的是不同问题,详见 SQLite 类型与亲和性说明。
import sqlite3
from contextlib import closing
def require_cents(value):
if type(value) is not int:
raise TypeError("amount must be an int, not bool or float")
if not -(2**63) <= value < 2**63:
raise OverflowError("outside SQLite integer range")
return value
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.execute("CREATE TABLE t(cents INTEGER NOT NULL "
"CHECK(typeof(cents) = 'integer'))")
for value in (1250, -300, 0):
con.execute("INSERT INTO t VALUES(?)", (require_cents(value),))
assert con.execute("SELECT COUNT(*), SUM(cents) FROM t").fetchone() == (3, 950)
for bad in (True, 1.2, None):
try:
require_cents(bad)
except TypeError:
pass
else:
raise AssertionError("invalid amount accepted")
try:
con.execute("INSERT INTO t VALUES(?)", (None,))
except sqlite3.IntegrityError:
pass
else:
raise AssertionError("NULL accepted")
con.execute("DELETE FROM t")
empty = con.execute("SELECT COUNT(*), SUM(cents), "
"COALESCE(SUM(cents), 0) FROM t").fetchone()
assert empty == (0, None, 0)
print("net=950; empty:", empty)运行输出:
net=950; empty: (0, None, 0)
COUNT(*) 统计行数;没有输入行时,SUM 返回 NULL,而不是整数零。上例的 COALESCE 只用于把空集合的展示值变成零,不能拿它掩盖来源表里的未知金额。我们直接禁止金额为 NULL,使每一笔交易都对笔数和净额有明确贡献。这里也不使用返回浮点结果的 total();具体聚合语义见 SQLite SUM 与 total 文档。
二、定义一个可以直接检查的不变量
tx 保存交易编号、账户与整数金额。account_summary 对每个至少有一笔交易的账户保存一行,tx_count 等于明细笔数,net_cents 等于明细金额总和。没有交易的账户不保留缓存行;净额为零却有交易的账户必须保留。这一区分让末笔删除、冲销和空账户都有唯一的预期结果。
汇总表允许 tx_count 暂时为零,因为删除触发器会先减一,再删除空行。最终状态不应留下零笔缓存行;这个业务不变量由触发器和对账共同检查。该设计没有账户主表,不处理账户生命周期或外键级联,因此不能直接把删除账户等更复杂操作纳入本例已经验证的范围。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
""")
con.executemany("INSERT INTO tx VALUES(?, ?, ?)",
[(1, "A", 1250), (2, "A", -300), (3, "B", 0)])
expected = con.execute("SELECT account_id, COUNT(*), SUM(amount_cents) "
"FROM tx GROUP BY account_id ORDER BY account_id").fetchall()
con.execute("INSERT INTO account_summary "
"SELECT account_id, COUNT(*), SUM(amount_cents) "
"FROM tx GROUP BY account_id")
assert expected == [("A", 2, 950), ("B", 1, 0)]
assert con.execute("SELECT * FROM account_summary ORDER BY account_id").fetchall() == expected
print(expected)运行输出:
[('A', 2, 950), ('B', 1, 0)]这段只建立基线并初始化缓存,没有安装触发器,之后修改明细不会自动同步。真实迁移应在没有其他写入者穿插的事务内建立缓存、回填历史数据并安装三类触发器,验证一致后提交。不要在旧数据已经存在时只创建触发器,然后期待它们自动处理过去的记录。
三、INSERT:新增账户与已有账户走同一入口
插入触发器读取 NEW,首次见到账户时写入一笔及其金额,账户已存在时累加。account_id 的主键约束为冲突目标提供依据;excluded.net_cents 指这次准备插入的金额。这里的 UPSERT 发生在派生表内部,不是让应用随意采用各种冲突处理策略。其语义与版本要求见 SQLite UPSERT 官方说明。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
CREATE TRIGGER tx_ai AFTER INSERT ON tx BEGIN
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
""")
con.executemany("INSERT INTO tx VALUES(?, ?, ?)",
[(1, "A", 1250), (2, "A", -300), (3, "B", 0)])
actual = con.execute("SELECT * FROM account_summary ORDER BY account_id").fetchall()
assert actual == [("A", 2, 950), ("B", 1, 0)]
print(actual)运行输出:
[('A', 2, 950), ('B', 1, 0)]触发器是逐行执行的,所以批量插入会为实际插入的各行执行相应逻辑。本例仅安装 INSERT 触发器来隔离观察这一种变化,完整系统必须同时安装后面的 DELETE 与 UPDATE 触发器。业务 SQL 使用参数绑定,账户名称和金额都不通过字符串拼接进入 SQL。
四、DELETE:移除旧贡献,随后清理空账户
删除触发器只能依赖 OLD,不能再回头读取已经删除的那一行。对存在交易的账户,先将笔数减一、净额减去旧金额,再按笔数清理空行。删除一笔负数金额会让净额增加,这是减去旧贡献的自然结果;不能一概把删除理解成净额减少。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
CREATE TRIGGER tx_ai AFTER INSERT ON tx BEGIN
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
CREATE TRIGGER tx_ad AFTER DELETE ON tx BEGIN
UPDATE account_summary SET
tx_count = tx_count - 1,
net_cents = net_cents - OLD.amount_cents
WHERE account_id = OLD.account_id;
DELETE FROM account_summary
WHERE account_id = OLD.account_id AND tx_count = 0;
END;
""")
con.executemany("INSERT INTO tx VALUES(?, ?, ?)",
[(1, "A", 1250), (2, "A", -300), (3, "B", 0)])
con.execute("DELETE FROM tx WHERE id = ?", (1,))
assert con.execute("SELECT * FROM account_summary WHERE account_id = 'A'").fetchone() == ("A", 1, -300)
con.execute("DELETE FROM tx WHERE id IN (?, ?)", (2, 3))
assert con.execute("SELECT * FROM account_summary").fetchall() == []
con.execute("DELETE FROM tx WHERE id = ?", (999,))
print("all summaries removed:", con.execute("SELECT * FROM account_summary").fetchall())运行输出:
all summaries removed: []
删除不存在的交易不会产生逐行事件,因此汇总保持不变。清理条件必须是 tx_count=0,不能写成 net_cents=0,否则收入与支出相互抵消的账户会被误删。此处的正确性有一个重要前提:操作前缓存已经一致。若某个账户的缓存行被其他程序私自删除,UPDATE 可能匹配不到行,增量触发器不会自动恢复全部历史;这正是独立对账不可省略的原因。
五、UPDATE:撤销 OLD,再加入 NEW
更新是最容易漏掉的一类变化。同账户改金额,需要替换旧金额;跨账户改归属,则需要减少旧账户并增加新账户;如果两项同时改变,也应走同一个原则。下面将删除旧贡献和插入新贡献放在同一个 AFTER UPDATE 触发器里,避免把正确性建立在多个同类触发器的执行顺序上。
WHEN 使用 IS NOT 比较新旧值,未改变分组键和金额时不更新缓存;交易编号单独变化也不影响这两个统计值。本例没有使用 UPDATE OF 列清单,因此不受该清单中拼错列名却可能被静默忽略的问题影响。NEW、OLD 的可用范围、逐行触发和 UPDATE OF 的注意事项均可在 SQLite CREATE TRIGGER 文档核对。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
CREATE TRIGGER tx_ai AFTER INSERT ON tx BEGIN
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
CREATE TRIGGER tx_ad AFTER DELETE ON tx BEGIN
UPDATE account_summary SET
tx_count = tx_count - 1,
net_cents = net_cents - OLD.amount_cents
WHERE account_id = OLD.account_id;
DELETE FROM account_summary
WHERE account_id = OLD.account_id AND tx_count = 0;
END;
CREATE TRIGGER tx_au AFTER UPDATE ON tx
WHEN OLD.account_id IS NOT NEW.account_id
OR OLD.amount_cents IS NOT NEW.amount_cents
BEGIN
UPDATE account_summary SET
tx_count = tx_count - 1,
net_cents = net_cents - OLD.amount_cents
WHERE account_id = OLD.account_id;
DELETE FROM account_summary
WHERE account_id = OLD.account_id AND tx_count = 0;
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
""")
con.executemany("INSERT INTO tx VALUES(?, ?, ?)",
[(1, "A", 1250), (2, "A", -300), (3, "B", 0)])
con.execute("UPDATE tx SET amount_cents = ? WHERE id = ?", (1000, 1))
con.execute("UPDATE tx SET account_id = ?, amount_cents = ? WHERE id = ?",
("B", -200, 2))
con.execute("UPDATE tx SET account_id = ? WHERE id = ?", ("C", 1))
con.execute("UPDATE tx SET amount_cents = amount_cents WHERE id = ?", (3,))
actual = con.execute("SELECT * FROM account_summary ORDER BY account_id").fetchall()
assert actual == [("B", 2, -200), ("C", 1, 1000)]
print(actual)运行输出:
[('B', 2, -200), ('C', 1, 1000)]示例依次修改金额、把一笔支出从 A 移到 B,再把 A 的最后一笔移到 C。最后 A 没有缓存行,B 的零金额交易仍计入笔数,C 得到自己的贡献。代码把同账户替换也统一处理成先减后加,因此应为所有中间结果保留整数范围,不应只检查最后得到的净额。
六、回滚边界:语句失败不等于整批失败
触发器中的写入属于引发它的数据库操作,不是额外开启的独立提交。可是一个事务中第二条语句失败,并不意味着第一条成功语句也已经消失。下面有意先写入一笔有效交易,再触发 NOT NULL 错误:捕获异常时,第一笔及它的汇总仍存在,随后显式 ROLLBACK 才把整批撤销。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
CREATE TRIGGER tx_ai AFTER INSERT ON tx BEGIN
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
""")
con.execute("BEGIN IMMEDIATE")
try:
con.execute("INSERT INTO tx VALUES(?, ?, ?)", (1, "A", 100))
con.execute("INSERT INTO tx VALUES(?, ?, ?)", (2, "A", None))
con.execute("COMMIT")
except sqlite3.IntegrityError:
# The failing statement was undone; the earlier statement still exists.
assert con.in_transaction
assert con.execute("SELECT * FROM account_summary").fetchall() == [("A", 1, 100)]
con.execute("ROLLBACK")
else:
raise AssertionError("expected NOT NULL failure")
assert not con.in_transaction
assert con.execute("SELECT * FROM tx").fetchall() == []
assert con.execute("SELECT * FROM account_summary").fetchall() == []
print("batch rolled back: tx=0, summaries=0")运行输出:
batch rolled back: tx=0, summaries=0
本教程要求业务入口使用普通 INSERT、UPDATE、DELETE 的默认失败语义。不要换成 OR FAIL、OR IGNORE 或 INSERT OR REPLACE 后仍沿用同样的推理:FAIL 可以保留失败语句之前已修改的行,REPLACE 可能先删除冲突行,其删除触发器行为还与递归触发设置有关。尤其不能把 REPLACE 当作这里已经验证的 UPDATE。差异详见 SQLite 冲突处理说明。
实际业务的异常处理范围应覆盖所有需要一起成功的语句以及 COMMIT,并在连接仍处于事务中时回滚,然后把错误继续报告给调用方。如果在异常发生前已经提交,后面的 ROLLBACK 无法撤销那个提交;如果异常被吞掉后照常提交,程序也可能保存部分业务结果。需要嵌套局部撤销时应另行设计 SAVEPOINT,不能直接嵌套 BEGIN。
七、对账:同时发现缺行、多行与数值错误
对账不从缓存计算期望值,而是直接按明细重新聚合。只从明细 LEFT JOIN 缓存会漏掉缓存中的多余账户;只从缓存出发则会漏掉缺失账户。因此先取双方账户键的并集,再分别连接期望值和缓存值。这个过程应当只读,把发现差异与执行修复分成明确步骤。
比较条件使用 IS NOT,而不是普通的不等号。LEFT JOIN 找不到的一侧会产生 NULL,普通比较遇到 NULL 不能得到所需的真值,缺失行就可能悄悄漏过。IS NOT 在这些场景中能够比较空值状态,见 SQLite 表达式中的 IS 与 IS NOT。虽然源金额不允许 NULL,连接结果仍然可能包含 NULL,两者并不矛盾。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
""")
con.executemany("INSERT INTO tx VALUES(?, ?, ?)",
[(1, "A", 1250), (2, "A", -300), (3, "B", 0)])
# Deliberately inject three kinds of drift for the audit demonstration.
con.executemany("INSERT INTO account_summary VALUES(?, ?, ?)",
[("A", 2, 999), ("C", 1, 7)])
audit_sql = """
WITH expected AS (
SELECT account_id, COUNT(*) AS tx_count,
SUM(amount_cents) AS net_cents
FROM tx GROUP BY account_id
), keys AS (
SELECT account_id FROM expected
UNION
SELECT account_id FROM account_summary
)
SELECT k.account_id,
e.tx_count AS expected_count, s.tx_count AS cached_count,
e.net_cents AS expected_net, s.net_cents AS cached_net
FROM keys AS k
LEFT JOIN expected AS e ON e.account_id = k.account_id
LEFT JOIN account_summary AS s ON s.account_id = k.account_id
WHERE e.tx_count IS NOT s.tx_count
OR e.net_cents IS NOT s.net_cents
ORDER BY k.account_id
"""
diffs = con.execute(audit_sql).fetchall()
assert diffs == [("A", 2, 2, 950, 999),
("B", 1, None, 0, None),
("C", None, 1, None, 7)]
print(diffs)运行输出:
[('A', 2, 2, 950, 999), ('B', 1, None, 0, None), ('C', None, 1, None, 7)]输出依次包含账户、期望笔数、缓存笔数、期望净额和缓存净额。A 的金额错误,B 的缓存缺失,C 的缓存多余,三个问题都被保留下来。整段对账在一个 SELECT 中完成,避免先后两次查询遇到不同时间的数据。若将检查拆成多条查询,应该在同一个读事务中读取一致快照,再决定是否需要修复。
八、原子重建:要么得到新缓存,要么保留旧缓存
修复应重新从 tx 生成缓存,不能根据错误缓存继续增减。下面在 BEGIN IMMEDIATE 之后执行删除与回填,并故意模拟删除后中断。第一次重建失败时,旧缓存完整保留;第二次成功时,再以准确结果替换它。代码中的缓存污染仅用于演示,正常业务不应直接修改这张派生表。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
CREATE TRIGGER tx_ai AFTER INSERT ON tx BEGIN
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
CREATE TRIGGER tx_ad AFTER DELETE ON tx BEGIN
UPDATE account_summary SET
tx_count = tx_count - 1,
net_cents = net_cents - OLD.amount_cents
WHERE account_id = OLD.account_id;
DELETE FROM account_summary
WHERE account_id = OLD.account_id AND tx_count = 0;
END;
CREATE TRIGGER tx_au AFTER UPDATE ON tx
WHEN OLD.account_id IS NOT NEW.account_id
OR OLD.amount_cents IS NOT NEW.amount_cents
BEGIN
UPDATE account_summary SET
tx_count = tx_count - 1,
net_cents = net_cents - OLD.amount_cents
WHERE account_id = OLD.account_id;
DELETE FROM account_summary
WHERE account_id = OLD.account_id AND tx_count = 0;
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
""")
con.executemany("INSERT INTO tx VALUES(?, ?, ?)",
[(1, "A", 1250), (2, "A", -300), (3, "B", 0)])
con.execute("UPDATE account_summary SET net_cents = 999 WHERE account_id = 'A'")
before = con.execute("SELECT * FROM account_summary ORDER BY account_id").fetchall()
def rebuild(inject_failure=False):
con.execute("BEGIN IMMEDIATE")
try:
con.execute("DELETE FROM account_summary")
if inject_failure:
raise RuntimeError("simulated interruption")
con.execute("""
INSERT INTO account_summary(account_id, tx_count, net_cents)
SELECT account_id, COUNT(*), SUM(amount_cents)
FROM tx GROUP BY account_id
""")
con.execute("COMMIT")
except BaseException:
if con.in_transaction:
con.execute("ROLLBACK")
raise
try:
rebuild(inject_failure=True)
except RuntimeError:
pass
assert con.execute("SELECT * FROM account_summary ORDER BY account_id").fetchall() == before
rebuild()
actual = con.execute("SELECT * FROM account_summary ORDER BY account_id").fetchall()
assert actual == [("A", 2, 950), ("B", 1, 0)]
print("failure preserved old cache; rebuilt:", actual)运行输出:
failure preserved old cache; rebuilt: [('A', 2, 950), ('B', 1, 0)]BEGIN IMMEDIATE 在开始时申请写事务,让重建期间的其他写入者不能穿插修改明细;它并不保证永远成功,遇到其他写事务时可能忙等待后失败。应按业务要求设计超时和整项重试,而不是只重试回填中的某一条 SQL。SQLite 一次只允许一个写事务,以及读事务的快照行为,见 SQLite 事务官方文档。
重建函数要求调用时没有外层事务。它不用 executescript 执行业务批次,而是分别 execute 每个事务步骤,清晰保留失败位置和回滚边界。三类触发器都挂在 tx 上,重建只写 account_summary,不会给交易重复计数。上线前还应记录差异、查出污染来源并处理错误写入路径;反复重建不能替代根因修复。
九、用独立模型回归,而不是只看几次打印
最后一段包含完整建表与三类触发器,并用固定随机种子生成二百次插入、更新和删除。每一步同时比较 Python 字典模型、源表 GROUP BY 和缓存表,三者必须相等。随机序列补充前面的定向案例,但不能证明所有并发、崩溃、磁盘损坏或版本组合都已覆盖,正式系统仍需按自己的风险扩展测试。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
con.executescript("""
CREATE TABLE tx(
id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL CHECK(account_id <> ''),
amount_cents INTEGER NOT NULL
CHECK(typeof(amount_cents) = 'integer')
);
CREATE TABLE account_summary(
account_id TEXT PRIMARY KEY NOT NULL,
tx_count INTEGER NOT NULL
CHECK(typeof(tx_count) = 'integer' AND tx_count >= 0),
net_cents INTEGER NOT NULL
CHECK(typeof(net_cents) = 'integer')
);
CREATE TRIGGER tx_ai AFTER INSERT ON tx BEGIN
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
CREATE TRIGGER tx_ad AFTER DELETE ON tx BEGIN
UPDATE account_summary SET
tx_count = tx_count - 1,
net_cents = net_cents - OLD.amount_cents
WHERE account_id = OLD.account_id;
DELETE FROM account_summary
WHERE account_id = OLD.account_id AND tx_count = 0;
END;
CREATE TRIGGER tx_au AFTER UPDATE ON tx
WHEN OLD.account_id IS NOT NEW.account_id
OR OLD.amount_cents IS NOT NEW.amount_cents
BEGIN
UPDATE account_summary SET
tx_count = tx_count - 1,
net_cents = net_cents - OLD.amount_cents
WHERE account_id = OLD.account_id;
DELETE FROM account_summary
WHERE account_id = OLD.account_id AND tx_count = 0;
INSERT INTO account_summary(account_id, tx_count, net_cents)
VALUES(NEW.account_id, 1, NEW.amount_cents)
ON CONFLICT(account_id) DO UPDATE SET
tx_count = tx_count + 1,
net_cents = net_cents + excluded.net_cents;
END;
""")
import random
rng = random.Random(20261018)
model = {}
next_id = 1
def check():
totals = {}
for account, amount in model.values():
count, net = totals.get(account, (0, 0))
totals[account] = (count + 1, net + amount)
expected = sorted((a, n, s) for a, (n, s) in totals.items())
cached = con.execute("SELECT * FROM account_summary ORDER BY account_id").fetchall()
grouped = con.execute("SELECT account_id, COUNT(*), SUM(amount_cents) "
"FROM tx GROUP BY account_id ORDER BY account_id").fetchall()
assert cached == grouped == expected
for _ in range(200):
op = rng.choice(("insert", "update", "delete")) if model else "insert"
if op == "insert":
account, amount = rng.choice("ABC"), rng.randint(-5000, 5000)
con.execute("INSERT INTO tx VALUES(?, ?, ?)", (next_id, account, amount))
model[next_id] = (account, amount)
next_id += 1
elif op == "update":
key = rng.choice(sorted(model))
account, amount = rng.choice("ABC"), rng.randint(-5000, 5000)
con.execute("UPDATE tx SET account_id = ?, amount_cents = ? WHERE id = ?",
(account, amount, key))
model[key] = (account, amount)
else:
key = rng.choice(sorted(model))
con.execute("DELETE FROM tx WHERE id = ?", (key,))
del model[key]
check()
# A rejected statement must not alter either source rows or the cache.
for statement, params in [
("INSERT INTO tx VALUES(?, ?, ?)", (next_id, "A", None)),
("INSERT INTO tx VALUES(?, ?, ?)", (next_id, "A", 1.25)),
]:
try:
con.execute(statement, params)
except sqlite3.IntegrityError:
pass
else:
raise AssertionError("invalid amount accepted")
check()
# Explicit rollback also reverses all trigger effects.
con.execute("BEGIN IMMEDIATE")
con.execute("DELETE FROM tx")
assert con.execute("SELECT * FROM account_summary").fetchall() == []
con.execute("ROLLBACK")
check()
# Test an error inside the trigger, rather than only on the source table.
con.execute("INSERT INTO tx VALUES(?, ?, ?)", (next_id, "Z", 2**63 - 1))
model[next_id] = ("Z", 2**63 - 1)
next_id += 1
try:
con.execute("INSERT INTO tx VALUES(?, ?, ?)", (next_id, "Z", 1))
except sqlite3.IntegrityError:
pass
else:
raise AssertionError("summary overflow accepted")
check()
assert con.execute("SELECT COUNT(*) FROM tx WHERE id = ?", (next_id,)).fetchone() == (0,)
print("200 mutations + invalid inputs + rollback + trigger overflow: OK")运行输出:
200 mutations + invalid inputs + rollback + trigger overflow: OK
最后一项测试专门使汇总相加超出有符号六十四位整数范围:按照 SQLite 算术表达式规则,整数加法溢出时可能转为浮点结果,缓存列的 typeof 检查会拒绝它,使触发器与引发它的新明细写入一并失败。与此同时,SUM 在纯整数求和发生溢出时也可能报错;它不会自动得到任意精度整数。这意味着账户净额、累加过程和先减后加的中间结果都必须处于支持范围。若业务确实需要更大的范围,应重新选择表示与聚合方案,不要转换成 REAL 来让报错消失。
投产前至少再核对四件事:所有写入入口是否使用已验证的普通 DML;历史缓存是否在安装触发器时完成同事务初始化;是否禁止无关业务路径直接修改派生表;对账发现差异时是否有记录、修复与复查流程。若业务改成只统计已入账交易、按币种分组或保留空账户,必须同时修改触发器、基准聚合、重建和测试模型,不能只改其中一个查询。
本教程九段代码均以 python -X dev -W error 独立执行通过,连接显式关闭。官方来源于 2026 年 10 月 18 日核验。可靠的汇总缓存不只是三段触发器,而是同一组不变量贯穿数据入口、增量维护、事务边界、对账和重建。

