flipbit03 / sqlalchemy-easy-softdelete

Easily add soft-deletion to your SQLAlchemy Models
Other
62 stars 13 forks source link

Models that don't inherit from the mixin class also have results filtered #22

Closed spr closed 1 year ago

spr commented 1 year ago

Description

On models that don't inherit from the generated SoftDeleteMixin class, but also have a field of the same name (so a deleted_at field in this case), select results are still filtered without providing the execution option.

I can work around this, but it'd be nice if the filtering only applied to models inheriting from the mixin.

What I Did

class Note(BaseModel):
    __tablename__ = "notes"
   id = Column(Integer, primary_key=True, autoincrement=True)
   deleted_at = Column(DateTime, nullable=True)

new_note = Note(deleted_at=datetime.utcnow())
session.add(new_note)
session.commit(new_note)
item = Note.query.filter(Note.id == new_note.id).first()
assert item is not None  # fails
flipbit03 commented 1 year ago

That is actually a pretty cool find, thank you for uncovering this! We'll need to think about a way to flag this inheritance somehow as metadata that is contained/passed to the Table object, because the internal "query rewriter" only sees Tables, and not the Declarative Classes themselves. Honestly I don't even know if it is possible, but I'll do some research.

flipbit03 commented 1 year ago

@spr Thanks for reporting this! I've created a new argument for the Mixin creator that will allow you to ignore certain tables by table name! Example:

If you're using a schema-less database (e.g.: SQLite), table_schema= is optional.


# Create a Class that inherits from our class builder
class SoftDeleteMixin(generate_soft_delete_mixin_class(
    # This table will be ignored by the hook
    # even if the table has the soft-delete column
    ignored_tables=[
        IgnoredTable(table_schema="public", name="cars"),
        IgnoredTable(table_schema="public", name="stores"),
        IgnoredTable(table_schema="public", name="employees"),
])):
    # type hint for autocomplete IDE support
    deleted_at: datetime
spr commented 1 year ago

That's great, thank you for the quick response!

flipbit03 commented 1 year ago

@spr if possible, I'm interested in following up with you if it suits your use case/works well. Please lmk what you find!

spr commented 1 year ago

Yep, it works for our project just fine, replaces the old hand-rolled mixin we had with sqlalchemy 1.3.

flipbit03 commented 1 year ago

That's great to hear. Thank you @spr!