diff --git a/server/polar/license_key/service.py b/server/polar/license_key/service.py index bb4e8deb49..107cc5008a 100644 --- a/server/polar/license_key/service.py +++ b/server/polar/license_key/service.py @@ -2,7 +2,7 @@ from uuid import UUID import structlog -from sqlalchemy import Select, and_, func, select +from sqlalchemy import Select, func, select from sqlalchemy.orm import contains_eager, joinedload from polar.auth.models import AuthSubject, is_customer, is_organization, is_user @@ -71,19 +71,9 @@ async def get_loaded( ) -> LicenseKey | None: query = ( self._get_select_base() - .join( - LicenseKeyActivation, - onclause=( - and_( - LicenseKeyActivation.license_key_id == LicenseKey.id, - LicenseKeyActivation.deleted_at.is_(None), - ) - ), - isouter=True, - ) .join(Benefit, onclause=LicenseKey.benefit_id == Benefit.id) .options( - contains_eager(LicenseKey.activations), + joinedload(LicenseKey.activations), contains_eager(LicenseKey.benefit), ) .where(LicenseKey.id == id) diff --git a/server/polar/models/license_key.py b/server/polar/models/license_key.py index 9a65b57ee2..255dddafd9 100644 --- a/server/polar/models/license_key.py +++ b/server/polar/models/license_key.py @@ -74,11 +74,26 @@ def benefit(cls) -> Mapped[BenefitLicenseKeys]: limit_activations: Mapped[int | None] = mapped_column(Integer, nullable=True) @declared_attr - def activations(cls) -> Mapped[list["LicenseKeyActivation"]]: + def all_activations(cls) -> Mapped[list["LicenseKeyActivation"]]: return relationship( "LicenseKeyActivation", lazy="raise", back_populates="license_key" ) + @declared_attr + def activations(cls) -> Mapped[list["LicenseKeyActivation"]]: + # Prices are almost always needed, so eager loading makes sense + return relationship( + "LicenseKeyActivation", + lazy="raise", + primaryjoin=( + "and_(" + "LicenseKeyActivation.license_key_id == LicenseKey.id, " + "LicenseKeyActivation.deleted_at.is_(None)" + ")" + ), + viewonly=True, + ) + usage: Mapped[int] = mapped_column(Integer, nullable=False, default=0) limit_usage: Mapped[int | None] = mapped_column(Integer, nullable=True)