180 lines
6.3 KiB
Python
180 lines
6.3 KiB
Python
"""Full wipe of all project-dependent data, keeping schema and migrations."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import shutil
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import document_storage_root
|
|
from app.models.agreement import Agreement, AgreementItem
|
|
from app.models.boq import BoqDocument, Section, System, WorkItem
|
|
from app.models.daily_report import DailyReport, DailyReportItem
|
|
from app.models.daily_report_photo import DailyReportPhoto
|
|
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
|
from app.models.ks3 import KS3, KS3KS2
|
|
from app.models.payment import Payment, PaymentAllocation
|
|
from app.models.project import Project
|
|
from app.models.work_journal import WorkJournalEntry
|
|
from app.models.document_artifact import DocumentArtifact
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class DatabaseResetError(RuntimeError):
|
|
"""Reset failed and was rolled back."""
|
|
|
|
|
|
# Order matters: dependents first. BoqDocument ↔ Agreement is circular
|
|
# (boq_documents.agreement_id and agreements.boq_document_id), so
|
|
# boq_documents.agreement_id is cleared before deleting Agreements.
|
|
DELETE_ORDER = (
|
|
("payment_allocations", PaymentAllocation),
|
|
("payments", Payment),
|
|
("ks3_ks2_links", KS3KS2),
|
|
("ks3_documents", KS3),
|
|
("ks2_item_sources", KS2ItemSource),
|
|
("ks2_items", KS2Item),
|
|
("ks2_documents", KS2),
|
|
("daily_report_photos", DailyReportPhoto),
|
|
("daily_report_items", DailyReportItem),
|
|
("daily_reports", DailyReport),
|
|
("agreement_items", AgreementItem),
|
|
("agreements", Agreement),
|
|
("work_items", WorkItem),
|
|
("sections", Section),
|
|
("systems", System),
|
|
("boq_documents", BoqDocument),
|
|
("work_journal_entries", WorkJournalEntry),
|
|
("document_artifacts", DocumentArtifact),
|
|
("projects", Project),
|
|
)
|
|
|
|
PROJECT_DEPENDENT_TABLES = tuple(name for name, _ in DELETE_ORDER)
|
|
|
|
|
|
def project_storage_path(project_id: int) -> Path:
|
|
"""
|
|
Return the storage directory for a project. Server-side construction only.
|
|
|
|
The result is always strictly inside document_storage_root()/projects/.
|
|
Does NOT create the directory.
|
|
"""
|
|
pid = int(project_id)
|
|
if pid <= 0:
|
|
raise ValueError("project_id must be a positive integer")
|
|
root = document_storage_root()
|
|
projects_root = (root / "projects").resolve()
|
|
candidate = (projects_root / str(pid)).resolve()
|
|
# Safety: must be a direct child of projects_root
|
|
if candidate.parent != projects_root:
|
|
raise ValueError("project storage path escapes projects root")
|
|
return candidate
|
|
|
|
|
|
@dataclass
|
|
class ResetResult:
|
|
deleted: dict[str, int]
|
|
verified: dict[str, int]
|
|
storage_removed: bool = False
|
|
storage_error: str | None = None
|
|
|
|
|
|
def count_project_data(db: Session) -> dict[str, int]:
|
|
"""Row counts for every project-dependent table."""
|
|
counts: dict[str, int] = {}
|
|
for name, model in DELETE_ORDER:
|
|
counts[name] = int(db.execute(select(func.count()).select_from(model)).scalar() or 0)
|
|
return counts
|
|
|
|
|
|
def _delete_project_storage(project_ids: list[int]) -> tuple[bool, str | None]:
|
|
"""
|
|
Remove physical storage for the given project IDs.
|
|
|
|
Only called AFTER a successful DB commit. Never rolls back DB.
|
|
Returns (all_removed, error_message_or_None).
|
|
"""
|
|
errors = []
|
|
for pid in project_ids:
|
|
try:
|
|
storage_dir = project_storage_path(pid)
|
|
except ValueError as exc:
|
|
errors.append(f"project {pid}: {exc}")
|
|
continue
|
|
if not storage_dir.exists():
|
|
continue # missing storage is not an error
|
|
try:
|
|
# Guard: resolved path must still be inside projects root
|
|
projects_root = (document_storage_root() / "projects").resolve()
|
|
if storage_dir.parent != projects_root:
|
|
errors.append(f"project {pid}: storage path escapes projects root")
|
|
continue
|
|
# Refuse to follow symlinks out of the tree
|
|
if storage_dir.is_symlink():
|
|
errors.append(f"project {pid}: storage directory is a symlink, refused to delete")
|
|
continue
|
|
shutil.rmtree(storage_dir)
|
|
except OSError as exc:
|
|
logger.warning(
|
|
"FS cleanup failed for project %s: %s: %s",
|
|
pid, type(exc).__name__, exc,
|
|
)
|
|
errors.append(f"project {pid}: {type(exc).__name__}: {exc}")
|
|
return (not errors, "; ".join(errors) if errors else None)
|
|
|
|
|
|
def reset_database(db: Session) -> ResetResult:
|
|
"""
|
|
Delete all project-dependent rows in one transaction, then clean FS.
|
|
|
|
Schema, indexes and schema_migrations are left untouched. On any DB error
|
|
the transaction is rolled back and physical storage is NOT touched.
|
|
FS deletion happens only after a successful DB commit.
|
|
"""
|
|
project_ids: list[int] = []
|
|
try:
|
|
# Collect project IDs before deletion
|
|
project_ids = [row[0] for row in db.execute(select(Project.id)).all()]
|
|
|
|
deleted: dict[str, int] = {}
|
|
# Break the circular BoqDocument ↔ Agreement FK before deleting either side.
|
|
db.execute(
|
|
BoqDocument.__table__.update().values(agreement_id=None)
|
|
)
|
|
for name, model in DELETE_ORDER:
|
|
result = db.execute(
|
|
model.__table__.delete()
|
|
)
|
|
deleted[name] = int(result.rowcount or 0)
|
|
|
|
db.flush()
|
|
|
|
verified = count_project_data(db)
|
|
leftovers = {k: v for k, v in verified.items() if v != 0}
|
|
if leftovers:
|
|
raise DatabaseResetError(
|
|
"Контроль очистки обнаружил остаточные данные: "
|
|
+ ", ".join(f"{k}={v}" for k, v in leftovers.items())
|
|
)
|
|
|
|
db.commit()
|
|
except DatabaseResetError:
|
|
db.rollback()
|
|
raise
|
|
except Exception as exc:
|
|
db.rollback()
|
|
raise DatabaseResetError(f"Сброс прерван, изменения отменены: {exc}") from exc
|
|
|
|
# DB commit succeeded — now clean physical storage.
|
|
storage_removed, storage_error = _delete_project_storage(project_ids)
|
|
return ResetResult(
|
|
deleted=deleted,
|
|
verified=verified,
|
|
storage_removed=storage_removed,
|
|
storage_error=storage_error,
|
|
)
|