sqlmodel-ext 0.3.0__py3-none-any.whl → 0.3.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlmodel_ext/__init__.py CHANGED
@@ -20,7 +20,7 @@ Quick start::
20
20
  user = await user.save(session)
21
21
  users = await User.get(session, fetch_mode="all")
22
22
  """
23
- __version__ = "0.2.1"
23
+ __version__ = "0.3.3"
24
24
 
25
25
  # Base
26
26
  from sqlmodel_ext.base import SQLModelBase, ExtraIgnoreModelBase
sqlmodel_ext/_compat.py CHANGED
@@ -14,6 +14,7 @@ if sys.version_info >= (3, 14):
14
14
  from enum import StrEnum
15
15
  from typing import Literal, Union, get_args, get_origin
16
16
 
17
+ from pydantic_core import PydanticUndefined
17
18
  from sqlalchemy import String
18
19
  from sqlalchemy.orm.attributes import InstrumentedAttribute
19
20
 
@@ -27,6 +28,24 @@ if sys.version_info >= (3, 14):
27
28
  import sqlmodel.main
28
29
  _original_get_sqlalchemy_type = sqlmodel.main.get_sqlalchemy_type
29
30
 
31
+ def _get_explicit_sa_type(field):
32
+ """
33
+ Extract an explicit ``sa_type`` from a SQLModel/Pydantic FieldInfo.
34
+
35
+ Matches upstream ``sqlmodel.main._get_sqlmodel_field_value`` semantics:
36
+ prefers ``FieldInfoMetadata.sa_type`` then falls back to the direct
37
+ ``field.sa_type`` attribute. Returns ``PydanticUndefined`` when unset.
38
+ """
39
+ # Prefer FieldInfoMetadata.sa_type (set via Field(sa_type=...))
40
+ metadata = getattr(field, 'metadata', None)
41
+ if metadata:
42
+ for item in metadata:
43
+ sa_type = getattr(item, 'sa_type', PydanticUndefined)
44
+ if sa_type is not PydanticUndefined:
45
+ return sa_type
46
+ # Fallback to direct attribute
47
+ return getattr(field, 'sa_type', PydanticUndefined)
48
+
30
49
  def _patched_get_sqlalchemy_type(field):
31
50
  """
32
51
  Fix SQLModel's get_sqlalchemy_type for Python 3.14 type issues.
@@ -34,13 +53,29 @@ if sys.version_info >= (3, 14):
34
53
  Handles ForwardRef, ClassVar, Literal, Mapped, and custom types
35
54
  that cause issubclass errors under PEP 649.
36
55
  """
56
+ # Respect explicit sa_type from Field(sa_type=...) — must take
57
+ # precedence over annotation-based auto-detection, matching upstream
58
+ # SQLModel behavior (sqlmodel/main.py::get_sqlalchemy_type checks
59
+ # sa_type before everything else). Without this, fields like
60
+ # ``options: list[str] | None = Field(sa_type=JSON)`` incorrectly
61
+ # get JSONB from the Union[list, None] -> JSONB branch below,
62
+ # breaking non-PostgreSQL dialects (e.g., SQLite in tests).
63
+ explicit_sa_type = _get_explicit_sa_type(field)
64
+ if explicit_sa_type is not PydanticUndefined:
65
+ return explicit_sa_type
66
+
37
67
  # Check field.metadata (Pydantic-processed Annotated types)
38
68
  metadata = getattr(field, 'metadata', None)
39
69
  if metadata:
70
+ # Pass field.annotation as source_type so handlers that need the element type
71
+ # (e.g. _PendingArrayHandler extracting T from list[T] to compute ARRAY(T))
72
+ # can resolve. handler=None is fine because the sa_type extraction path only
73
+ # reads metadata['sa_type'] and never invokes the schema itself.
74
+ field_annotation = getattr(field, 'annotation', None)
40
75
  for metadata_item in metadata:
41
76
  if hasattr(metadata_item, '__get_pydantic_core_schema__'):
42
77
  try:
43
- schema = metadata_item.__get_pydantic_core_schema__(None, None)
78
+ schema = metadata_item.__get_pydantic_core_schema__(field_annotation, None)
44
79
  if isinstance(schema, dict) and 'metadata' in schema:
45
80
  sa_type = schema['metadata'].get('sa_type')
46
81
  if sa_type is not None:
@@ -75,7 +110,9 @@ if sys.version_info >= (3, 14):
75
110
  for md in inner_args[1:]:
76
111
  if hasattr(md, '__get_pydantic_core_schema__'):
77
112
  try:
78
- schema = md.__get_pydantic_core_schema__(None, None)
113
+ # Pass first_arg (the full Annotated alias) as source_type so
114
+ # handlers like _PendingArrayHandler can extract the element type.
115
+ schema = md.__get_pydantic_core_schema__(first_arg, None)
79
116
  if isinstance(schema, dict) and 'metadata' in schema:
80
117
  sa_type = schema['metadata'].get('sa_type')
81
118
  if sa_type is not None:
@@ -123,7 +160,10 @@ if sys.version_info >= (3, 14):
123
160
  for md in args[1:]:
124
161
  if hasattr(md, '__get_pydantic_core_schema__'):
125
162
  try:
126
- schema = md.__get_pydantic_core_schema__(None, None)
163
+ # Pass annotation (the full Annotated form) as source_type so
164
+ # handlers needing the element type (_PendingArrayHandler etc.)
165
+ # can extract T from list[T].
166
+ schema = md.__get_pydantic_core_schema__(annotation, None)
127
167
  if isinstance(schema, dict) and 'metadata' in schema:
128
168
  sa_type = schema['metadata'].get('sa_type')
129
169
  if sa_type is not None:
sqlmodel_ext/base.py CHANGED
@@ -15,7 +15,7 @@ import re
15
15
  import sys
16
16
  import types
17
17
  import typing
18
- from typing import Any, get_args, get_origin
18
+ from typing import Any, Self, Sequence, get_args, get_origin
19
19
 
20
20
  from pydantic import ConfigDict, model_validator
21
21
  from pydantic.fields import FieldInfo
@@ -102,6 +102,47 @@ def _merge_field_info_attrs(target: SQLModelFieldInfo, source: SQLModelFieldInfo
102
102
  target.metadata = list(target_meta) + list(source_meta)
103
103
 
104
104
 
105
+ def _find_field_info_in_annotated(annotation: Any) -> SQLModelFieldInfo | None:
106
+ """
107
+ Extract SQLModel ``FieldInfo`` embedded in ``Annotated[T, Field(...)]`` metadata.
108
+
109
+ Used by the metaclass sa_type injection loop. When a field is declared
110
+ ``Annotated[X, Field(default_factory=list, ...)]`` *without* an explicit
111
+ ``= ...`` assignment, ``attrs[field_name]`` is ``Undefined``. Replacing
112
+ it with a fresh ``Field(sa_type=sa_type)`` would discard the user's
113
+ Field metadata (``default_factory``, ``max_length``, validators, ...)
114
+ that lives inside the Annotated args. This helper recovers that
115
+ FieldInfo so the caller can attach ``sa_type`` to the user's Field
116
+ instead of clobbering it. The bug only surfaces after 2+ levels of
117
+ inheritance: single-class instantiation goes through Pydantic's native
118
+ Annotated path and works, but child classes rebuild ``model_fields``
119
+ from the clobbered ``attrs`` and the field becomes silently
120
+ ``is_required=True``.
121
+
122
+ Multiple FieldInfo args (e.g. ``Annotated[Str64, Field(unique=True)]``
123
+ expands to ``Annotated[str, Field(max_length=64), Field(unique=True)]``)
124
+ are merged into a single shallow copy so the shared Annotated metadata
125
+ singletons are never mutated.
126
+
127
+ :param annotation: Field type annotation
128
+ :returns: Merged SQLModelFieldInfo (shallow copy, safe to mutate), or None
129
+ """
130
+ if get_origin(annotation) is not typing.Annotated:
131
+ return None
132
+ args = get_args(annotation)
133
+ if len(args) < 2:
134
+ return None
135
+ sqlmodel_fis: list[SQLModelFieldInfo] = [
136
+ arg for arg in args[1:] if isinstance(arg, SQLModelFieldInfo)
137
+ ]
138
+ if not sqlmodel_fis:
139
+ return None
140
+ merged = copy.copy(sqlmodel_fis[0])
141
+ for extra_fi in sqlmodel_fis[1:]:
142
+ _merge_field_info_attrs(merged, extra_fi)
143
+ return merged
144
+
145
+
105
146
  def _make_annotation_optional(annotation: typing.Any) -> typing.Any:
106
147
  """
107
148
  Convert type annotation to optional: ``T → T | None``
@@ -179,6 +220,27 @@ def _apply_all_fields_optional(
179
220
  if original_ann is None:
180
221
  continue
181
222
 
223
+ # Bug fix: when a field is declared as ``field: T = Field(gt=..., le=...)`` (non-Annotated form),
224
+ # MRO ``__annotations__`` only stores the bare ``T``. The ``Field(...)`` constraint metadata
225
+ # lives on the right-hand-side assignment, so all_fields_optional-derived UpdateRequest classes
226
+ # lose those constraints (e.g. UFT-style "missing range" warnings fire on derived fields that
227
+ # had constraints in the source class). Patch: when ``original_ann`` is not already Annotated,
228
+ # pull constraints from the base class's resolved ``model_fields[name].metadata`` (Pydantic
229
+ # stores them there as ``[Gt(0), Le(600), ...]``) and re-wrap into ``Annotated[T, *metadata]``,
230
+ # letting downstream ``_make_annotation_optional`` preserve the constraints when converting
231
+ # to ``T | None``. The root recommended fix is still to declare fields in Annotated form at
232
+ # the source; this patch is defense-in-depth for legacy ``field: T = Field(...)`` declarations.
233
+ if get_origin(original_ann) is not typing.Annotated:
234
+ for base in bases:
235
+ base_model_fields = getattr(base, 'model_fields', None)
236
+ if not base_model_fields:
237
+ continue
238
+ base_field_info = base_model_fields.get(field_name)
239
+ if base_field_info is None or not base_field_info.metadata:
240
+ continue
241
+ original_ann = typing.Annotated[original_ann, *base_field_info.metadata]
242
+ break
243
+
182
244
  # Skip Literal type fields (e.g. discriminator):
183
245
  # Literal['text'] | None breaks Pydantic discriminated union
184
246
  raw_type = original_ann
@@ -268,10 +330,33 @@ def _recover_annotated_sqlmodel_fields(
268
330
  all_annotated.update(annotations)
269
331
 
270
332
  for field_name, field_type in all_annotated.items():
271
- if get_origin(field_type) is not typing.Annotated:
333
+ # Unwrap Optional/Union wrappers: forms like ``Annotated[X, Field(sa_type=BigInteger)] | None``
334
+ # have ``get_origin() == Union`` (or ``types.UnionType`` for PEP 604 ``|``); we must
335
+ # peel back to find the inner Annotated to extract the SQLModel FieldInfo. Otherwise
336
+ # nullable aliases like ``PositiveBigInt | None`` lose ``sa_type`` and the SA column
337
+ # silently degrades (e.g. BigInteger → Integer → asyncpg int32 overflow on large defaults).
338
+ annotated_type = field_type
339
+ union_args: list[typing.Any] | None = None
340
+ union_origin = get_origin(field_type)
341
+ # ``X | None`` (PEP 604) has origin ``types.UnionType``; ``Union[X, None]`` is ``typing.Union``.
342
+ # Match both without depending on ``types`` import inside any version block.
343
+ is_union = union_origin is typing.Union or (
344
+ union_origin is not None and getattr(union_origin, '__name__', '') == 'UnionType'
345
+ )
346
+ if is_union:
347
+ union_args = list(get_args(field_type))
348
+ annotated_in_union = next(
349
+ (arg for arg in union_args if get_origin(arg) is typing.Annotated),
350
+ None,
351
+ )
352
+ if annotated_in_union is None:
353
+ continue
354
+ annotated_type = annotated_in_union
355
+
356
+ if get_origin(annotated_type) is not typing.Annotated:
272
357
  continue
273
358
 
274
- args = get_args(field_type)
359
+ args = get_args(annotated_type)
275
360
  if len(args) < 2:
276
361
  continue
277
362
 
@@ -313,10 +398,24 @@ def _recover_annotated_sqlmodel_fields(
313
398
  base_type = args[0]
314
399
  remaining_metadata = [a for a in args[1:] if not isinstance(a, SQLModelFieldInfo)]
315
400
  if remaining_metadata:
316
- new_ann = typing.Annotated[tuple([base_type] + remaining_metadata)]
401
+ new_inner: typing.Any = typing.Annotated[tuple([base_type] + remaining_metadata)]
317
402
  else:
318
- new_ann = base_type
319
- annotations[field_name] = new_ann
403
+ new_inner = base_type
404
+
405
+ if union_args is not None:
406
+ # Rebuild Union: replace the inner Annotated with the stripped version, keeping
407
+ # the other Union members (e.g. ``| None``) intact. Use PEP 604 ``|`` to accumulate
408
+ # so we don't trip the deprecated-typing.Union warning.
409
+ new_union_args = [
410
+ new_inner if get_origin(arg) is typing.Annotated else arg
411
+ for arg in union_args
412
+ ]
413
+ rebuilt: typing.Any = new_union_args[0]
414
+ for extra in new_union_args[1:]:
415
+ rebuilt = rebuilt | extra
416
+ annotations[field_name] = rebuilt
417
+ else:
418
+ annotations[field_name] = new_inner
320
419
 
321
420
 
322
421
  def _make_sti_fk_resolver(
@@ -495,7 +594,19 @@ class __DeclarativeMeta(SQLModelMetaclass):
495
594
  field_value = attrs.get(field_name, Undefined)
496
595
 
497
596
  if field_value is Undefined:
498
- attrs[field_name] = Field(sa_type=sa_type)
597
+ # No explicit ``= Field(...)`` assignment. Prefer recovering
598
+ # FieldInfo from inside Annotated[X, Field(default_factory=..., ...)]
599
+ # so user-supplied default_factory / max_length / constraints
600
+ # survive — clobbering with a fresh Field(sa_type=sa_type)
601
+ # would silently make the field required after multi-level
602
+ # inheritance.
603
+ annotated_fi = _find_field_info_in_annotated(field_type)
604
+ if annotated_fi is not None:
605
+ if getattr(annotated_fi, 'sa_type', Undefined) is Undefined:
606
+ setattr(annotated_fi, 'sa_type', sa_type)
607
+ attrs[field_name] = annotated_fi
608
+ else:
609
+ attrs[field_name] = Field(sa_type=sa_type)
499
610
  elif isinstance(field_value, FieldInfo):
500
611
  if getattr(field_value, 'sa_type', Undefined) is Undefined:
501
612
  setattr(field_value, 'sa_type', sa_type)
@@ -975,6 +1086,11 @@ class SQLModelBase(SQLModel, metaclass=__DeclarativeMeta):
975
1086
  prop['description'] = finfo.description
976
1087
  return json_schema
977
1088
 
1089
+ @classmethod
1090
+ def validate_list(cls, items: Sequence[Any]) -> list[Self]:
1091
+ """Batch-convert a sequence of ORM instances (or dicts) to this model type."""
1092
+ return [cls.model_validate(item, from_attributes=True) for item in items]
1093
+
978
1094
  @classmethod
979
1095
  def get_computed_field_names(cls) -> set[str]:
980
1096
  """Get the set of computed_field names for this model class."""
@@ -108,6 +108,9 @@ Text5K: TypeAlias = Annotated[str, Field(max_length=5000), _NO_NULL_BYTE]
108
108
  Text10K: TypeAlias = Annotated[str, Field(max_length=10000), _NO_NULL_BYTE]
109
109
  """10000-character text field"""
110
110
 
111
+ Text16K: TypeAlias = Annotated[str, Field(max_length=16000), _NO_NULL_BYTE]
112
+ """16000-character text field (long-form descriptions, tool docs)"""
113
+
111
114
  Text32K: TypeAlias = Annotated[str, Field(max_length=32000), _NO_NULL_BYTE]
112
115
  """32000-character text field"""
113
116
 
@@ -120,9 +123,29 @@ Text64K: TypeAlias = Annotated[str, Field(max_length=65536), _NO_NULL_BYTE]
120
123
  Text100K: TypeAlias = Annotated[str, Field(max_length=100000), _NO_NULL_BYTE]
121
124
  """100000-character text field"""
122
125
 
126
+ Text128K: TypeAlias = Annotated[str, Field(max_length=131072), _NO_NULL_BYTE]
127
+ """131072-character (128 * 1024) text field (large markdown documents etc.)"""
128
+
123
129
  Text1M: TypeAlias = Annotated[str, Field(max_length=1000000), _NO_NULL_BYTE]
124
130
  """1000000-character text field (tool call parameters, tool responses, etc.)"""
125
131
 
132
+ # NonEmptyStr* — same as Str* but also requires ``min_length=1``, rejecting empty
133
+ # ``""`` strings with a 422 ValidationError. Use for naming fields where the empty
134
+ # string is semantically invalid (e.g. UserFolder.name).
135
+ NonEmptyStr64: TypeAlias = Annotated[str, Field(min_length=1, max_length=64), _NO_NULL_BYTE]
136
+ """1-64 character non-empty string field"""
137
+
138
+ NonEmptyStr128: TypeAlias = Annotated[str, Field(min_length=1, max_length=128), _NO_NULL_BYTE]
139
+ """1-128 character non-empty string field"""
140
+
141
+ NonEmptyStr256: TypeAlias = Annotated[str, Field(min_length=1, max_length=256), _NO_NULL_BYTE]
142
+ """1-256 character non-empty string field"""
143
+
144
+ # Sha256Hex — exactly 64 lowercase hex characters, the canonical SHA-256 hex digest form.
145
+ # The strict regex also implicitly rejects NUL bytes, so no separate _NO_NULL_BYTE is needed.
146
+ Sha256Hex: TypeAlias = Annotated[str, StringConstraints(min_length=64, max_length=64, pattern=r'^[0-9a-f]{64}$')]
147
+ """64-char lowercase-hex SHA-256 digest (e.g. content hashes)"""
148
+
126
149
  # Numeric range constraints
127
150
  Port: TypeAlias = Annotated[int, Field(ge=1, le=65535)]
128
151
  """Port number (1-65535)"""
@@ -91,6 +91,7 @@ logger = logging.getLogger(__name__)
91
91
 
92
92
  from pydantic import ValidationError
93
93
  from sqlalchemy import ColumnElement, event, inspect as sa_inspect, select as sa_select
94
+ from sqlalchemy.exc import NoResultFound
94
95
  from sqlalchemy.orm import InstanceState, QueryableAttribute, Session as _SyncSession, make_transient_to_detached
95
96
  from sqlalchemy.orm.attributes import set_committed_value
96
97
  from sqlalchemy.orm.relationships import MANYTOONE # pyright: ignore[reportPrivateImportUsage]
@@ -1319,6 +1320,15 @@ class CachedTableBaseMixin(TableBaseMixin):
1319
1320
  if cached is not _LOAD_CACHE_MISS:
1320
1321
  if cls.on_cache_hit is not None:
1321
1322
  cls.on_cache_hit(cls.__name__)
1323
+ if cached is None and fetch_mode == 'one':
1324
+ # ``fetch_mode='one'`` type contract guarantees raise (not None);
1325
+ # when the cache hit is None we must raise, matching the SQL
1326
+ # path's ``result.one()`` behavior. Otherwise downstream
1327
+ # ``try/except NoResultFound`` callers (e.g. dep injection that
1328
+ # maps "missing" to 503) would silently see None and fail later.
1329
+ raise NoResultFound(
1330
+ f"No row was found when one was required: {cls.__name__}(id={id_value})"
1331
+ )
1322
1332
  return cached
1323
1333
  # Redis was actually queried and missed.
1324
1334
 
@@ -1394,18 +1404,25 @@ class CachedTableBaseMixin(TableBaseMixin):
1394
1404
  else:
1395
1405
  # Phase 2: merge into the session identity map to preserve
1396
1406
  # the same semantics as a DB query.
1397
- if result is not None:
1398
- if isinstance(result, list):
1399
- merged_list: list[Self] = []
1400
- for item in result:
1401
- make_transient_to_detached(item)
1402
- merged_list.append(await session.merge(item, load=False))
1403
- return merged_list
1404
- else:
1405
- make_transient_to_detached(result)
1406
- result = await session.merge(result, load=False)
1407
1407
  if cls.on_cache_hit is not None:
1408
1408
  cls.on_cache_hit(cls.__name__)
1409
+ if result is None:
1410
+ if fetch_mode == 'one':
1411
+ # ``fetch_mode='one'`` type contract guarantees raise (not None);
1412
+ # raise on cache hit to mirror the SQL path's ``result.one()`` behavior.
1413
+ raise NoResultFound(
1414
+ f"No row was found when one was required: {cls.__name__}"
1415
+ )
1416
+ return result
1417
+ if isinstance(result, list):
1418
+ merged_list: list[Self] = []
1419
+ for item in result:
1420
+ make_transient_to_detached(item)
1421
+ merged_list.append(await session.merge(item, load=False))
1422
+ return merged_list
1423
+ else:
1424
+ make_transient_to_detached(result)
1425
+ result = await session.merge(result, load=False)
1409
1426
  return result
1410
1427
 
1411
1428
  # Cache miss callback (only when Redis was actually queried, not skip_cache path)
@@ -1709,35 +1726,53 @@ class CachedTableBaseMixin(TableBaseMixin):
1709
1726
  # SA does not load children and persistent_to_deleted does not fire,
1710
1727
  # so we must query child IDs ourselves before DELETE and invalidate
1711
1728
  # their caches afterwards.
1729
+ #
1730
+ # The walk is BFS over the entire passive_deletes chain — a single
1731
+ # level is not enough. Example: A -[passive=True]-> B -[passive=True]-> C
1732
+ # all use DB CASCADE, SA never loads B or C, persistent_to_deleted
1733
+ # only fires for A. Stale rows of both B and C linger in Redis until
1734
+ # TTL. The BFS prefetches every cached level before issuing DELETE.
1712
1735
  passive_targets: dict[type[CachedTableBaseMixin], list[Any]] = {}
1713
- try:
1714
- mapper = sa_inspect(cls)
1715
- if mapper is None:
1716
- raise TypeError(f"sa_inspect({cls.__name__}) returned None")
1717
- for rel in mapper.relationships:
1718
- if not rel.cascade.delete or not rel.passive_deletes:
1719
- continue
1720
- target = rel.mapper.class_
1721
- if not (isinstance(target, type) and issubclass(target, CachedTableBaseMixin)):
1736
+ # Queue items: (current_cls, IDs from the previous level, or None for
1737
+ # full-model propagation when the upstream delete used a condition).
1738
+ passive_queue: list[tuple[type, list[Any] | None]] = [
1739
+ (cls, list(instance_ids) if instance_ids else None)
1740
+ ]
1741
+ while passive_queue:
1742
+ current_cls, current_ids = passive_queue.pop(0)
1743
+ try:
1744
+ current_mapper = sa_inspect(current_cls)
1745
+ if current_mapper is None:
1722
1746
  continue
1723
- if instance_ids:
1747
+ for rel in current_mapper.relationships:
1748
+ if not rel.cascade.delete or not rel.passive_deletes:
1749
+ continue
1750
+ target = rel.mapper.class_
1751
+ if not (isinstance(target, type) and issubclass(target, CachedTableBaseMixin)):
1752
+ continue
1753
+ if current_ids is None:
1754
+ # Condition delete or already-full propagation.
1755
+ if _FULL_MODEL_INVALIDATION not in passive_targets.get(target, []):
1756
+ passive_targets.setdefault(target, []).append(_FULL_MODEL_INVALIDATION)
1757
+ passive_queue.append((target, None))
1758
+ continue
1724
1759
  remote_cols = list(rel.remote_side)
1725
- if len(remote_cols) == 1:
1726
- target_mapper = sa_inspect(target)
1727
- if target_mapper is None:
1728
- continue
1729
- target_pk = target_mapper.primary_key[0]
1730
- stmt = sa_select(target_pk).where(remote_cols[0].in_(instance_ids))
1731
- rows = await session.execute(stmt)
1732
- child_ids = [row[0] for row in rows]
1733
- if child_ids:
1734
- passive_targets[target] = child_ids
1735
- else:
1736
- # Condition deletes cannot enumerate parent IDs; use the
1737
- # sentinel to request a model-level full invalidation.
1738
- passive_targets[target] = [_FULL_MODEL_INVALIDATION]
1739
- except Exception as e:
1740
- logger.warning(f"passive_deletes pre-query failed ({cls.__name__}): {e}")
1760
+ if len(remote_cols) != 1:
1761
+ # Composite FK is not supported (matches the original
1762
+ # single-level behaviour).
1763
+ continue
1764
+ target_mapper = sa_inspect(target)
1765
+ if target_mapper is None:
1766
+ continue
1767
+ target_pk = target_mapper.primary_key[0]
1768
+ stmt = sa_select(target_pk).where(remote_cols[0].in_(current_ids))
1769
+ rows = await session.execute(stmt)
1770
+ child_ids = [row[0] for row in rows]
1771
+ if child_ids:
1772
+ passive_targets.setdefault(target, []).extend(child_ids)
1773
+ passive_queue.append((target, child_ids))
1774
+ except Exception as e:
1775
+ logger.warning(f"passive_deletes pre-query failed ({current_cls.__name__}): {e}")
1741
1776
 
1742
1777
  # Clear any leftover cascade data from a previous run (defensive;
1743
1778
  # normal flows never leave residue).
@@ -453,6 +453,22 @@ class AutoPolymorphicIdentityMixin:
453
453
  # other subclasses' rows won't have values for these columns.
454
454
  # Pydantic-level constraints still apply when creating specific subclasses.
455
455
  column.nullable = True
456
+
457
+ # Clear Python-side and server-side defaults on the shared column.
458
+ # Otherwise, a Pydantic field default (e.g. ``some_field: int = 5``)
459
+ # gets propagated into Column.default by ``get_column_from_field()``.
460
+ # When sibling subclasses that do NOT declare this field are inserted,
461
+ # the attribute is absent from their model_fields and from the
462
+ # instance's ``__dict__``; the ORM falls back to Column.default and
463
+ # writes the declaring subclass's default into the sibling row,
464
+ # silently polluting unrelated rows across the STI table.
465
+ # The declaring subclass itself is unaffected: Pydantic populates the
466
+ # instance attribute at ``__init__`` time, and the ORM reads the
467
+ # value directly from the instance on flush without ever consulting
468
+ # Column.default.
469
+ column.default = None
470
+ column.server_default = None
471
+
456
472
  parent_table.append_column(column)
457
473
  except Exception as e:
458
474
  logger.warning(f"Failed to create column {field_name} for {cls.__name__}: {e}")