Python SQLite 备份别只复制文件:用 backup() 固定快照,再独立打开验证

10-20 11阅读

给 SQLite 做备份,最容易误判的时刻不是报错,而是脚本安静地复制出了一个文件。文件存在,不代表它包含已提交的数据;查询能打开,也不代表业务能恢复。这篇教程把目标缩小到一件可验证的小事:把一个已经存在的小型数据库,通过 Python 标准库的 Connection.backup() 写入全新临时目录,再关闭连接、重新打开副本,逐层检查。

本文代码实测于 Python 3.12.14、SQLite 3.53.1;核对资料日期为 2026 年 10 月 20 日。只有 Python 标准库依赖。示例不覆盖已有数据库,不修改源库的日志模式,也不把临时文件直接替换成线上数据库。

Python SQLite 备份别只复制文件:用 backup() 固定快照,再独立打开验证

概念示意:图中复制与检查流程由 AI 生成,不是程序运行截图,也不表示已经具备生产恢复保证。

一、先分清:数据库快照,不是复制几个正在变化的文件

在 WAL 模式下,提交的数据可能仍在 -wal 文件中,尚未进入主数据库文件。单独复制 app.sqlite3 可能遗漏已提交事务;在系统运行时依次复制主文件、-wal 和 -shm,也不能仅凭“文件齐了”就断言它们来自同一状态。SQLite 官方把 WAL 视为数据库持久状态的一部分。本文让 SQLite 自己通过备份 API 读取一致状态,而不是自己拼装活跃文件。参见 SQLite WAL 文件说明。

Connection.backup() 的目标是另一个数据库连接,不是文件路径;pages 控制每批复制的页数,progress 接收状态、剩余页数和总页数。本文固定为每批 64 页,但这不是性能最优值。API 的行为以 Python 官方 backup 文档为准。

这里另外做了一个明确选择:先在只读源连接中 BEGIN,再执行一次真正的读取,固定一个读快照。随后提交的新数据不属于这个快照。因此,副本的含义是“读取建立时看到的状态”,不是“脚本打印成功时世界上最新的一条记录”。这种做法更容易解释与测试,但也延长了读事务的生命周期。参见 SQLite 隔离说明及 Online Backup API。

二、先把成功条件写清楚

  1. 源路径必须已经存在。使用 mode=ro 打开,拼错路径不能悄悄创建空数据库。

  2. 目标由 mkdtemp() 分配一个新目录,不接受一个现成数据库作为输出目标。重跑产生另一份候选副本,旧备份不动。

  3. 备份连接全部关闭后,再以新的只读连接打开副本。不能只查询原连接、缓存或源库。

  4. integrity_check 必须完整返回一行 ok;foreign_key_check 必须没有结果行。

  5. 结构与外键检查通过后,工具写入基本检查记录 verified.json;随后演示程序还会对业务表执行明确的 SELECT,与预期行比较。该标记不包含业务验收结果。

这些条件只为本文的小型、受信任、本地 SQLite 数据库提供一条清楚的验证链。它们不等于跨机器容灾、断电持久性验证、应用启动验证或业务验收。

三、完整备份工具:backup_existing.py

将下面内容保存为 backup_existing.py。程序只备份 main 数据库,不把 ATTACH 的其他数据库、应用配置或附件目录一并打包。输出父目录必须事先存在。Path.as_uri() 负责路径编码,避免文件名里的空格、# 或 ? 被当成 URI 参数;不要手工拼 file: 加原始路径。只读模式说明见 SQLite URI 文档。

"""Back up an existing SQLite database into a newly allocated temp directory."""
from contextlib import closing
from pathlib import Path
import argparse
import json
import sqlite3
import tempfile
import time


def connect_read_only(path):
    # as_uri() also quotes spaces, # and ? in file names correctly.
    uri = Path(path).resolve(strict=True).as_uri() + "?mode=ro"
    return sqlite3.connect(uri, uri=True, isolation_level=None, timeout=1.0)


def check_database(path):
    """Use a NEW read-only connection, not the backup destination handle."""
    with closing(connect_read_only(path)) as db:
        integrity = db.execute("PRAGMA integrity_check").fetchall()
        if integrity != [("ok",)]:
            raise ValueError(f"integrity_check failed: {integrity!r}")
        foreign_keys = db.execute("PRAGMA foreign_key_check").fetchall()
        if foreign_keys:
            raise ValueError(f"foreign_key_check failed: {foreign_keys!r}")
        tables = [row[0] for row in db.execute(
            "SELECT name FROM sqlite_master "
            "WHERE type = 'table' ORDER BY name"
        )]
    return {"integrity_check": "ok", "foreign_key_errors": 0,
            "tables": tables}


def backup_to_new_temp(source, output_parent, *, max_seconds=10.0):
    """Return (new_path, report); never accept an existing destination path."""
    source = Path(source).resolve(strict=True)
    parent = Path(output_parent).resolve(strict=True)
    if not source.is_file():
        raise ValueError("source must be an existing regular file")
    if not parent.is_dir():
        raise ValueError("output_parent must be an existing directory")
    if max_seconds <= 0:
        raise ValueError("max_seconds must be positive")

    # mkdtemp creates a fresh private directory; it does not reuse old backups.
    work = Path(tempfile.mkdtemp(prefix="sqlite-backup-", dir=parent))
    destination = work / "snapshot.sqlite3"
    started = time.monotonic()

    def progress(status, remaining, total):
        # Cooperative guard only, NOT a hard deadline for filesystem/SQLite I/O.
        if time.monotonic() - started > max_seconds:
            raise TimeoutError("backup exceeded its cooperative time budget")

    try:
        with closing(connect_read_only(source)) as src:
            # BEGIN alone is deferred. This read establishes the snapshot.
            src.execute("BEGIN")
            src.execute("SELECT name FROM sqlite_master").fetchall()
            with closing(sqlite3.connect(
                destination, isolation_level=None, timeout=1.0
            )) as dst:
                src.backup(dst, pages=64, progress=progress, sleep=0.05)
                # Change ONLY the fresh destination, never the source mode.
                mode = dst.execute("PRAGMA journal_mode=DELETE").fetchone()[0]
                if mode != "delete":
                    raise RuntimeError(f"unexpected destination mode: {mode}")
            src.rollback()  # End the pinned read transaction.
        # Both copying handles are now closed before independent inspection.
        report = check_database(destination)
        (work / "verified.json").write_text(
            json.dumps(report, ensure_ascii=False, indent=2) + "\n",
            encoding="utf-8",
        )
        return destination, report
    except Exception as exc:
        # Retain the new directory for diagnosis. Never delete older backups.
        raise RuntimeError(
            f"backup failed; do not use the candidate in {work}; {exc}"
        ) from exc


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("output_parent", type=Path)
    args = parser.parse_args()
    destination, report = backup_to_new_temp(args.source, args.output_parent)
    print(f"backup: {destination}")
    print(json.dumps(report, ensure_ascii=False, indent=2))
    print("Checks passed; application restore testing is still required.")


if __name__ == "__main__":
    main()

用自己已有的小型数据库时,在终端运行:python backup_existing.py "./data/app.sqlite3" "./backup-staging"。请把两个路径换成实际存在的源文件与目录。工具会打印新目录中的 snapshot.sqlite3 路径,不会自动清理这份结果,也不会发布或替换线上文件。

代码里有三个不显眼但重要的细节。第一,BEGIN 本身是延迟事务,后面的 SELECT 才把读状态固定下来。第二,contextlib.closing() 明确关闭连接;不要把连接的事务上下文管理器误认为自动关闭文件。第三,journal_mode=DELETE 只设置刚创建的目标,让这个示例的结果以独立主文件形式验证;它没有对源库执行切换模式或手工清理 WAL。

max_seconds 是在备份进度回调里检查的协作式预算,不是进程级硬超时。它无法强行中断某个阻塞的文件系统调用,也没有给之后的完整性检查设定时间上限。timeout=1.0 则是连接层的锁等待设置,不能理解成整个备份最多一秒。

四、用一个已存在的 WAL 小库做演示

不要拿生产数据测试。把下面内容保存为 demo.py,与备份工具放在同一目录。它先在新的临时目录建立演示库并提交两行,然后才调用“备份已有库”的函数。写连接故意保持打开,且关闭自动检查点,确保测试时确实有非空 WAL 文件。演示结束后,TemporaryDirectory 会删除这批专门创建的测试文件;这与上面工具保留输出的行为不同。

"""Self-contained demonstration; all databases are new disposable fixtures."""
from contextlib import closing
from pathlib import Path
import sqlite3
import tempfile

from backup_existing import backup_to_new_temp, connect_read_only


def read_tasks(path):
    with closing(connect_read_only(path)) as db:
        return db.execute(
            "SELECT id, title, done FROM tasks ORDER BY id"
        ).fetchall()


def main():
    with tempfile.TemporaryDirectory(prefix="sqlite-demo-") as temp:
        root = Path(temp)
        source = root / "existing.sqlite3"
        # Preparation ends before the backup function is called.
        with closing(sqlite3.connect(source, isolation_level=None)) as writer:
            writer.execute("PRAGMA journal_mode=WAL")
            writer.execute("PRAGMA wal_autocheckpoint=0")
            writer.execute(
                "CREATE TABLE tasks (id INTEGER PRIMARY KEY, "
                "title TEXT NOT NULL, done INTEGER NOT NULL "
                "CHECK (done IN (0, 1)))"
            )
            writer.executemany(
                "INSERT INTO tasks VALUES (?, ?, ?)",
                [(1, "整理发票", 1), (2, "核对备份", 0)],
            )
            expected = read_tasks(source)
            wal = Path(str(source) + "-wal")
            print("source WAL has bytes:", wal.stat().st_size > 0)
            backup, report = backup_to_new_temp(source, root)
            print("integrity_check:", report["integrity_check"])
            print("foreign_key_errors:", report["foreign_key_errors"])
            print("independent rows:", read_tasks(backup))
            assert read_tasks(backup) == expected
            writer.execute("INSERT INTO tasks VALUES (3, '稍后新增', 0)")
            print("source rows after later commit:", len(read_tasks(source)))
            print("backup rows after later commit:", len(read_tasks(backup)))
            assert len(read_tasks(backup)) == 2
            print("PASS: verified copy is independent; demo temp files will be removed")


if __name__ == "__main__":
    main()

运行命令:python demo.py。下面是本次实际执行的输出,不是手写的预期结果:

Python 3.12.14
SQLite 3.53.1
source WAL has bytes: True
integrity_check: ok
foreign_key_errors: 0
independent rows: [(1, '整理发票', 1), (2, '核对备份', 0)]
source rows after later commit: 3
backup rows after later commit: 2
PASS: verified copy is independent; demo temp files will be removed

最值得看的是最后两组数字:源库后来增加到 3 行,副本依然是 2 行。副本不是一个指向源库的快捷方式,也不会随着源库后续写入自动更新。演示中的行数据检查比只查表名更有意义,但换成自己的业务时,需要写自己的预期与关键查询。

五、八个可重复的测试,而不只测成功路径

把下面内容保存为 test_backup.py,然后执行 python -m unittest -v test_backup。测试不接触外部数据库,所有写入都发生在新建的临时目录里。它覆盖 URI 特殊字符、只读重开、旧副本不被覆盖、源文件缺失、无效文件、外键违规、活跃 WAL、固定快照与预算中止。

from contextlib import closing
from pathlib import Path
import hashlib
import sqlite3
import tempfile
import unittest
from unittest.mock import patch

from backup_existing import backup_to_new_temp, check_database, connect_read_only


class BackupTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory(prefix="sqlite-test-")
        self.root = Path(self.tmp.name)
        self.source = self.root / "existing #1?.sqlite3"
        with closing(sqlite3.connect(self.source)) as db:
            db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, value TEXT)")
            db.executemany("INSERT INTO items VALUES (?, ?)",
                           [(1, "one"), (2, "two")])
            db.commit()

    def tearDown(self):
        self.tmp.cleanup()

    def rows(self, path):
        with closing(connect_read_only(path)) as db:
            return db.execute("SELECT * FROM items ORDER BY id").fetchall()

    def test_round_trip_and_uri_filename(self):
        backup, report = backup_to_new_temp(self.source, self.root)
        self.assertEqual(self.rows(backup), [(1, "one"), (2, "two")])
        self.assertEqual(report["integrity_check"], "ok")
        self.assertTrue((backup.parent / "verified.json").exists())
        with closing(connect_read_only(backup)) as db:
            with self.assertRaises(sqlite3.OperationalError):
                db.execute("DELETE FROM items")

    def test_new_destination_preserves_previous_backup(self):
        first, _ = backup_to_new_temp(self.source, self.root)
        digest = hashlib.sha256(first.read_bytes()).hexdigest()
        with closing(sqlite3.connect(self.source)) as db:
            db.execute("INSERT INTO items VALUES (3, 'three')")
            db.commit()
        second, _ = backup_to_new_temp(self.source, self.root)
        self.assertNotEqual(first.parent, second.parent)
        self.assertEqual(hashlib.sha256(first.read_bytes()).hexdigest(), digest)
        self.assertEqual(len(self.rows(first)), 2)
        self.assertEqual(len(self.rows(second)), 3)

    def test_missing_source_is_not_created(self):
        missing = self.root / "does-not-exist.sqlite3"
        with self.assertRaises(FileNotFoundError):
            backup_to_new_temp(missing, self.root)
        self.assertFalse(missing.exists())
        self.assertEqual(list(self.root.glob("sqlite-backup-*")), [])

    def test_invalid_database_is_rejected(self):
        invalid = self.root / "invalid.sqlite3"
        invalid.write_text("not a database", encoding="utf-8")
        with self.assertRaisesRegex(RuntimeError, "backup failed"):
            backup_to_new_temp(invalid, self.root)
        self.assertEqual(list(self.root.glob("sqlite-backup-*/verified.json")), [])

    def test_foreign_key_failure_is_not_integrity_success(self):
        with closing(sqlite3.connect(self.source)) as db:
            db.execute("CREATE TABLE parent (id INTEGER PRIMARY KEY)")
            db.execute("CREATE TABLE child (pid REFERENCES parent(id))")
            db.execute("INSERT INTO child VALUES (999)")
            db.commit()
            self.assertEqual(db.execute("PRAGMA integrity_check").fetchall(),
                             [("ok",)])
        with self.assertRaisesRegex(RuntimeError, "foreign_key_check failed"):
            backup_to_new_temp(self.source, self.root)
        self.assertEqual(list(self.root.glob("sqlite-backup-*/verified.json")), [])

    def test_live_wal_commit_is_included(self):
        with closing(sqlite3.connect(self.source, isolation_level=None)) as writer:
            writer.execute("PRAGMA journal_mode=WAL")
            writer.execute("PRAGMA wal_autocheckpoint=0")
            writer.execute("INSERT INTO items VALUES (3, 'committed in WAL')")
            self.assertGreater(Path(str(self.source) + "-wal").stat().st_size, 0)
            backup, _ = backup_to_new_temp(self.source, self.root)
            self.assertEqual(self.rows(backup)[-1], (3, "committed in WAL"))

    def test_snapshot_excludes_later_concurrent_commit(self):
        with closing(sqlite3.connect(self.source, isolation_level=None)) as writer:
            writer.execute("PRAGMA journal_mode=WAL")
            original_connect = sqlite3.connect

            class SourceConnection(sqlite3.Connection):
                def backup(self, target, **kwargs):
                    # The function has already begun and read its source snapshot.
                    writer.execute("INSERT INTO items VALUES (3, 'later commit')")
                    return super().backup(target, **kwargs)

            def connect(*args, **kwargs):
                if kwargs.get("uri") and str(args[0]).startswith(self.source.as_uri()):
                    kwargs["factory"] = SourceConnection
                return original_connect(*args, **kwargs)

            with patch("backup_existing.sqlite3.connect", side_effect=connect):
                backup, _ = backup_to_new_temp(self.source, self.root)
            self.assertEqual(len(self.rows(self.source)), 3)
            self.assertEqual(len(self.rows(backup)), 2)

    def test_cooperative_budget_failure_has_no_verified_marker(self):
        with patch("backup_existing.time.monotonic", side_effect=[0.0, 20.0]):
            with self.assertRaisesRegex(RuntimeError, "cooperative time budget"):
                backup_to_new_temp(self.source, self.root, max_seconds=1)
        self.assertEqual(list(self.root.glob("sqlite-backup-*/verified.json")), [])


if __name__ == "__main__":
    unittest.main(verbosity=2)

固定快照那一项使用第二个写连接,在源读快照建立之后、真正复制之前提交新行。这是一个可控的交错操作测试,不是多进程压力测试。预算测试通过替换单调时钟模拟超时,不是真的等十秒,也不是在证明硬超时。

本次测试原始输出如下。耗时只代表这台运行环境与这组微型数据,不是吞吐量结论:

test_cooperative_budget_failure_has_no_verified_marker (test_backup.BackupTests.test_cooperative_budget_failure_has_no_verified_marker) ... ok
test_foreign_key_failure_is_not_integrity_success (test_backup.BackupTests.test_foreign_key_failure_is_not_integrity_success) ... ok
test_invalid_database_is_rejected (test_backup.BackupTests.test_invalid_database_is_rejected) ... ok
test_live_wal_commit_is_included (test_backup.BackupTests.test_live_wal_commit_is_included) ... ok
test_missing_source_is_not_created (test_backup.BackupTests.test_missing_source_is_not_created) ... ok
test_new_destination_preserves_previous_backup (test_backup.BackupTests.test_new_destination_preserves_previous_backup) ... ok
test_round_trip_and_uri_filename (test_backup.BackupTests.test_round_trip_and_uri_filename) ... ok
test_snapshot_excludes_later_concurrent_commit (test_backup.BackupTests.test_snapshot_excludes_later_concurrent_commit) ... ok

----------------------------------------------------------------------
Ran 8 tests in 0.021s

OK

六、为什么 integrity_check 返回 ok,仍可能不能接受这份备份

integrity_check 检查数据库底层结构及若干一致性问题,但不检查外键。因此,本文单独执行 foreign_key_check。这一边界来自 SQLite PRAGMA 官方说明,不是额外的“保险选项”。

下面的输出来自实际失败用例:缺失源没有被创建;普通文本文件被拒绝;孤儿外键的库虽然能得到 integrity_check 的 ok,仍未通过我们的验收。失败候选目录保留用于排查,不能因 snapshot.sqlite3 文件存在就当成成功。

missing source: FileNotFoundError
missing source created: False
invalid source: DatabaseError file is not a database
orphan integrity_check: [('ok',)]
orphan backup: ValueError foreign_key_check failed: [('child', 1, 'parent', 0)]
verified markers after failures: 0

verified.json 只是本次基本检查完成的记录,不是签名、校验和或原子发布协议。机器可能在写检查记录时断电,文件也可能在检查以后被改动。更不能把它理解为业务“可恢复”的证明。

七、适用边界:哪些问题还没有解决

  • 持续写入与锁。固定读快照会占用读事务。WAL 下可能影响检查点推进、使 WAL 增长;回滚日志模式下可能延迟写者提交。本例适合小库与短事务,不承诺零阻塞。大库应评估事务时长、磁盘空间及应用负载。备份 API 的更多并发边界见 SQLite 官方备份说明。

  • 读权限不是“源目录绝无变化”。mode=ro 限制这个连接写数据库内容,但 WAL 的共享内存及伴随文件管理仍受 SQLite 与目录权限约束。不能因此把线上活跃库错误标为 immutable,也不要删源库的 -wal 或 -shm。

  • 磁盘满、权限错误与进程退出。异常会停止返回成功;已经新建的候选目录保留。不要把失败文件放入可恢复备份清单。本文没有注入真实磁盘满、断电、网络文件系统故障或操作系统强制退出。

  • 业务完整性。结构正常的数据库仍可能缺了重要订单、存了错误状态或与外部附件不同步。需要关键查询、业务约束与应用级恢复演练;通用脚本不知道你的“正确数据”是什么。

  • 特殊数据库。依赖扩展、自定义排序规则或特殊虚拟表的数据库,重新打开与检查时可能还需要相同运行依赖。本文没有覆盖这些情况,也不是修复损坏数据库的工具。

  • 备份保留与安全。临时目录可以被清理,和源库位于同一磁盘也不能防整盘丢失。正式方案还应决定保留期限、异地副本、访问控制、加密、版本兼容与定期恢复演练,不能直接拿临时路径作为长期策略。

八、把“复制完成”改成“有证据地验收”

这一版工具刻意没有加入轮换删除、压缩上传或覆盖恢复。先做好一条可以独立审查的短链路:存在的只读源、明确的快照、新建目标、关闭连接、独立打开、结构检查、外键检查、业务查询。每一步都能回答“我验证了什么”,也能说明“我还没有验证什么”。这比输出一句 backup success 更值得信任。

官方资料

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。