Python sqlite3 实战:文章改名后如何保留旧网址与 slug 别名
文章标题改了,网址也想跟着改,这是内容系统很常见的小需求。真正棘手的地方却在发布之后:收藏夹、站外引用、旧邮件以及缓存中的地址不会同步更新。如果把旧 slug 直接覆盖掉,文章虽然还在,原来的入口已经消失;如果每次只增加一条旧地址到新地址的映射,多次改名又会逐渐形成跳转链。
本文把问题拆成三个不同的东西:稳定的文章 ID 表示内容身份,当前规范 slug 表示今天希望公开使用的地址,历史别名表示仍然有效的旧入口。名称可以变化,身份保持不变。所有 slug 都登记在同一张表中,并直接关联文章 ID;解析时再读取文章的当前规范地址。这是本文自行设计的一种应用模型,而不是 SQLite 自带的网址管理功能。
下面九个示例都能单独复制运行,不依赖其他示例、第三方库或预先存在的数据库。运行环境为 Python 3.12 及以上;代码显式设置 autocommit=True,再用 SQL 管理事务。为便于独立验证,部分建表与辅助函数会重复出现。内存数据库只用于演示,双写入示例会创建并清理临时数据库文件;每一段都包含断言,随后给出完整的预期输出。

一、先把 slug 的等价规则写成代码
同一篇文章如果同时接受 Python-SQLite 与 python-sqlite,却允许这两个值分别被不同文章占用,冲突检查就失去了意义。本文选择明确而保守的规则:只使用 ASCII 字母、数字与单个连字符,长度为一到八十个字符,统一转为小写,不接受首尾空白、连续连字符或路径分隔符。文章标题仍然可以使用中文,标题与 slug 无须完全一致。
这里刻意不把任意输入自动转换成看起来可用的地址。删除标点、合并字符或翻译中文都会产生额外的碰撞规则,应当由独立的地址生成流程处理。normalize_slug 负责验证和规范化已经选好的候选地址,不能代替命名策略。先检查 isascii,也避免某些非 ASCII 字符经大小写转换后进入原本没有允许的范围。
数据库沿用普通二进制比较,因为写入前已经规范化。SQLite 内置 NOCASE 只处理 ASCII 范围的大小写,并不是完整的 Unicode 大小写折叠。如果项目将来支持国际化 slug,应先固定 Unicode 规范化、大小写与碰撞策略,再迁移已有地址;不要直接换一个比较规则就假设历史数据仍然互不冲突。
大小写处理依据可参阅 SQLite 比较规则文档。
独立示例:01_normalization.py。运行后输出如下所示。
import re
def normalize_slug(raw):
if not isinstance(raw, str) or not raw.isascii():
raise ValueError("ASCII slug required")
value = raw.lower()
if not 1 <= len(value) <= 80:
raise ValueError("slug length must be 1..80")
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", value) is None:
raise ValueError("invalid slug")
return value
assert normalize_slug("Python-SQLite-3") == "python-sqlite-3"
assert normalize_slug("a" * 80) == "a" * 80
for bad in ("", " title", "a--b", "a/b", "a%2fb", "中文", "a" * 81):
try:
normalize_slug(bad)
except ValueError:
pass
else:
raise AssertionError(bad)
print("canonical=python-sqlite-3; rejected=7")预期输出:
canonical=python-sqlite-3; rejected=7
二、让当前地址与旧地址共享一个名称空间
把当前 slug 放在文章表、旧 slug 放在另一张仅存历史地址的表,看起来很自然,却容易漏掉跨表冲突:新文章可能恰好占用了另一篇文章的旧地址。这里让 slug 表保存所有已分配地址,主键保证整个文章路由名称空间只有一个所有者。所谓全局,范围是本文这一套文章路由;多租户或多语言站点应明确是否还需要把站点、租户或语言加入联合键。
article 表只保存一个当前规范 slug。复合外键同时检查地址和文章 ID,因此当前地址不仅必须存在,还必须属于这篇文章。slug 表反过来引用文章身份。新建文章时会短暂出现文章已有、地址尚未插入的中间状态,所以当前地址的复合外键延迟到事务提交时验证。创建文章与分配初始地址必须在同一事务里完成,不能先提交半个对象。
示例中的 CHECK 是数据库侧的第二道格式检查;TEXT 主键仍显式声明 NOT NULL。每个连接都在事务开始前启用并验证 foreign_keys,避免把数据库文件建有外键误认为所有连接都会自动检查。SQL 参数始终通过占位符绑定,地址字符串不参与拼接 SQL。建表用的 executescript 只在初始化阶段调用,不放进改名事务中。
复合与延迟外键、逐连接启用的细节见 SQLite 外键说明;主键与检查约束见 CREATE TABLE 文档。
独立示例:02_namespace.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
with closing(open_db()) as db:
seed(db)
try:
db.execute("INSERT INTO slug VALUES (?, ?)", ("first-title", 42))
except sqlite3.IntegrityError:
pass
else:
raise AssertionError("global namespace was not enforced")
db.execute("BEGIN IMMEDIATE")
try:
db.execute("UPDATE article SET canonical_slug = ? WHERE article_id = ?",
("other-article", 41))
db.execute("COMMIT")
except sqlite3.IntegrityError:
db.execute("ROLLBACK")
else:
raise AssertionError("canonical slug accepted the wrong owner")
assert db.execute("SELECT canonical_slug FROM article WHERE article_id = 41").fetchone() == ("first-title",)
assert db.execute("PRAGMA foreign_key_check").fetchall() == []
print("namespace=unique; canonical-owner=verified")预期输出:
namespace=unique; canonical-owner=verified
三、一次改名就是一个完整事务
改名需要完成三个动作:必要时登记新地址、切换文章当前地址、写入成功审计。这些动作要么一起提交,要么一起撤销。旧地址无须搬家,也无须改成指向新地址;它原本就指向稳定文章 ID。这样保留历史入口是默认行为,不再依赖额外的补救操作。
函数使用 BEGIN IMMEDIATE,在读取当前状态与目标所有者之前先尝试取得写事务。找到目标地址之后只有三种结果:未分配时插入;属于本文章时允许重新启用历史地址;属于其他文章时拒绝。相同规范地址的重复请求是无操作,不额外生成审计事件。本文函数自行管理事务,发现调用方已有事务就明确报错,避免在外层事务中悄悄提交别的业务修改。
捕获异常后检查 in_transaction,再执行显式 ROLLBACK。COMMIT 也在异常处理范围内,因为延迟外键或锁争用可能在提交阶段才暴露问题。autocommit=True 模式下不依赖 Connection.commit、rollback 或连接上下文管理器完成这些显式事务;closing 只负责可靠关闭连接。这种选择把控制边界留在代码中,便于测试和审查。
显式事务和连接行为可对照 Python 3.12 sqlite3 事务控制文档。
独立示例:03_atomic_rename.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
import re
def normalize_slug(raw):
if not isinstance(raw, str) or not raw.isascii():
raise ValueError("ASCII slug required")
value = raw.lower()
if not 1 <= len(value) <= 80:
raise ValueError("slug length must be 1..80")
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", value) is None:
raise ValueError("invalid slug")
return value
def rename_article(db, article_id, raw, actor="editor-7"):
new = normalize_slug(raw)
if db.in_transaction:
raise RuntimeError("rename needs its own transaction")
db.execute("BEGIN IMMEDIATE")
try:
row = db.execute(
"SELECT canonical_slug, deleted FROM article WHERE article_id = ?",
(article_id,)).fetchone()
if row is None or row[1]:
raise LookupError("active article required")
old = row[0]
if old != new:
owner = db.execute("SELECT article_id FROM slug WHERE slug = ?",
(new,)).fetchone()
if owner is not None and owner[0] != article_id:
raise ValueError("slug belongs to another article")
if owner is None:
db.execute("INSERT INTO slug VALUES (?, ?)", (new, article_id))
db.execute("UPDATE article SET canonical_slug = ? WHERE article_id = ?",
(new, article_id))
db.execute("""INSERT INTO rename_audit
(article_id, old_slug, new_slug, actor) VALUES (?, ?, ?, ?)""",
(article_id, old, new, actor))
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
return new
with closing(open_db()) as db:
seed(db)
assert rename_article(db, 41, "Second-Title") == "second-title"
assert db.execute("SELECT slug FROM slug WHERE article_id = 41 ORDER BY slug").fetchall() == [("first-title",), ("second-title",)]
assert db.execute("SELECT canonical_slug FROM article WHERE article_id = 41").fetchone() == ("second-title",)
assert db.execute("SELECT old_slug, new_slug FROM rename_audit").fetchall() == [("first-title", "second-title")]
assert not db.in_transaction
print("article=41; canonical=second-title; aliases=2; audit=1")预期输出:
article=41; canonical=second-title; aliases=2; audit=1
四、解析时直接找到身份,再得到最新地址
解析只需要一次联表查询:输入 slug 找到其所属文章,再读取该文章当前的 canonical_slug。表中没有 next_slug 字段,也没有递归追踪目标的循环。即使文章经过十次改名,第一次使用过的地址仍然能够直接算出今天的规范地址。示例把首次地址、中间地址和大小写变体都解析到同一个最终结果。
返回的三元组分别表示状态码、文章 ID 和可选的站内跳转地址,尚未绑定具体 Web 框架。公开只读文章页可以把历史入口映射为 308,并将第三项设为 Location;规范地址返回 200,未找到的合法地址返回 404。308 会保留请求方法,因此不要把这段公开阅读路由的策略直接套到提交表单或其他写入接口。
传入参数应是框架已经解析的一段路径,不是完整 URL,也不要在这里再做一次百分号解码。查询参数、尾随斜线和主机名由外层路由独立处理。跳转目标只由数据库中经过检查的规范 slug 与固定站内前缀组成,不能接受用户传入的任意外部网址。数据库保证的是每次当前解析直接得到目标;客户端若缓存过旧的永久跳转,仍可能先经过旧缓存,因此频繁改名时还要设计缓存策略。
状态码含义参阅 RFC 9110 的 308 定义;返回结构是本文为演示设计的应用接口。
独立示例:04_direct_resolution.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
import re
def normalize_slug(raw):
if not isinstance(raw, str) or not raw.isascii():
raise ValueError("ASCII slug required")
value = raw.lower()
if not 1 <= len(value) <= 80:
raise ValueError("slug length must be 1..80")
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", value) is None:
raise ValueError("invalid slug")
return value
def resolve(db, raw):
try:
key = normalize_slug(raw)
except ValueError:
return (404, None, None)
row = db.execute("""
SELECT a.article_id, a.canonical_slug, a.deleted
FROM slug AS s JOIN article AS a ON a.article_id = s.article_id
WHERE s.slug = ?
""", (key,)).fetchone()
if row is None:
return (404, None, None)
article_id, canonical, deleted = row
if deleted:
return (410, None, None)
if raw != canonical:
return (308, article_id, "/articles/" + canonical)
return (200, article_id, None)
with closing(open_db()) as db:
seed(db)
db.execute("BEGIN IMMEDIATE")
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("middle-title", 41), ("latest-title", 41)])
db.execute("UPDATE article SET canonical_slug = ? WHERE article_id = ?",
("latest-title", 41))
db.execute("COMMIT")
expected = (308, 41, "/articles/latest-title")
assert resolve(db, "first-title") == expected
assert resolve(db, "middle-title") == expected
assert resolve(db, "LATEST-TITLE") == expected
assert resolve(db, "latest-title") == (200, 41, None)
assert resolve(db, "missing") == (404, None, None)
print("old=308/latest-title; middle=308/latest-title; current=200")预期输出:
old=308/latest-title; middle=308/latest-title; current=200
五、区分名称冲突与执行到一半的失败
改名为别人的当前地址会冲突,改名为别人的历史地址也应该冲突。不能因为旧地址不再显示在文章首页,就把它当成空闲名称。名称冲突可以向编辑者显示清晰的业务错误,但底层约束仍然要保留,作为遗漏检查或未来新增写入路径时的兜底。
更容易漏测的是后半段失败:新地址已插入,当前地址已切换,审计写入却失败。如果只捕获异常并返回错误而没有回滚,数据库可能保留一部分修改。下面使用触发器故意拒绝审计插入,确认整个改名事务撤销后,没有泄漏新别名、没有改变规范地址,也没有留下假成功记录。
不要用 INSERT OR REPLACE 来解决地址占用。SQLite 的 REPLACE 在唯一键冲突时可能删除已有行再写入新行,这与保留原所有者的需求方向相反。默认约束失败也不等于整笔业务事务自动回滚,因此必须把错误处理放在业务事务边界;不要根据一句异常消息就假设前面的 SQL 全部撤销了。
语句回退与整笔事务回退的区别,以及 REPLACE 的删除行为,见 SQLite 冲突处理文档。
独立示例:05_rollback.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
import re
def normalize_slug(raw):
if not isinstance(raw, str) or not raw.isascii():
raise ValueError("ASCII slug required")
value = raw.lower()
if not 1 <= len(value) <= 80:
raise ValueError("slug length must be 1..80")
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", value) is None:
raise ValueError("invalid slug")
return value
def rename_article(db, article_id, raw, actor="editor-7"):
new = normalize_slug(raw)
if db.in_transaction:
raise RuntimeError("rename needs its own transaction")
db.execute("BEGIN IMMEDIATE")
try:
row = db.execute(
"SELECT canonical_slug, deleted FROM article WHERE article_id = ?",
(article_id,)).fetchone()
if row is None or row[1]:
raise LookupError("active article required")
old = row[0]
if old != new:
owner = db.execute("SELECT article_id FROM slug WHERE slug = ?",
(new,)).fetchone()
if owner is not None and owner[0] != article_id:
raise ValueError("slug belongs to another article")
if owner is None:
db.execute("INSERT INTO slug VALUES (?, ?)", (new, article_id))
db.execute("UPDATE article SET canonical_slug = ? WHERE article_id = ?",
(new, article_id))
db.execute("""INSERT INTO rename_audit
(article_id, old_slug, new_slug, actor) VALUES (?, ?, ?, ?)""",
(article_id, old, new, actor))
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
return new
with closing(open_db()) as db:
seed(db)
try:
rename_article(db, 41, "other-article")
except ValueError:
pass
else:
raise AssertionError("conflict was accepted")
# Simulate an audit write failure after inserting and switching the slug.
db.execute("""CREATE TRIGGER reject_audit BEFORE INSERT ON rename_audit
BEGIN SELECT RAISE(ABORT, 'audit unavailable'); END""")
try:
rename_article(db, 41, "new-title")
except sqlite3.IntegrityError:
pass
else:
raise AssertionError("injected failure did not occur")
assert db.execute("SELECT canonical_slug FROM article WHERE article_id = 41").fetchone() == ("first-title",)
assert db.execute("SELECT article_id FROM slug WHERE slug = 'new-title'").fetchone() is None
assert db.execute("SELECT COUNT(*) FROM rename_audit").fetchone() == (0,)
assert not db.in_transaction
print("conflict=rejected; canonical=unchanged; leaked-aliases=0")预期输出:
conflict=rejected; canonical=unchanged; leaked-aliases=0
六、两个编辑者同时抢一个名称会发生什么
应用层先查询再插入并不自动消除竞争,尤其当查询发生在事务之外时。本文把检查和修改放在同一个立即写事务中,数据库仍以唯一键作最终裁决。SQLite 同一时间只有一个写事务;另一个连接可能在 BEGIN IMMEDIATE 就遇到 SQLITE_BUSY,而不是等到真正插入时才失败。
此示例用两个独立连接和 timeout=0 构造可重复的争用,不依赖线程调度或任意时长的 sleep。第一个连接持有写事务时,第二个连接拿不到写锁。第一个连接提交目标地址后,第二个连接重新开始事务,看到的结果已经变成名称冲突。锁等待与业务冲突是两类问题,界面和日志不应该把它们混为一谈。
生产连接应配置符合延迟目标的等待时间;确实需要重试时,应重新运行有边界的整笔业务操作,并在新事务中重新读取所有者。不要在失败事务中继续执行剩余步骤,也不要把所有 OperationalError 都当作临时锁竞争。若客户端可能在提交成功后丢失响应,可按业务需要加入请求幂等键;这里只演示相同当前地址请求的无操作语义。
单写入者、立即事务与 SQLITE_BUSY 的边界见 SQLite 事务说明。
独立示例:06_two_writers.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = str(Path(folder) / "articles.db")
with closing(open_db(path, 0.0)) as first, closing(open_db(path, 0.0)) as second:
seed(first)
first.execute("BEGIN IMMEDIATE")
try:
second.execute("BEGIN IMMEDIATE")
except sqlite3.OperationalError as exc:
assert exc.sqlite_errorcode == sqlite3.SQLITE_BUSY
else:
raise AssertionError("second writer unexpectedly acquired the lock")
first.execute("INSERT INTO slug VALUES (?, ?)", ("shared-title", 41))
first.execute("COMMIT")
second.execute("BEGIN IMMEDIATE")
try:
second.execute("INSERT INTO slug VALUES (?, ?)", ("shared-title", 42))
except sqlite3.IntegrityError:
second.execute("ROLLBACK")
else:
raise AssertionError("duplicate ownership was accepted")
assert second.execute("SELECT article_id FROM slug WHERE slug = ?",
("shared-title",)).fetchone() == (41,)
print("writer-2=busy; retry=conflict; owner=41")预期输出:
writer-2=busy; retry=conflict; owner=41
七、内容删除后,地址是否还能交给别人
本文选择保留占位的软删除策略:将文章标记为 deleted,文章 ID 与全部地址绑定继续保留。所有命中这篇文章的入口先检查删除状态,再决定响应,因此不会先跳转到一个已删除的规范地址。公开且确定永久撤下的内容在示例中返回 410;从未分配过的地址仍返回 404。
这是一项产品政策,不是所有站点都必须采用的标准答案。如果暴露内容曾经存在本身就会泄露信息,可以统一返回 404;仅暂时下架或权限不足的情况,也不应机械套用永久删除的语义。对于需登录的内容,认证、授权与存在性隐藏应在外层有一致规则,不能仅凭 slug 命中就展示身份信息。
不回收旧名称的好处是旧引用不会突然指向完全无关的新文章,代价是名称空间会持续增长。本文业务 API 不提供改文章 ID、转让地址或删除历史绑定的操作。若未来必须清除正文,可把正文与最小身份占位拆开,按真实保留政策处理;如果允许其他程序直接写数据库,还需要补充权限边界或触发器,不能把本教程函数当作能约束所有任意 SQL 的安全沙箱。
410 的语义见 RFC 9110 的 Gone 定义,是否对外区分历史存在状态仍由产品政策决定。
独立示例:07_deleted_content.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
import re
def normalize_slug(raw):
if not isinstance(raw, str) or not raw.isascii():
raise ValueError("ASCII slug required")
value = raw.lower()
if not 1 <= len(value) <= 80:
raise ValueError("slug length must be 1..80")
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", value) is None:
raise ValueError("invalid slug")
return value
def resolve(db, raw):
try:
key = normalize_slug(raw)
except ValueError:
return (404, None, None)
row = db.execute("""
SELECT a.article_id, a.canonical_slug, a.deleted
FROM slug AS s JOIN article AS a ON a.article_id = s.article_id
WHERE s.slug = ?
""", (key,)).fetchone()
if row is None:
return (404, None, None)
article_id, canonical, deleted = row
if deleted:
return (410, None, None)
if raw != canonical:
return (308, article_id, "/articles/" + canonical)
return (200, article_id, None)
with closing(open_db()) as db:
seed(db)
db.execute("INSERT INTO slug VALUES (?, ?)", ("old-title", 41))
db.execute("UPDATE article SET deleted = 1 WHERE article_id = 41")
for key in ("first-title", "old-title", "FIRST-TITLE"):
assert resolve(db, key) == (410, None, None)
try:
db.execute("INSERT INTO slug VALUES (?, ?)", ("old-title", 42))
except sqlite3.IntegrityError:
pass
else:
raise AssertionError("deleted address was recycled")
assert db.execute("SELECT COUNT(*) FROM slug WHERE article_id = 41").fetchone() == (2,)
assert resolve(db, "never-used") == (404, None, None)
print("deleted=410; retained-slugs=2; reuse=blocked")预期输出:
deleted=410; retained-slugs=2; reuse=blocked
八、让审计记录回答实际问题
审计至少需要知道哪篇文章从哪个地址改到哪个地址、由谁执行以及何时发生。这里用内部操作者标识而不是姓名或邮箱,避免在示例中扩散个人信息。事件序号用于本数据库内的稳定读取顺序,时间字段用于排查,但不应把同一秒的时间戳当作唯一排序依据。
成功审计与改名共享事务,意味着记录出现就代表那次改名已提交,回滚不会留下成功事件。相同当前地址的重复调用不写新事件,重新启用本文章旧地址则写一条真实变化记录,而且不会新增重复绑定。失败尝试如果需要追踪,应写入独立的运行日志并控制敏感信息,不要把失败硬塞进这一张成功变更表。
定期执行 foreign_key_check 可以检查外键关系,再用针对业务不变量的查询检查每篇文章的规范地址是否正确归属。quick_check 是快速结构检查,并不能替代外键检查、完整性检查或业务语义验证。示例里的断言只是最小巡检集合;审计表也不是防篡改账本,数据库管理员仍可直接修改它,若有更高要求就需要独立留存与访问控制。
检查指令的作用范围可查阅 foreign_key_check 与 quick_check 官方说明。
独立示例:08_audit_checks.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
import re
def normalize_slug(raw):
if not isinstance(raw, str) or not raw.isascii():
raise ValueError("ASCII slug required")
value = raw.lower()
if not 1 <= len(value) <= 80:
raise ValueError("slug length must be 1..80")
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", value) is None:
raise ValueError("invalid slug")
return value
def rename_article(db, article_id, raw, actor="editor-7"):
new = normalize_slug(raw)
if db.in_transaction:
raise RuntimeError("rename needs its own transaction")
db.execute("BEGIN IMMEDIATE")
try:
row = db.execute(
"SELECT canonical_slug, deleted FROM article WHERE article_id = ?",
(article_id,)).fetchone()
if row is None or row[1]:
raise LookupError("active article required")
old = row[0]
if old != new:
owner = db.execute("SELECT article_id FROM slug WHERE slug = ?",
(new,)).fetchone()
if owner is not None and owner[0] != article_id:
raise ValueError("slug belongs to another article")
if owner is None:
db.execute("INSERT INTO slug VALUES (?, ?)", (new, article_id))
db.execute("UPDATE article SET canonical_slug = ? WHERE article_id = ?",
(new, article_id))
db.execute("""INSERT INTO rename_audit
(article_id, old_slug, new_slug, actor) VALUES (?, ?, ?, ?)""",
(article_id, old, new, actor))
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
return new
with closing(open_db()) as db:
seed(db)
rename_article(db, 41, "second-title", "editor-7")
rename_article(db, 41, "second-title", "editor-7") # No-op.
rename_article(db, 41, "first-title", "editor-8") # Reuse own alias.
events = db.execute("""SELECT old_slug, new_slug, actor
FROM rename_audit ORDER BY event_id""").fetchall()
assert events == [("first-title", "second-title", "editor-7"),
("second-title", "first-title", "editor-8")]
assert db.execute("SELECT COUNT(*) FROM slug WHERE article_id = 41").fetchone() == (2,)
assert db.execute("PRAGMA foreign_key_check").fetchall() == []
assert db.execute("PRAGMA quick_check").fetchall() == [("ok",)]
mismatches = db.execute("""SELECT a.article_id FROM article AS a
LEFT JOIN slug AS s ON s.slug = a.canonical_slug
AND s.article_id = a.article_id WHERE s.slug IS NULL""").fetchall()
assert mismatches == []
print("audit-events=2; no-op-events=0; invariant-errors=0")预期输出:
audit-events=2; no-op-events=0; invariant-errors=0
九、用一组状态变化验证整个模型
最后把规范化、登记表、改名和解析放进同一个可独立运行的脚本。测试故意反复改名、重新启用旧地址、重复提交当前地址,并让另一篇文章尝试抢占历史别名。每一次状态变化之后,所有已用过的地址都要重新验证:只有当前地址返回内容,其余地址直接给出当前规范地址。
随后把文章标记删除,确认所有历史入口都返回同一种删除结果,且删除后的改名请求不会偷偷分配新地址。这样的测试关注长期不变量,比仅检查第二次改名是否成功更有价值。它也能在以后加入编辑权限、版本控制、事务封装或缓存时,帮助识别原本没有的问题是否被新路径带了进来。
实际接入时,还要在事务提交后失效相关缓存,并让站内链接、站点地图与页面规范地址声明采用当前 canonical_slug。若需要防止两位编辑者互相覆盖意图,可以给文章加入版本号并在更新时检查旧版本,本文的写锁只保护事务一致性,不代表已经实现这种编辑冲突检测。正文与标题更新是否和改名同事务,应由业务需求决定,不应在没有明确边界时随意混用。
独立示例:09_regression_model.py。运行后输出如下所示。
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE article(
article_id INTEGER PRIMARY KEY,
canonical_slug TEXT NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0 CHECK(deleted IN (0, 1)),
FOREIGN KEY(canonical_slug, article_id)
REFERENCES slug(slug, article_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE slug(
slug TEXT PRIMARY KEY NOT NULL CHECK(
length(slug) BETWEEN 1 AND 80
AND slug NOT GLOB '*[^a-z0-9-]*'
AND substr(slug, 1, 1) != '-'
AND substr(slug, -1, 1) != '-'
AND instr(slug, '--') = 0
AND instr(slug, char(0)) = 0),
article_id INTEGER NOT NULL REFERENCES article(article_id),
UNIQUE(slug, article_id)
);
CREATE INDEX slug_article_idx ON slug(article_id);
CREATE TABLE rename_audit(
event_id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES article(article_id),
old_slug TEXT NOT NULL,
new_slug TEXT NOT NULL,
actor TEXT NOT NULL,
changed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def open_db(path=":memory:", timeout=5.0):
db = sqlite3.connect(path, autocommit=True, timeout=timeout)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
return db
def seed(db):
db.executescript(SCHEMA)
db.execute("BEGIN IMMEDIATE")
try:
db.executemany(
"INSERT INTO article(article_id, canonical_slug) VALUES (?, ?)",
[(41, "first-title"), (42, "other-article")])
db.executemany("INSERT INTO slug VALUES (?, ?)",
[("first-title", 41), ("other-article", 42)])
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
import re
def normalize_slug(raw):
if not isinstance(raw, str) or not raw.isascii():
raise ValueError("ASCII slug required")
value = raw.lower()
if not 1 <= len(value) <= 80:
raise ValueError("slug length must be 1..80")
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", value) is None:
raise ValueError("invalid slug")
return value
def rename_article(db, article_id, raw, actor="editor-7"):
new = normalize_slug(raw)
if db.in_transaction:
raise RuntimeError("rename needs its own transaction")
db.execute("BEGIN IMMEDIATE")
try:
row = db.execute(
"SELECT canonical_slug, deleted FROM article WHERE article_id = ?",
(article_id,)).fetchone()
if row is None or row[1]:
raise LookupError("active article required")
old = row[0]
if old != new:
owner = db.execute("SELECT article_id FROM slug WHERE slug = ?",
(new,)).fetchone()
if owner is not None and owner[0] != article_id:
raise ValueError("slug belongs to another article")
if owner is None:
db.execute("INSERT INTO slug VALUES (?, ?)", (new, article_id))
db.execute("UPDATE article SET canonical_slug = ? WHERE article_id = ?",
(new, article_id))
db.execute("""INSERT INTO rename_audit
(article_id, old_slug, new_slug, actor) VALUES (?, ?, ?, ?)""",
(article_id, old, new, actor))
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
return new
def resolve(db, raw):
try:
key = normalize_slug(raw)
except ValueError:
return (404, None, None)
row = db.execute("""
SELECT a.article_id, a.canonical_slug, a.deleted
FROM slug AS s JOIN article AS a ON a.article_id = s.article_id
WHERE s.slug = ?
""", (key,)).fetchone()
if row is None:
return (404, None, None)
article_id, canonical, deleted = row
if deleted:
return (410, None, None)
if raw != canonical:
return (308, article_id, "/articles/" + canonical)
return (200, article_id, None)
with closing(open_db()) as db:
seed(db)
history = {"first-title"}
changes = ["v2", "v3", "first-title", "v4", "v4", "v2"]
for raw in changes:
current = rename_article(db, 41, raw)
history.add(current)
for old in history:
expected = (200, 41, None) if old == current else (
308, 41, "/articles/" + current)
assert resolve(db, old) == expected
assert db.execute("PRAGMA foreign_key_check").fetchall() == []
try:
rename_article(db, 42, "v3")
except ValueError:
pass
else:
raise AssertionError("historical alias was stolen")
assert resolve(db, "other-article") == (200, 42, None)
assert db.execute("SELECT COUNT(*) FROM rename_audit").fetchone() == (5,)
assert db.execute("SELECT COUNT(*) FROM slug WHERE article_id = 41").fetchone() == (4,)
db.execute("UPDATE article SET deleted = 1 WHERE article_id = 41")
for old in history:
assert resolve(db, old) == (410, None, None)
try:
rename_article(db, 41, "after-delete")
except LookupError:
pass
else:
raise AssertionError("deleted article was renamed")
assert db.execute("SELECT article_id FROM slug WHERE slug = 'after-delete'").fetchone() is None
assert not db.in_transaction
print("regression=passed; history=4; changes=5; deleted-aliases=410")预期输出:
regression=passed; history=4; changes=5; deleted-aliases=410
把可变名称留给路由,把稳定身份留给数据
可靠的旧网址支持并不需要堆积一条条跳转规则。关键是把地址归属作为长期数据保存,让当前地址与历史地址接受同一套唯一性检查,再用事务维护当前指针与成功审计。文章改名时身份不变,地址发生冲突时整体失败,内容删除时策略一致,这三个原则明确之后,旧链接才真正成为可以验证和维护的系统能力。

