feat: add atomic database reset that wipes project data while keeping schema
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
"""Full wipe of all project-dependent data, keeping schema and migrations."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
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.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
|
||||
|
||||
|
||||
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_items", DailyReportItem),
|
||||
("daily_reports", DailyReport),
|
||||
("agreement_items", AgreementItem),
|
||||
("agreements", Agreement),
|
||||
("work_items", WorkItem),
|
||||
("sections", Section),
|
||||
("systems", System),
|
||||
("boq_documents", BoqDocument),
|
||||
("work_journal_entries", WorkJournalEntry),
|
||||
("projects", Project),
|
||||
)
|
||||
|
||||
PROJECT_DEPENDENT_TABLES = tuple(name for name, _ in DELETE_ORDER)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResetResult:
|
||||
deleted: dict[str, int]
|
||||
verified: dict[str, int]
|
||||
|
||||
|
||||
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 reset_database(db: Session) -> ResetResult:
|
||||
"""
|
||||
Delete all project-dependent rows in one transaction.
|
||||
|
||||
Schema, indexes and schema_migrations are left untouched. On any error the
|
||||
transaction is rolled back and no partial delete remains.
|
||||
"""
|
||||
try:
|
||||
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()
|
||||
return ResetResult(deleted=deleted, verified=verified)
|
||||
except DatabaseResetError:
|
||||
db.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
raise DatabaseResetError(f"Сброс прерван, изменения отменены: {exc}") from exc
|
||||
Reference in New Issue
Block a user