Skip to content

Best practice for common filters like for soft-delete when using the asyncio API #7973

Closed

Description

@pansen

Describe the use case

I have entities, which are supposed to be soft-deleted by setting an deleted_at attribute per entity. If that value is greater than timestamptz('1970-01-01T00:00:00+00:00'), the instance / row is considered deleted. My goal is, to let entites / rows marked as soft-deleted to completely disappear for the whole application.

For the query API of SqlAlchemy, it was easy to establish a custom Query subclass, wire that properly and required filters, to omit soft-deleted items in all operations.

When using the asyncio API, the Query class is not used, but sqlalchemy/sql/expression.py#select statements are created. From what I understand, it is not easily possible to wire in some extra filter expression, which is automagically in place.

Databases / Backends / Drivers targeted

Postgresql

Example Use

Lets assume I'm creating a statement to gather multiple entities:

models = (await sqla_session.execute(select(Model)
                                         )) \
        .scalars().all()

I want this to be in fact:

POSIX_ZERO = datetime(1970, 1, 1, tzinfo=UTC)

models = (await sqla_session.execute(select(Model)
                      filter(deleted_at == POSIX_ZERO)
                                         )) \
        .scalars().all()

without having the requirement to express this filter part: filter(deleted_at == POSIX_ZERO) in the statement. I'm looking for a way to have this filter part present in all statements, automatically. This example is focussed on reading, select, but my goal is to apply this to all CRUD operations equally.

Additional context

Thanks in advance :)

Activity

  1. added
    requires triage
    use case
    on Apr 28, 2022
  2. pansen commented on Apr 28, 2022

    @pansen
    SponsorAuthor

    Awesome, adding global where criteria is what I was looking for.

    Thank you very much!

  3. removed
    requires triage
    on Apr 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    use case

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions