Coverage for polar/custom_field/attachment.py: 91%
18 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 12:42 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 12:42 +0000
1from typing import TYPE_CHECKING, Any
2from uuid import UUID
4from sqlalchemy import Boolean, ForeignKey, Integer, Uuid, event
5from sqlalchemy.orm import (
6 Mapped,
7 Mapper,
8 declared_attr,
9 mapped_column,
10 relationship,
11)
13if TYPE_CHECKING: 13 ↛ 14line 13 didn't jump to line 14 because the condition on line 13 was never true
14 from polar.models import CustomField
17class AttachedCustomFieldMixin:
18 """Mixin for models that attach custom fields."""
20 custom_field_id: Mapped[UUID] = mapped_column(
21 Uuid,
22 ForeignKey("custom_fields.id", ondelete="cascade"),
23 primary_key=True,
24 )
25 order: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
26 required: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
28 @declared_attr
29 def custom_field(cls) -> Mapped["CustomField"]:
30 # This is an association table, so eager loading makes sense
31 return relationship("CustomField", lazy="joined")
34attached_custom_fields_models: set[type[AttachedCustomFieldMixin]] = set()
37# Event listener to track models inheriting from AttachedCustomFieldMixin
38@event.listens_for(Mapper, "mapper_configured")
39def track_attached_custom_field_mixin(_mapper: Mapper[Any], class_: type) -> None:
40 if issubclass(class_, AttachedCustomFieldMixin):
41 attached_custom_fields_models.add(class_)