File size: 2,381 Bytes
f8975ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
"""sqlite-stage: a consistent copy of live SQLite databases, for the backup to take.

  sqlite-stage.py DEST_DIR DATABASE [DATABASE ...]

A backup that copies a database file while a service writes to it can catch the file and its write-ahead log
at different moments, and the copy may not open. SQLite's own backup API reads a consistent snapshot while
the writer keeps writing. Each database lands in DEST_DIR under its path with slashes as underscores, written
to a temporary name, checked (`quick_check`), synced and renamed: a half copy never has the final name.
A missing database is skipped; a failed one is reported and makes the exit status 1, and the others still run.
"""
from __future__ import annotations

import os
import sqlite3
import sys
from pathlib import Path


def stage(source: Path, dest_dir: Path) -> str:
    name = str(source).replace(str(Path.home()), "").strip("/").replace("/", "_")
    final = dest_dir / name
    tmp = dest_dir / (name + ".tmp")
    tmp.unlink(missing_ok=True)
    try:
        src = sqlite3.connect(f"file:{source}?mode=ro", uri=True, timeout=30)
        dst = sqlite3.connect(tmp)
        try:
            src.backup(dst)
            ok = dst.execute("PRAGMA quick_check").fetchone()[0]
        finally:
            dst.close()
            src.close()
        if ok != "ok":
            raise sqlite3.DatabaseError(f"the copy does not pass quick_check: {ok}")
    except sqlite3.Error:
        tmp.unlink(missing_ok=True)      # a half copy never stays, under any name
        raise
    with open(tmp, "rb") as fh:
        os.fsync(fh.fileno())
    os.replace(tmp, final)
    return f"{source} -> {final} ({final.stat().st_size} bytes)"


def main(argv: list[str]) -> int:
    if len(argv) < 2:
        print(__doc__.strip().splitlines()[2].strip(), file=sys.stderr)
        return 2
    dest = Path(argv[0])
    dest.mkdir(parents=True, exist_ok=True)
    failed = 0
    for arg in argv[1:]:
        source = Path(arg)
        if not source.exists():
            continue
        try:
            print(stage(source, dest))
        except sqlite3.Error as e:
            failed = 1
            print(f"sqlite-stage: {source}: {e}", file=sys.stderr)
    fd = os.open(dest, os.O_RDONLY)
    os.fsync(fd)
    os.close(fd)
    return failed


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))