I have a hierarchy of classes where subclasses can be related together, like here:
class BaseComponent(BaseORMModel):
__tablename__ = "basecomponents"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
type = Column(String(50))
__mapper_args__ = {
"polymorphic_identity": "component",
"polymorphic_on": type,
}
class AComponent(BaseResourceComponent):
__tablename__ = "acomponents"
__mapper_args__ = {"polymorphic_identity": "text", "polymorphic_load": "inline"}
id = Column(UUID(as_uuid=True), ForeignKey("basecomponents.id", ondelete="CASCADE"), primary_key=True)
text = Column(TEXT)
class BComponent(BaseResourceComponent):
__tablename__ = "bcomponents"
__mapper_args__ = {"polymorphic_identity": "audio", "polymorphic_load": "inline"}
id = Column(UUID(as_uuid=True), ForeignKey("basecomponents.id", ondelete="CASCADE"), primary_key=True)
a_component_id = Column(UUID(as_uuid=True), ForeignKey("acomponents.id", ondelete="CASCADE"), nullable=True)
acomponent = relationship(
"AComponent",
foreign_keys=[a_component_id],
backref=backref("bcomponent", passive_deletes=True, uselist=False),
)
If I delete a Acomponent object, using this approach
query = select([model]).filter_by(id=id).options(*options)
component = self.db.execute(query).unique().scalar_one()
self.db.delete(component)
I see that Acomponent is deleted, as well as its BaseComponent, BComponent is deleted to but the BaseComponent associated to the BComponent is not. This is kind of reasonable due to the cascade policy, but it sounds weird SQLAlchemy does not handle this.
IN brief:
Deleting AComponent produces a CASCADE Delete at the database layer over BComponent as a consequence of the FK BComponent.acomponent_id
.
the BaseComponent related to the AComponent object is deleted too, while the one related to the BComponent is kept.
How to remove also the BaseComponent bound to the deleted BComponent?