Skip to main content

SQLAlchemy Easy Soft-Delete

PyPI - Python Version PyPI - Version PyPI - Types PyPI - Downloads Supported SQLAlchemy Versions

Easily add soft-deletion to your SQLAlchemy Models and automatically filter out soft-deleted objects from your queries and relationships.

This package can generate a tailor-made SQLAlchemy Mixin that can be added to your SQLAlchemy Models, making them contain a field that, when set, will mark the entity as being soft-deleted.

The library also installs a hook which dynamically rewrites all selects which are sent to the database for all tables that implement the soft-delete mixin, providing a seamless experience in both manual queries and model relationship accesses.

Mixin generation is fully customizable and you can choose the field name, its type, and the presence of (soft-)delete/undelete methods.

The default implementation will generate a deleted_at field in your models, of type DateTime(timezone=True), and will also provide a .delete(v: Optional = datetime.utcnow()) and .undelete() methods.

Installation:

pip install sqlalchemy-easy-softdelete

How to use:

from sqlalchemy_easy_softdelete.mixin import generate_soft_delete_mixin_class
from sqlalchemy_easy_softdelete.hook import IgnoredTable
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import Integer
from datetime import datetime

# Create a Class that inherits from our class builder
class SoftDeleteMixin(
    generate_soft_delete_mixin_class(  # type: ignore[misc]
        # 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"),]
    )
):
    # The `type: ignore[misc]` above is required because the mixin is dynamically generated

    # Type hint for IDE autocomplete and type checker support.
    # Using Mapped[T | None] ensures type checkers understand this is a
    # SQLAlchemy column that supports query operations like .where()
    deleted_at: Mapped[datetime | None]

    # Optional: Add method stubs for delete/undelete for type checker support.
    # The actual implementations are provided by the generated mixin class.
    def delete(self, v: datetime | None = None) -> None:
        super().delete(v)  # type: ignore[misc]

    def undelete(self) -> None:
        super().undelete()  # type: ignore[misc]

# Apply the mixin to your Models
class Base(DeclarativeBase):
    pass

class Fruit(Base, SoftDeleteMixin):
    __tablename__ = "fruit"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)

Example Usage:

all_active_fruits = session.query(Fruit).all()

This will generate a query with an automatic WHERE fruit.deleted_at IS NULL condition added to it.

all_fruits = session.query(Fruit).execution_options(include_deleted=True).all()

Setting include_deleted=True (attribute name can be customized) in the query disables soft delete for that query.

The rewrite never modifies your statement or anything inside it, so statements, subqueries and lambda_stmt() objects can be built once and executed many times, with or without include_deleted.

Rewrite cache

To know which tables a SELECT reads from, the library has SQLAlchemy work out the statement's final FROM clause, which for an ORM statement runs SQLAlchemy's ORM compilation of it, outside of SQLAlchemy's own compiled cache. The library remembers what it adds to a statement by the statement's cache key, so later statements of the same shape (the same SQL, with any parameter values) skip that work.

The cache holds 500 statement shapes by default, the same as SQLAlchemy's default query_cache_size. An application with more distinct statements can raise it, and 0 disables it:

class SoftDeleteMixin(generate_soft_delete_mixin_class(rewrite_cache_size=2000)):  # type: ignore[misc]
    deleted_at: Mapped[datetime | None]

Each entry takes 1-4 KB, most of it the statement's cache key. To see how well the size fits, read the cache statistics of the mixin's rewriter. misses counts the statement shapes that were analyzed and then remembered: a misses count that keeps growing while size stays at max_size means the cache is too small.

SoftDeleteMixin._sqlalchemy_easy_softdelete_rewriter.rewrite_cache_info()
# RewriteCacheInfo(hits=48210, misses=212, uncacheable=35, size=212, max_size=500)

uncacheable counts the statements whose rewrite cannot be remembered, and is redone on every execution, such as statements without a SQLAlchemy cache key.

Contributing

Contributions are welcome! See CONTRIBUTING.md for development setup and guidelines.

License

  • BSD-3-Clause

Metadata

Release files for sqlalchemy-easy-softdelete 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sqlalchemy-easy-softdelete 1.1.0
File Size Uploaded Provenance Actions
sqlalchemy_easy_softdelete-1.1.0.tar.gz 47.2 kB With provenance Details for sqlalchemy_easy_softdelete-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sqlalchemy-easy-softdelete 1.1.0
File Interpreter ABI Platform Actions
sqlalchemy_easy_softdelete-1.1.0-py3-none-any.whl Python 3 none any Details for sqlalchemy_easy_softdelete-1.1.0-py3-none-any.whl

Total release size: 67.4 kB

Release files / sqlalchemy_easy_softdelete-1.1.0.tar.gz

Download URL sqlalchemy_easy_softdelete-1.1.0.tar.gz
Size 47.2 kB
Tags Source
SHA-256 checksum
How to use checksums
e0b78a0e1e2b477e519c73ef889e938e3ff34433a8d6c47ad6c3582e0e99d0a4
BLAKE2b-256 checksum
How to use checksums
18e90c64409fc11fcbdcf37404256c45716afded184ba34daba468af6a54f494
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Release files / sqlalchemy_easy_softdelete-1.1.0-py3-none-any.whl

Download URL sqlalchemy_easy_softdelete-1.1.0-py3-none-any.whl
Size 20.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
71c9e672ea946a9a3e8005d1164017ed6e8f1d4c07e51819fa92a5dfcc7a3400
BLAKE2b-256 checksum
How to use checksums
c2f52bd1510e71dd5ac3a1b9819ac033aa36c81f2a2889aad0a012f3a67abe52
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Security for sqlalchemy-easy-softdelete 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for sqlalchemy_easy_softdelete-1.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page