feat: export calendar and backup db

This commit is contained in:
jfmcarreira committed 2026-10-06 15:44:25 +01:00
1 parent 306e21fe44
commit f4985b7fbc
28 files changed
+712 -46

No files matched your search

+45
View File
@@ -1,7 +1,11 @@
from __future__ import annotations
import shutil
import sqlite3
from collections.abc import Generator
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
from alembic import command
from alembic.config import Config
@@ -60,3 +64,44 @@ def get_db() -> Generator[Session, None, None]:
yield db
finally:
db.close()
def database_file(url: str | None = None) -> Path | None:
"""The SQLite file behind DATABASE_URL, or None for another engine."""
raw = url or settings.database_url
if not raw.startswith("sqlite"):
return None
path = urlparse(raw).path
if not path:
return None
# sqlite:///./data/x.db is relative, sqlite:////srv/x.db is absolute.
if path.startswith("/"):
path = path[1:]
if not path or path.startswith(":memory:"):
return None
return Path(path)
def backup_database(destination_dir: str | None = None) -> Path | None:
"""Copy the database aside on every start, never overwriting an older copy.
Uses SQLite's own backup API so the copy is consistent even if another
process is writing. Returns the new file, or None when there is nothing to copy.
"""
source = database_file()
if source is None or not source.is_file():
return None
folder = Path(destination_dir or settings.backup_dir or source.parent / "backups")
folder.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
target = folder / f"{source.stem}-{stamp}{source.suffix}"
index = 1
while target.exists(): # two starts in the same second
target = folder / f"{source.stem}-{stamp}-{index}{source.suffix}"
index += 1
with sqlite3.connect(source) as origin, sqlite3.connect(target) as copy:
origin.backup(copy)
shutil.copystat(source, target)
return target