|
2 | 2 |
|
3 | 3 | from typing import Any, ClassVar |
4 | 4 |
|
5 | | -from sqlalchemy import MetaData, event, select |
| 5 | +from sqlalchemy import MetaData, event, select, true |
6 | 6 | from sqlalchemy import inspect as sa_inspect |
7 | 7 | from sqlalchemy.exc import IntegrityError |
8 | 8 | from sqlalchemy.orm import Session as SASession |
9 | | -from sqlalchemy.orm import with_loader_criteria |
| 9 | +from sqlalchemy.orm import class_mapper, with_loader_criteria |
10 | 10 | from sqlalchemy.sql import expression |
11 | 11 | from sqlmodel import Field, Session, SQLModel |
12 | 12 |
|
@@ -137,12 +137,16 @@ def _identity_dict_from_instance(instance: SoftDeleteModel) -> dict[str, Any] | |
137 | 137 | return identity |
138 | 138 |
|
139 | 139 |
|
140 | | -def _soft_delete_filter(cls) -> Any: |
141 | | - mapper = sa_inspect(cls, raiseerr=False) |
142 | | - if mapper is None: |
143 | | - return expression.true() |
144 | | - column = mapper.c.is_deleted |
145 | | - return column.is_(False) |
| 140 | +def _soft_delete_filter(entity_cls) -> Any: |
| 141 | + try: |
| 142 | + # ensure this is a mapped class and has the column |
| 143 | + class_mapper(entity_cls) |
| 144 | + col = getattr(entity_cls, "is_deleted", None) |
| 145 | + if col is not None: |
| 146 | + return col.is_(False) |
| 147 | + except Exception: |
| 148 | + pass |
| 149 | + return true() |
146 | 150 |
|
147 | 151 |
|
148 | 152 | @event.listens_for(SASession, "before_flush") |
@@ -178,7 +182,7 @@ def _filter_soft_deleted(execute_state) -> None: |
178 | 182 | execute_state.statement = execute_state.statement.options( |
179 | 183 | with_loader_criteria( |
180 | 184 | SoftDeleteModel, |
181 | | - lambda cls: _soft_delete_filter(cls), |
| 185 | + _soft_delete_filter, |
182 | 186 | include_aliases=True, |
183 | 187 | ) |
184 | 188 | ) |
|
0 commit comments