From 96db5607eae2f939115ad142a72c973de1956bbd Mon Sep 17 00:00:00 2001 From: dbildhauer Date: Sun, 25 Oct 2026 15:36:39 +0100 Subject: [PATCH] =?UTF-8?q?fix:=20sicherung=20schlie=C3=9Ft=20verbindungen?= =?UTF-8?q?=20und=20hinterl=C3=A4sst=20keine=20hilfsdateien?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- backend/app/services/backup.py | 20 ++++++++++++++++---- backend/tests/test_backup.py | 11 ++++++++--- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/backend/app/services/backup.py b/backend/app/services/backup.py index b81df50..e3db0a7 100644 --- a/backend/app/services/backup.py +++ b/backend/app/services/backup.py @@ -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() diff --git a/backend/tests/test_backup.py b/backend/tests/test_backup.py index 899c344..a30c909 100644 --- a/backend/tests/test_backup.py +++ b/backend/tests/test_backup.py @@ -1,6 +1,7 @@ import gzip import os import sqlite3 +from contextlib import closing from datetime import date, datetime, timedelta import pytest @@ -46,7 +47,11 @@ def test_backup_can_be_restored(app_env, make_user, tmp_path): assert info.path.name == "app-2026-10-25.db.gz" assert info.size > 0 - with restore(info, tmp_path) as conn: + # Nothing but the backup itself: no snapshot, -wal, -shm or temp files left over + assert [p.name for p in backup.backup_dir().iterdir()] == [info.path.name] + with closing(restore(info, tmp_path)) as conn: + # A single self-contained file, not a WAL database that needs its -wal file + assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "delete" assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok" assert conn.execute("SELECT username FROM users").fetchall() == [("anna",)] assert conn.execute("SELECT version_num FROM alembic_version").fetchone() is not None @@ -57,7 +62,7 @@ def test_backup_is_a_snapshot(app_env, make_user, tmp_path): info = backup.create_backup(at("2026-10-25")) make_user("bert") - with restore(info, tmp_path) as conn: + with closing(restore(info, tmp_path)) as conn: assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1 @@ -67,7 +72,7 @@ def test_second_backup_of_a_day_replaces_the_first(app_env, make_user, tmp_path) info = backup.create_backup(at("2026-10-25", 14)) assert [b.path.name for b in backup.list_backups()] == ["app-2026-10-25.db.gz"] - with restore(info, tmp_path) as conn: + with closing(restore(info, tmp_path)) as conn: assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1