Files
Heimdall/scripts/ci/check-efcore-usage.py
T

65 lines
2.8 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Reject direct database commands in production source outside documented EF exceptions."""
from pathlib import Path
import re
import sys
ROOT = Path(__file__).resolve().parents[2]
SOURCE_ROOT = ROOT / "src"
# These operations cannot be expressed portably through EF's LINQ/change tracker.
# Keep the exception narrow by path and explain it in the file next to the operation.
EF_CORE_EXCEPTIONS = {
"src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs": "PostgreSQL VACUUM/REINDEX and catalog inspection",
"src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs": "PostgreSQL partition DDL and catalog inspection",
"src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs": "transaction-scoped PostgreSQL advisory lock",
"src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs": "transaction-scoped PostgreSQL advisory lock for serialized recording quota checks",
"src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs": "idempotent PostgreSQL bulk insert with ON CONFLICT DO NOTHING",
"src/Heimdall.Agent/Data/AgentOutboxDatabaseInitializer.cs": "baseline and migrate pre-EF local SQLite outbox schemas",
}
DATABASE_API = re.compile(
r"\b(?:Sqlite|Npgsql|Sql|MySql|Db)(?:Connection|Command|DataReader)\b"
r"|\.CreateCommand\s*\(|\.GetDbConnection\s*\(|\.CommandText\s*=|"
r"\.Execute(?:Reader|NonQuery|Scalar)(?:Async)?\s*\(|\b(?:ExecuteSqlRaw|ExecuteSqlInterpolated|"
r"SqlQueryRaw|SqlQuery|FromSqlRaw|FromSqlInterpolated|FromSql)\s*(?:Async)?\s*\(",
)
def inspect_source(path: str, content: str) -> list[str]:
"""Return policy violations for one repository-relative C# source file."""
if not path.startswith("src/") or "/Migrations/" in path or path.endswith(".Designer.cs"):
return []
if not DATABASE_API.search(content):
return []
rationale = EF_CORE_EXCEPTIONS.get(path)
if rationale and "EF Core exception:" in content:
return []
return [f"{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception"]
def check_tree(root: Path = ROOT) -> list[str]:
failures = []
for path in sorted((root / "src").rglob("*.cs")):
relative = path.relative_to(root).as_posix()
try:
content = path.read_text(encoding="utf-8-sig")
except UnicodeDecodeError:
failures.append(f"{relative}: source is not valid UTF-8")
continue
failures.extend(inspect_source(relative, content))
return failures
def main() -> int:
failures = check_tree()
if failures:
print("EF Core persistence policy violations:", file=sys.stderr)
print("\n".join(f"- {failure}" for failure in failures), file=sys.stderr)
return 1
print("EF Core persistence policy passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())