"""SQLite 分离数据库离线实验:实测多别名附加后单别名 DETACH、保留库 main/temp 不可分离及内存库分离销毁数据。"""
import json
import platform
import sqlite3
import tempfile
from pathlib import Path
def run() -> dict:
cases = []
with tempfile.TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
test_db = tmp / "testDB.db"
conn = sqlite3.connect(str(test_db))
try:
conn.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT);")
conn.execute("INSERT INTO items VALUES (1, 'persisted');")
conn.commit()
# Case 1: Attach same file under 'test' and 'currentDB', then DETACH only 'currentDB'
conn.execute(f"ATTACH DATABASE '{test_db.as_posix()}' AS 'test';")
conn.execute(f"ATTACH DATABASE '{test_db.as_posix()}' AS 'currentDB';")
before_detach = [r[1] for r in conn.execute("PRAGMA database_list;").fetchall()]
conn.execute("DETACH DATABASE 'currentDB';")
after_detach = [r[1] for r in conn.execute("PRAGMA database_list;").fetchall()]
still_readable = conn.execute("SELECT name FROM test.items WHERE id = 1;").fetchone()[0]
exp1 = {
"before_detach": ["main", "test", "currentDB"],
"after_detach": ["main", "test"],
"test_alias_still_valid": "persisted",
}
act1 = {
"before_detach": before_detach,
"after_detach": after_detach,
"test_alias_still_valid": still_readable,
}
cases.append({
"name": "detach_single_alias_preserves_others",
"summary": "同一库附加为 test 与 currentDB 后,DETACH DATABASE 'currentDB' 仅断开该别名而保留 main 与 test",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
})
# Case 2: Cannot DETACH main or temp (materialize temp schema first)
conn.execute("CREATE TEMP TABLE tmp_guard (x INT);")
conn.commit()
detach_errors = {}
for alias in ("main", "temp"):
try:
conn.execute(f"DETACH DATABASE {alias};")
detach_errors[alias] = "unexpected_success"
except sqlite3.OperationalError as exc:
detach_errors[alias] = str(exc)
exp2 = {
"main": "cannot detach database main",
"temp": "cannot detach database temp",
}
cases.append({
"name": "cannot_detach_main_or_temp",
"summary": "验证尝试分离保留数据库 main 或 temp 时抛出 OperationalError",
"expected": exp2,
"actual": detach_errors,
"passed": detach_errors == exp2,
})
# Case 3: Detaching an attached in-memory database destroys its contents
conn.execute("ATTACH DATABASE ':memory:' AS scratch;")
conn.execute("CREATE TABLE scratch.ephemeral (x INTEGER);")
conn.execute("INSERT INTO scratch.ephemeral VALUES (42);")
conn.commit()
before_mem_count = conn.execute("SELECT COUNT(*) FROM scratch.ephemeral;").fetchone()[0]
conn.execute("DETACH DATABASE scratch;")
conn.execute("ATTACH DATABASE ':memory:' AS scratch;")
tables_after_reattach = [
r[0] for r in conn.execute("SELECT name FROM scratch.sqlite_master WHERE type='table';").fetchall()
]
conn.execute("DETACH DATABASE scratch;")
exp3 = {"before_mem_count": 1, "tables_after_reattach": []}
act3 = {"before_mem_count": before_mem_count, "tables_after_reattach": tables_after_reattach}
cases.append({
"name": "detach_in_memory_destroys_content",
"summary": "验证分离附加的 ':memory:' 内存数据库后原表与数据立即销毁,重新附加为全新空库",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
})
finally:
conn.close()
return {
"version": f"CPython {platform.python_version()} / Native SQLite {sqlite3.sqlite_version}",
"cases": cases,
}
if __name__ == "__main__":
print(json.dumps(run(), ensure_ascii=False, indent=2))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/sqlite-detach-database-lab/explore-detach-database.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-detach-database.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联51章) · 含当前章节或实例 · mbskycom202612a1680.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1690.zip