backup.py•1.31 kB
"""Backup SQLite database."""
import shutil
import os
from datetime import datetime
from pathlib import Path
def backup_sqlite():
"""Create a timestamped backup of the SQLite database."""
sqlite_path = os.getenv("SQLITE_PATH", "/app/data/documents.db")
backup_dir = Path(sqlite_path).parent / "backups"
# Ensure backup directory exists
backup_dir.mkdir(parents=True, exist_ok=True)
# Create backup with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = backup_dir / f"documents_{timestamp}.db"
if not Path(sqlite_path).exists():
print(f"Error: Database not found at {sqlite_path}")
return
shutil.copy2(sqlite_path, backup_path)
print(f"Backup created: {backup_path}")
# Optional: Clean up old backups (keep last 7 days)
cleanup_old_backups(backup_dir, days=7)
def cleanup_old_backups(backup_dir: Path, days: int = 7):
"""Remove backups older than specified days."""
import time
cutoff_time = time.time() - (days * 86400) # days to seconds
for backup_file in backup_dir.glob("documents_*.db"):
if backup_file.stat().st_mtime < cutoff_time:
backup_file.unlink()
print(f"Removed old backup: {backup_file}")
if __name__ == "__main__":
backup_sqlite()