fix: sicherung schließt verbindungen und hinterlässt keine hilfsdateien

sqlite3-Verbindungen werden ausdrücklich geschlossen (der Kontextmanager
beendet nur die Transaktion). Die Kopie wird vor dem Komprimieren aus dem
geerbten WAL-Modus in eine einzelne Datei überführt; -wal/-shm-Reste
werden immer entfernt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 15:36:39 +01:00
1 parent 50cf1a8492
commit 96db5607ea
2 files changed
+24 -7

No files matched your search

+16 -4
View File
@@ -12,6 +12,7 @@ import os
import re
import shutil
import sqlite3
from contextlib import closing
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from pathlib import Path
@@ -76,12 +77,18 @@ def latest_backup() -> BackupInfo | None:
def _verify(path: Path) -> None:
with sqlite3.connect(path) as conn:
# closing(): sqlite3's own context manager only ends the transaction
with closing(sqlite3.connect(path)) as conn:
result = conn.execute("PRAGMA integrity_check").fetchone()[0]
if result != "ok":
raise BackupError(f"Integritätsprüfung fehlgeschlagen: {result}")
def _remove_snapshot(snapshot: Path) -> None:
for suffix in ("", "-wal", "-shm", "-journal"):
Path(f"{snapshot}{suffix}").unlink(missing_ok=True)
def create_backup(now: datetime | None = None) -> BackupInfo:
"""Snapshot, verify and compress the database; a second run on the same day replaces
that day's backup. Only a verified, complete file ever gets the final name."""
@@ -94,10 +101,15 @@ def create_backup(now: datetime | None = None) -> BackupInfo:
compressed = directory / f".app-{day}.db.gz.tmp"
final = directory / f"app-{day}.db.gz"
try:
snapshot.unlink(missing_ok=True)
_remove_snapshot(snapshot)
# sqlite3 backup API: consistent copy while the app keeps writing
with sqlite3.connect(_database_path()) as source, sqlite3.connect(snapshot) as target:
with (
closing(sqlite3.connect(_database_path())) as source,
closing(sqlite3.connect(snapshot)) as target,
):
source.backup(target)
# The copy inherits WAL mode; switch back so everything is in one file
target.execute("PRAGMA journal_mode=DELETE")
_verify(snapshot)
with snapshot.open("rb") as raw, gzip.open(compressed, "wb", compresslevel=6) as out:
shutil.copyfileobj(raw, out)
@@ -108,7 +120,7 @@ def create_backup(now: datetime | None = None) -> BackupInfo:
logger.exception("Backup failed")
raise BackupError(str(exc)) from exc
finally:
snapshot.unlink(missing_ok=True)
_remove_snapshot(snapshot)
last_error = None
removed = prune()