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:
1 parent
50cf1a8492
commit
96db5607ea
2 files changed
+24
-7
No files matched your search
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user