"""只在自动创建的临时目录演练合成 SQLite 备份，不接收真实库路径。"""
import sqlite3
import tempfile
from contextlib import closing
from pathlib import Path

with tempfile.TemporaryDirectory(prefix="gateway-restore-demo-") as folder:
    root = Path(folder)
    with closing(sqlite3.connect(root / "source.db")) as source:
        source.execute("CREATE TABLE demo_channels(id INTEGER PRIMARY KEY, units INTEGER)")
        source.executemany("INSERT INTO demo_channels VALUES (?, ?)", [(1, 10), (2, 20)])
        source.commit()
        with closing(sqlite3.connect(root / "backup.db")) as target:
            source.backup(target)
    uri = (root / "backup.db").as_uri() + "?mode=ro"
    with closing(sqlite3.connect(uri, uri=True)) as restored:
        restored.execute("PRAGMA query_only=ON")
        integrity = restored.execute("PRAGMA integrity_check").fetchone()[0]
        count, total = restored.execute("SELECT count(*),sum(units) FROM demo_channels").fetchone()
        assert (integrity, count, total) == ("ok", 2, 30)
        print(f"integrity={integrity}; rows={count}; total={total}")
