"""Row-level validation. Each row is validated on its own, collecting all of its errors, and sorted into accepted or rejected; a bad row does not abort the batch.""" from dataclasses import dataclass, field from typing import Any, Iterable, Type from pydantic import BaseModel from pydantic import ValidationError as PydanticValidationError from webapi.imports.schemas.classify import ValidationError, classify_error @dataclass class RowErrors: row_index: int errors: list[ValidationError] = field(default_factory=list) @dataclass(frozen=True) class AcceptedRow: row_index: int data: dict[str, Any] @dataclass class BatchValidationResult: total_rows: int = 0 accepted_rows: list[AcceptedRow] = field(default_factory=list) rejected: list[RowErrors] = field(default_factory=list) @property def accepted(self) -> list[dict[str, Any]]: return [row.data for row in self.accepted_rows] @property def valid_count(self) -> int: return len(self.accepted) @property def error_count(self) -> int: return len(self.rejected) def validate_rows(schema_cls: Type[BaseModel], rows: Iterable[dict[str, Any] | None]) -> BatchValidationResult: """`None` rows count towards the total but are not validated: they were merged into a row of another source.""" result = BatchValidationResult() for index, row in enumerate(rows): result.total_rows += 1 if row is None: continue try: validated = schema_cls(**row) except PydanticValidationError as exc: result.rejected.append( RowErrors(row_index=index, errors=[classify_error(e) for e in exc.errors()]) ) else: # exclude_unset keeps only the fields this source supplied, so an # upsert does not overwrite columns the source never mapped. result.accepted_rows.append(AcceptedRow(row_index=index, data=validated.model_dump(exclude_unset=True))) return result