Live
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create a consistent SQLite backup without replacing an existing destination."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def snapshot(source, destination, timeout=120):
|
||||
source = Path(source).resolve(strict=True)
|
||||
destination = Path(destination).absolute()
|
||||
if not source.is_file():
|
||||
raise ValueError("Source must be a database file")
|
||||
if destination.exists():
|
||||
raise FileExistsError("Destination already exists; use a new backup filename")
|
||||
# mkstemp creates mode 0600 on Ubuntu. Place alongside destination so publishing
|
||||
# can use an atomic, exclusive hard link, including against concurrent runs.
|
||||
fd, temporary = tempfile.mkstemp(prefix=".snapshot-", dir=destination.parent)
|
||||
os.close(fd)
|
||||
deadline = time.monotonic() + timeout
|
||||
|
||||
def progress(status, remaining, total):
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError("SQLite backup timed out")
|
||||
|
||||
try:
|
||||
src = sqlite3.connect(source.as_uri() + "?mode=ro", uri=True, timeout=5)
|
||||
try:
|
||||
dst = sqlite3.connect(temporary)
|
||||
try:
|
||||
src.backup(dst, pages=256, progress=progress, sleep=0.1)
|
||||
if dst.execute("PRAGMA quick_check").fetchall() != [("ok",)]:
|
||||
raise ValueError("Snapshot failed SQLite integrity check")
|
||||
# A standalone snapshot must not depend on a WAL sidecar.
|
||||
dst.execute("PRAGMA journal_mode=DELETE")
|
||||
finally:
|
||||
dst.close()
|
||||
finally:
|
||||
src.close()
|
||||
with open(temporary, "rb+") as backup:
|
||||
os.fsync(backup.fileno())
|
||||
os.link(temporary, destination)
|
||||
finally:
|
||||
Path(temporary).unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("source")
|
||||
parser.add_argument("destination", help="New filename in an existing directory")
|
||||
args = parser.parse_args()
|
||||
snapshot(args.source, args.destination)
|
||||
print("SQLite snapshot created successfully")
|
||||
Reference in New Issue
Block a user