Skip to content

Commit

Permalink
refactor: update sqlalchemy setup
Browse files Browse the repository at this point in the history
  • Loading branch information
edpyt committed Apr 28, 2024
1 parent 7ff22ab commit 086dcaa
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 19 deletions.
2 changes: 2 additions & 0 deletions src/domain/common/models/domain_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ class DomainEvent(Protocol): ...


class HasDomainEvents(Protocol):
_domain_events: list[DomainEvent]

def clear_domain_events(self) -> None: ...
8 changes: 4 additions & 4 deletions src/domain/common/models/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@
@dataclass(kw_only=True)
class Entity(ABC, HasDomainEvents, Generic[TId]):
id: TId
_events: list[DomainEvent] = field(default_factory=list)
_domain_events: list[DomainEvent] = field(default_factory=list)

@property
def events(self) -> tuple[DomainEvent, ...]:
return tuple(self._events)
return tuple(self._domain_events)

def add_domain_event(self, domain_event: DomainEvent) -> None:
self._events.append(domain_event)
self._domain_events.append(domain_event)

def clear_domain_events(self) -> None:
self._events.clear()
self._domain_events.clear()
22 changes: 17 additions & 5 deletions src/infrastructure/persistence/db/interceptors/publish_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,36 @@
from sqlalchemy.orm import Mapper, QueryContext

from src.infrastructure.persistence.db.extra.sas import sync_as_async
from src.infrastructure.persistence.db.models.base import Base
from src.infrastructure.persistence.db.models.base import BaseClass


@event.listens_for(Mapper, "refresh", named=True)
@sync_as_async
async def saving_changes(
target: Base,
target: BaseClass,
context: QueryContext,
attrs: Optional[set[str]],
) -> Any:
"""Publish domain events interceptor.
:param target: SQLAlchemy ORM Model
:param context: QueryContext
:param attrs: Set of strings
:param attrs: Set of attributes
"""

await publish_domain_events(context)
await publish_domain_events(target.entity, context)


async def publish_domain_events(context: QueryContext | None) -> None: ...
async def publish_domain_events(entity: object | None, context: QueryContext | None) -> None:
if not (entity and context):
return
# Get hold of domain events
events = entity.events # type: ignore [attr-defined]

# Clear domain events
entity.clear_domain_events() # type: ignore [attr-defined]

# Publish domain events
for domain_event in events:
# Call mediator here
print(domain_event) # noqa: T201
13 changes: 13 additions & 0 deletions src/infrastructure/persistence/db/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,16 @@


class Base(DeclarativeBase): ...


class BaseClass(Base):
__abstract__ = True

def __init__(self, entity: object | None = None, **kwargs) -> None:
"""Initialize SQLAlchemy model.
:param entity: Optional `Entity` instance attribute
:param kwargs: SQLAlchemy model params
"""
super().__init__(**kwargs)
self.entity = entity
4 changes: 2 additions & 2 deletions src/infrastructure/persistence/db/models/dinner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

from sqlalchemy.orm import Mapped, mapped_column

from .base import Base
from .base import BaseClass


class Dinner(Base):
class Dinner(BaseClass):
__tablename__ = "dinner"

id: Mapped[UUID] = mapped_column(primary_key=True)
12 changes: 6 additions & 6 deletions src/infrastructure/persistence/db/models/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
from src.application.menu.dto.average_rating import AverageRatingDTO
from src.infrastructure.persistence.db.types.dataclass import DataclassType

from .base import Base
from .base import BaseClass


class Menu(Base):
class Menu(BaseClass):
__tablename__ = "menu"

id: Mapped[UUID] = mapped_column(primary_key=True)
Expand All @@ -27,7 +27,7 @@ class Menu(Base):
updated_date_time: Mapped[datetime]


class MenuSection(Base):
class MenuSection(BaseClass):
__tablename__ = "menu_sections"

id: Mapped[UUID] = mapped_column(primary_key=True)
Expand All @@ -40,7 +40,7 @@ class MenuSection(Base):
menu_id: Mapped[UUID] = mapped_column(ForeignKey("menu.id"), primary_key=True)


class MenuItem(Base):
class MenuItem(BaseClass):
__tablename__ = "menu_items"
__table_args__ = (
ForeignKeyConstraint(
Expand All @@ -61,15 +61,15 @@ class MenuItem(Base):
)


class MenuDinnerIds(Base):
class MenuDinnerIds(BaseClass):
__tablename__ = "menu_dinner_ids"

id: Mapped[UUID] = mapped_column(primary_key=True, default=uuid4)
menu_id: Mapped[UUID] = mapped_column(ForeignKey("menu.id"))
dinner_id: Mapped[UUID] = mapped_column(ForeignKey("dinner.id"))


class MenuReviewIds(Base):
class MenuReviewIds(BaseClass):
__tablename__ = "menu_review_ids"

id: Mapped[UUID] = mapped_column(primary_key=True, default=uuid4)
Expand Down
4 changes: 2 additions & 2 deletions src/infrastructure/persistence/db/models/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

from sqlalchemy.orm import Mapped, mapped_column

from .base import Base
from .base import BaseClass


class MenuReview(Base):
class MenuReview(BaseClass):
__tablename__ = "menu_review"

id: Mapped[UUID] = mapped_column(primary_key=True)
1 change: 1 addition & 0 deletions tests/integration/menu/test_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ async def test_add_menu(menu_repo: MenuRepository) -> None:
host_id=HostId.create_unique(),
)
menu_db = MenuDB(
entity=menu,
id=menu.id.value,
name=menu.name,
description=menu.description,
Expand Down

0 comments on commit 086dcaa

Please sign in to comment.