Ignore generated OpenAPI types
This commit is contained in:
2
fastapi_demo/app/infrastructure/db/base.py
Normal file
2
fastapi_demo/app/infrastructure/db/base.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from fastapi_demo.app.infrastructure.db.session import Base # noqa: F401
|
||||
from fastapi_demo.app.infrastructure.db import models # noqa: F401
|
||||
13
fastapi_demo/app/infrastructure/db/deps.py
Normal file
13
fastapi_demo/app/infrastructure/db/deps.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Generator
|
||||
from fastapi_demo.app.infrastructure.db.session import SessionLocal
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
53
fastapi_demo/app/infrastructure/db/models.py
Normal file
53
fastapi_demo/app/infrastructure/db/models.py
Normal file
@@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import String, DateTime, Text, ForeignKey, Integer, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi_demo.app.infrastructure.db.session import Base
|
||||
|
||||
|
||||
class Asset(Base):
|
||||
__tablename__ = "assets"
|
||||
|
||||
id: Mapped[str] = mapped_column(String, primary_key=True, index=True)
|
||||
name: Mapped[str] = mapped_column(String, nullable=False)
|
||||
serial: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
|
||||
status: Mapped[str] = mapped_column(String, nullable=False)
|
||||
|
||||
revision: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
nullable=False,
|
||||
server_default=text("0"),
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False
|
||||
)
|
||||
|
||||
events: Mapped[list["AssetEvent"]] = relationship(
|
||||
"AssetEvent",
|
||||
back_populates="asset",
|
||||
cascade="all, delete-orphan",
|
||||
passive_deletes=True,
|
||||
)
|
||||
|
||||
|
||||
class AssetEvent(Base):
|
||||
__tablename__ = "asset_events"
|
||||
|
||||
id: Mapped[str] = mapped_column(String, primary_key=True, index=True)
|
||||
asset_id: Mapped[str] = mapped_column(
|
||||
String, ForeignKey("assets.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
|
||||
from_status: Mapped[str] = mapped_column(String, nullable=False)
|
||||
to_status: Mapped[str] = mapped_column(String, nullable=False)
|
||||
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
note: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
|
||||
asset: Mapped["Asset"] = relationship("Asset", back_populates="events")
|
||||
24
fastapi_demo/app/infrastructure/db/session.py
Normal file
24
fastapi_demo/app/infrastructure/db/session.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
from fastapi_demo.app.core.config import settings
|
||||
|
||||
# sorgt dafür, dass ./data existiert (für sqlite datei)
|
||||
Path("data").mkdir(exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
connect_args={"check_same_thread": False}
|
||||
if settings.DATABASE_URL.startswith("sqlite")
|
||||
else {},
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def dispose_engine() -> None:
|
||||
engine.dispose()
|
||||
11
fastapi_demo/app/infrastructure/repositories/assets_repo.py
Normal file
11
fastapi_demo/app/infrastructure/repositories/assets_repo.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from typing import Protocol
|
||||
from uuid import UUID
|
||||
from fastapi_demo.app.schemas.asset import AssetOut, AssetEventOut
|
||||
|
||||
|
||||
class AssetsRepo(Protocol):
|
||||
def create(self, asset: AssetOut) -> None: ...
|
||||
def get(self, asset_id: UUID) -> AssetOut | None: ...
|
||||
def update(self, asset: AssetOut) -> None: ...
|
||||
def add_event(self, event: AssetEventOut) -> None: ...
|
||||
def list_events(self, asset_id: UUID) -> list[AssetEventOut]: ...
|
||||
@@ -0,0 +1,25 @@
|
||||
from uuid import UUID
|
||||
from fastapi_demo.app.infrastructure.repositories.assets_repo import AssetsRepo
|
||||
from fastapi_demo.app.schemas.asset import AssetOut, AssetEventOut
|
||||
|
||||
|
||||
class MemoryAssetsRepo(AssetsRepo):
|
||||
def __init__(self) -> None:
|
||||
self.assets: dict[UUID, AssetOut] = {}
|
||||
self.events: dict[UUID, list[AssetEventOut]] = {}
|
||||
|
||||
def create(self, asset: AssetOut) -> None:
|
||||
self.assets[asset.id] = asset
|
||||
self.events.setdefault(asset.id, [])
|
||||
|
||||
def get(self, asset_id: UUID) -> AssetOut | None:
|
||||
return self.assets.get(asset_id)
|
||||
|
||||
def update(self, asset: AssetOut) -> None:
|
||||
self.assets[asset.id] = asset
|
||||
|
||||
def add_event(self, event: AssetEventOut) -> None:
|
||||
self.events.setdefault(event.asset_id, []).append(event)
|
||||
|
||||
def list_events(self, asset_id: UUID) -> list[AssetEventOut]:
|
||||
return list(self.events.get(asset_id, []))
|
||||
137
fastapi_demo/app/infrastructure/repositories/sql_assets_repo.py
Normal file
137
fastapi_demo/app/infrastructure/repositories/sql_assets_repo.py
Normal file
@@ -0,0 +1,137 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from fastapi_demo.app.infrastructure.db.models import (
|
||||
Asset as AssetORM,
|
||||
AssetEvent as AssetEventORM,
|
||||
)
|
||||
from fastapi_demo.app.domain.status import AssetStatus
|
||||
from fastapi_demo.app.schemas.asset import AssetOut, AssetEventOut
|
||||
|
||||
|
||||
class SqlAssetsRepo:
|
||||
def __init__(self, db: Session) -> None:
|
||||
self.db = db
|
||||
|
||||
def create(self, asset: AssetOut) -> None:
|
||||
row = AssetORM(
|
||||
id=str(asset.id),
|
||||
name=asset.name,
|
||||
serial=asset.serial,
|
||||
status=str(asset.status),
|
||||
revision=asset.revision, # <-- wichtig
|
||||
created_at=asset.updated_at, # MVP: created_at == updated_at
|
||||
updated_at=asset.updated_at,
|
||||
)
|
||||
self.db.add(row)
|
||||
self.db.commit()
|
||||
|
||||
def get(self, asset_id: UUID) -> AssetOut | None:
|
||||
row = self.db.get(AssetORM, str(asset_id))
|
||||
if not row:
|
||||
return None
|
||||
return AssetOut(
|
||||
id=UUID(row.id),
|
||||
name=row.name,
|
||||
serial=row.serial,
|
||||
status=AssetStatus(row.status),
|
||||
revision=row.revision, # <-- wichtig
|
||||
updated_at=row.updated_at,
|
||||
)
|
||||
|
||||
def transition_with_revision(
|
||||
self,
|
||||
asset_id: UUID,
|
||||
expected_revision: int,
|
||||
to_status: AssetStatus,
|
||||
at: datetime,
|
||||
note: str | None,
|
||||
) -> tuple[AssetOut, AssetEventOut]:
|
||||
|
||||
with self.db.begin(): # <-- begin ganz nach oben
|
||||
current = self.db.get(AssetORM, str(asset_id))
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="Asset nicht gefunden")
|
||||
|
||||
from_status = AssetStatus(current.status)
|
||||
|
||||
stmt = (
|
||||
update(AssetORM)
|
||||
.where(
|
||||
AssetORM.id == str(asset_id),
|
||||
AssetORM.revision == expected_revision,
|
||||
)
|
||||
.values(
|
||||
status=str(to_status),
|
||||
updated_at=at,
|
||||
revision=expected_revision + 1,
|
||||
)
|
||||
)
|
||||
|
||||
res = self.db.execute(stmt)
|
||||
if res.rowcount != 1:
|
||||
# aktuelle Revision für saubere Fehlermeldung neu lesen
|
||||
latest = self.db.get(AssetORM, str(asset_id))
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={
|
||||
"message": "Revision-Konflikt",
|
||||
"expected_revision": expected_revision,
|
||||
"current_revision": latest.revision if latest else None,
|
||||
},
|
||||
)
|
||||
|
||||
event_row = AssetEventORM(
|
||||
id=str(uuid4()),
|
||||
asset_id=str(asset_id),
|
||||
from_status=str(from_status),
|
||||
to_status=str(to_status),
|
||||
at=at,
|
||||
note=note,
|
||||
)
|
||||
self.db.add(event_row)
|
||||
|
||||
# nach Commit: updated Asset laden
|
||||
updated = self.db.get(AssetORM, str(asset_id))
|
||||
assert updated is not None
|
||||
|
||||
asset_out = AssetOut(
|
||||
id=UUID(updated.id),
|
||||
name=updated.name,
|
||||
serial=updated.serial,
|
||||
status=AssetStatus(updated.status),
|
||||
revision=updated.revision,
|
||||
updated_at=updated.updated_at,
|
||||
)
|
||||
event_out = AssetEventOut(
|
||||
asset_id=asset_out.id,
|
||||
from_status=from_status,
|
||||
to_status=to_status,
|
||||
at=at,
|
||||
note=note,
|
||||
)
|
||||
return asset_out, event_out
|
||||
|
||||
def list_events(self, asset_id: UUID) -> list[AssetEventOut]:
|
||||
stmt = (
|
||||
select(AssetEventORM)
|
||||
.where(AssetEventORM.asset_id == str(asset_id))
|
||||
.order_by(AssetEventORM.at.asc())
|
||||
)
|
||||
rows = self.db.execute(stmt).scalars().all()
|
||||
return [
|
||||
AssetEventOut(
|
||||
asset_id=UUID(r.asset_id),
|
||||
from_status=AssetStatus(r.from_status),
|
||||
to_status=AssetStatus(r.to_status),
|
||||
at=r.at,
|
||||
note=r.note,
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
Reference in New Issue
Block a user