Add optional soft delete support #2033
Replies: 1 comment
-
|
This is a reasonable feature to consider, but it should probably be scoped pretty carefully. Soft delete looks small at the model level, but once it becomes part of The class SoftDeleteMixin:
deleted_at: datetime | None = Field(default=None)
class Hero(SQLModel, SoftDeleteMixin, table=True):
id: int | None = Field(default=None, primary_key=True)
name: strFor the session API, I would avoid making soft delete implicit in the normal with SoftDeleteSession(engine) as session:
session.delete(hero) # sets deleted_at
session.commit()The harder and more important part is query filtering. If For the “include deleted” escape hatch, I’d lean toward a SQLAlchemy-style execution option rather than adding a special keyword to every heroes = session.exec(select(Hero)).all()
all_heroes = session.exec(
select(Hero).execution_options(include_deleted=True)
).all()That keeps the query object carrying the behavior and avoids widening the Custom field names are useful, but they also make this more than just a mixin. If class Hero(SQLModel, table=True):
__soft_delete_field__ = "removed_at"
id: int | None = Field(default=None, primary_key=True)
name: str
removed_at: datetime | None = Field(default=None)The main cases I would want covered before merging something like this are:
One detail worth deciding early is whether soft delete should cascade. SQLAlchemy’s normal delete cascade semantics do not map perfectly to “set If my answer solved your problem, you can click answered the question. I'm really here to help, and along the way I'm also collecting Galaxy Brain badges haha 😆 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Example Code
Description
I would like to ask whether SQLModel maintainers would consider adding optional soft delete support.
There was a previous PR for this feature: #1890
That PR was closed due to inactivity. It added delete interception, but it did not include query filtering and used a fixed
deleted_atfield.The API I would like to discuss could include:
SoftDeleteMixin, usingdeleted_atby defaultSoftDeleteSession.delete(), which marks soft-deletable models as deleted instead of physically deleting themSoftDeleteSession.exec(select(...)), so soft-deleted rows are hidden by defaultinclude_deleted=Trueto include soft-deleted rows__soft_delete_field__Example usage:
By default,
heroeswould not include soft-deleted rows.For custom field names:
Would this kind of optional soft delete API be welcome in SQLModel?
Operating System
macOS
Operating System Details
No response
Project Version
0.0.39
Python Version
No response
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions