I am using FastAPI + SQLAlchemy. I have a table User
class User(Base):
id: Mapped[uuid.UUID] = mapped_column(primary_key=True)
organization_users: Mapped[List["OrganizationUser"]] = relationship(
back_populates="user",
lazy="selectin",
foreign_keys=[OrganizationUser.user_id],
)
and a table OrganizationUser:
class OrganizationUser(Base):
id: Mapped[uuid.UUID] = mapped_column(primary_key=True)
user: Mapped["User"] = relationship(
back_populates="organization_users",
lazy="selectin",
foreign_keys=[user_id],
)
There are many other tables and relationships.
I have recently started to add cascade delete to various relationships. This means that I have started to explicitly add relationships to User (for example, there was a relationship between User and UserSocialAccount, but that was only obvious from the ForeignKey to User in UserSocialAccount. Now I have explicitly added the relationship to User like this:
social_accounts: Mapped[List["UserSocialAccount"]] = relationship(
cascade="all, delete-orphan",
)
)
The problem is I am now getting a sqlalchemy.exc.MissingGreenlet error when running the tests for OrganizationUser edit. The weird thing is that the error is not consistent; sometimes I run all the scenarios and they run just fine, and sometimes 1-2 produce the error. The error happens when I access
organization_user.user.email
I already use a selectin load for OrganizationUser.user, so I can’t understand why I am getting this error. Previously, when adding cascade delete to Organization, I was able to stop the error by adding selectin to Organization.groups (which references entity OrganizationGroup, which is connected to OrganizationUser via OrganizationGroupUser). Didn’t make much sense, but if it works it works. Now I have added a whole bunch of relationships to User, I don’t want to use selectin for all of them. And I can’t understand why a relationship between User and UserSession, or LoginAttempts, or Signup, should be eagerly loaded in order for me to access organization_user.user.email. I tried changing to
cascade="delete, delete-orphan"
to no avail.