|
| 1 | +""" |
| 2 | +Deferred Column Property implementation for SQLModel. |
| 3 | +
|
| 4 | +This module provides deferred_column_property function that creates column properties |
| 5 | +with safe deferred loading - returning fallback values instead of raising DetachedInstanceError. |
| 6 | +""" |
| 7 | + |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from sqlalchemy.orm import ColumnProperty |
| 11 | +from sqlalchemy.orm.strategies import DeferredColumnLoader, _state_session |
| 12 | + |
| 13 | + |
| 14 | +class SafeDeferredColumnLoader(DeferredColumnLoader): |
| 15 | + """ |
| 16 | + A custom deferred column loader that returns a fallback value instead of |
| 17 | + raising DetachedInstanceError when the session is detached. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, parent, strategy_key, fallback_value=None): |
| 21 | + super().__init__(parent, strategy_key) |
| 22 | + self.fallback_value = fallback_value |
| 23 | + |
| 24 | + def _load_for_state(self, state, passive): |
| 25 | + """ |
| 26 | + Override the default behavior to return fallback value instead of raising |
| 27 | + DetachedInstanceError when session is None. |
| 28 | + """ |
| 29 | + from sqlalchemy.orm import LoaderCallableStatus |
| 30 | + |
| 31 | + if not state.key: |
| 32 | + return LoaderCallableStatus.ATTR_EMPTY |
| 33 | + |
| 34 | + # Check passive flags |
| 35 | + from sqlalchemy.orm import PassiveFlag |
| 36 | + |
| 37 | + if not passive & PassiveFlag.SQL_OK: |
| 38 | + return LoaderCallableStatus.PASSIVE_NO_RESULT |
| 39 | + |
| 40 | + # Check if we have a session before attempting to load |
| 41 | + session = _state_session(state) |
| 42 | + if session is None: |
| 43 | + # No session available, return fallback value directly |
| 44 | + return self.fallback_value |
| 45 | + |
| 46 | + # We have a session, use the parent implementation |
| 47 | + return super()._load_for_state(state, passive) |
| 48 | + |
| 49 | + |
| 50 | +class SafeColumnProperty(ColumnProperty): |
| 51 | + """ |
| 52 | + Custom ColumnProperty that uses SafeDeferredColumnLoader for deferred loading. |
| 53 | + """ |
| 54 | + |
| 55 | + def __init__(self, *args, fallback_value=None, **kwargs): |
| 56 | + self.fallback_value = fallback_value |
| 57 | + super().__init__(*args, **kwargs) |
| 58 | + |
| 59 | + def do_init(self): |
| 60 | + """Override to set our custom strategy after parent initialization.""" |
| 61 | + super().do_init() |
| 62 | + |
| 63 | + # Replace the strategy with our safe version if it's deferred |
| 64 | + if self.deferred and hasattr(self, "strategy"): |
| 65 | + # Create our safe loader with the same parameters as the original |
| 66 | + original_strategy = self.strategy |
| 67 | + |
| 68 | + # Create new strategy with proper initialization |
| 69 | + safe_strategy = SafeDeferredColumnLoader( |
| 70 | + parent=self, # The ColumnProperty itself |
| 71 | + strategy_key=original_strategy.strategy_key, |
| 72 | + fallback_value=self.fallback_value, |
| 73 | + ) |
| 74 | + |
| 75 | + self.strategy = safe_strategy |
| 76 | + |
| 77 | + |
| 78 | +def deferred_column_property( |
| 79 | + expression: Any, *, fallback_value: Any, deferred: bool = True, **kwargs: Any |
| 80 | +) -> SafeColumnProperty: |
| 81 | + """ |
| 82 | + Create a deferred column property that returns a fallback value instead of raising |
| 83 | + DetachedInstanceError when accessed on a detached instance. |
| 84 | +
|
| 85 | + This function behaves exactly like SQLAlchemy's column_property, but with safe |
| 86 | + deferred loading behavior when the session is detached. |
| 87 | +
|
| 88 | + Args: |
| 89 | + expression: The SQL expression for the column property |
| 90 | + fallback_value: Value to return when property cannot be loaded (required) |
| 91 | + deferred: Whether to defer loading the property (defaults to True) |
| 92 | + **kwargs: Additional arguments passed to column_property |
| 93 | +
|
| 94 | + Returns: |
| 95 | + A SafeColumnProperty instance |
| 96 | +
|
| 97 | + Example: |
| 98 | + ```python |
| 99 | + class User(SQLModel, table=True): |
| 100 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 101 | + user_id: Optional[int] = None |
| 102 | +
|
| 103 | + @classmethod |
| 104 | + def __declare_last__(cls): |
| 105 | + cls.computed_value = deferred_column_property( |
| 106 | + cls.__table__.c.user_id * 2, |
| 107 | + fallback_value=0, |
| 108 | + deferred=True |
| 109 | + ) |
| 110 | + ``` |
| 111 | + """ |
| 112 | + kwargs["deferred"] = deferred |
| 113 | + return SafeColumnProperty(expression, fallback_value=fallback_value, **kwargs) |
0 commit comments