SQLAlchemy 2.1.7__py3-none-any.whl → 2.1.9__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.
Files changed (40) hide show
  1. sqlalchemy/__init__.py +1 -1
  2. sqlalchemy/dialects/mssql/base.py +8 -0
  3. sqlalchemy/dialects/oracle/cx_oracle.py +1 -1
  4. sqlalchemy/dialects/postgresql/asyncpg.py +15 -0
  5. sqlalchemy/dialects/postgresql/base.py +4 -1
  6. sqlalchemy/dialects/postgresql/hstore.py +1 -0
  7. sqlalchemy/engine/_row_cy.py +12 -0
  8. sqlalchemy/engine/interfaces.py +1 -1
  9. sqlalchemy/engine/result.py +4 -1
  10. sqlalchemy/engine/row.py +1 -1
  11. sqlalchemy/engine/url.py +28 -13
  12. sqlalchemy/ext/asyncio/result.py +2 -1
  13. sqlalchemy/ext/asyncio/scoping.py +1 -1
  14. sqlalchemy/ext/asyncio/session.py +1 -1
  15. sqlalchemy/ext/declarative/extensions.py +3 -2
  16. sqlalchemy/ext/hybrid.py +2 -2
  17. sqlalchemy/orm/context.py +67 -1
  18. sqlalchemy/orm/dependency.py +3 -0
  19. sqlalchemy/orm/events.py +4 -8
  20. sqlalchemy/orm/interfaces.py +11 -1
  21. sqlalchemy/orm/loading.py +24 -5
  22. sqlalchemy/orm/relationships.py +16 -0
  23. sqlalchemy/orm/strategies.py +51 -69
  24. sqlalchemy/orm/util.py +25 -0
  25. sqlalchemy/pool/base.py +21 -6
  26. sqlalchemy/sql/_annotated_cols.py +1 -1
  27. sqlalchemy/sql/elements.py +16 -8
  28. sqlalchemy/sql/operators.py +28 -21
  29. sqlalchemy/sql/selectable.py +86 -18
  30. sqlalchemy/sql/sqltypes.py +1 -1
  31. sqlalchemy/sql/util.py +83 -0
  32. sqlalchemy/util/__init__.py +3 -0
  33. sqlalchemy/util/concurrency.py +4 -0
  34. sqlalchemy/util/langhelpers.py +1 -1
  35. {sqlalchemy-2.1.7.dist-info → sqlalchemy-2.1.9.dist-info}/METADATA +1 -1
  36. {sqlalchemy-2.1.7.dist-info → sqlalchemy-2.1.9.dist-info}/RECORD +40 -40
  37. {sqlalchemy-2.1.7.dist-info → sqlalchemy-2.1.9.dist-info}/WHEEL +0 -0
  38. {sqlalchemy-2.1.7.dist-info → sqlalchemy-2.1.9.dist-info}/licenses/AUTHORS +0 -0
  39. {sqlalchemy-2.1.7.dist-info → sqlalchemy-2.1.9.dist-info}/licenses/LICENSE +0 -0
  40. {sqlalchemy-2.1.7.dist-info → sqlalchemy-2.1.9.dist-info}/top_level.txt +0 -0
sqlalchemy/__init__.py CHANGED
@@ -285,7 +285,7 @@ from .types import Uuid as Uuid
285
285
  from .types import VARBINARY as VARBINARY
286
286
  from .types import VARCHAR as VARCHAR
287
287
 
288
- __version__ = "2.1.7"
288
+ __version__ = "2.1.9"
289
289
 
290
290
 
291
291
  def __go(lcls: Any) -> None:
@@ -4267,6 +4267,14 @@ index_info AS (
4267
4267
  == sys_key_constraints.c.unique_index_id,
4268
4268
  ),
4269
4269
  )
4270
+ # a table with a primary key that another session is creating
4271
+ # within a transaction has its key constraint rows locked until
4272
+ # that transaction ends; the plan for this query can read those
4273
+ # rows even though the filter discards them, so skip them
4274
+ # rather than block on them. See #13789.
4275
+ .with_hint(
4276
+ sys_key_constraints, "WITH (READPAST)", dialect_name="mssql"
4277
+ )
4270
4278
  .where(
4271
4279
  sys_key_constraints.c.type == "PK",
4272
4280
  ischema.sys_schemas.c.name == sql.bindparam("owner"),
@@ -1485,7 +1485,7 @@ class OracleDialect_cx_oracle(OracleDialect):
1485
1485
  connection level.
1486
1486
 
1487
1487
  note that when using a Compiled statement that has types (e.g.
1488
- TypeEngine), we set up a per-cursor handler instead which supercedes
1488
+ TypeEngine), we set up a per-cursor handler instead which supersedes
1489
1489
  this one, using Oracle-specific TypeEngine handlers delivered by the
1490
1490
  _cx_oracle_outputtypehandler() method of each one.
1491
1491
 
@@ -174,6 +174,21 @@ client using this setting passed to :func:`_asyncio.create_async_engine`::
174
174
 
175
175
  https://github.com/MagicStack/asyncpg/issues/727
176
176
 
177
+ DBAPI Error Messages
178
+ ---------------------
179
+
180
+ The asyncpg error message are wrapped by in :class:`.EmulatedDBAPIException`
181
+ object providing a more consistent experience for the async drivers.
182
+ A side effect of this change is that the textual representation of
183
+ the error may be different than it was in previous sqlalchemy versions,
184
+ and the ``DETAIL`` line may be missing.
185
+ The original asyncpg exception can be accessed using the
186
+ :attr:`.DBAPIError.driver_exception` attribute.
187
+
188
+ .. versionchanged:: 2.1.0
189
+
190
+ The exceptions are wrapped in :class:`.EmulatedDBAPIException` objects.
191
+
177
192
  """ # noqa
178
193
 
179
194
  from __future__ import annotations
@@ -1653,7 +1653,7 @@ defined, so other SQL dialects may behave differently than PostgreSQL.
1653
1653
  The ``NULLS NOT DISTINCT`` clause can be used to change this behavior, treating
1654
1654
  null values as equal and preventing unintended duplicate rows. The opposite
1655
1655
  ``NULLS DISTINCT`` clause can also be used to make PostgreSQL's default behavior
1656
- explict.
1656
+ explicit.
1657
1657
 
1658
1658
  The ``postgresql_nulls_not_distinct`` parameter can be set to ``True`` to
1659
1659
  add the ``NULLS NOT DISTINCT`` clause, or ``False`` to add ``NULLS DISTINCT``.
@@ -1959,6 +1959,7 @@ from .types import REGCLASS as REGCLASS
1959
1959
  from .types import REGCONFIG as REGCONFIG # noqa: F401
1960
1960
  from .types import TIME as TIME
1961
1961
  from .types import TIMESTAMP as TIMESTAMP
1962
+ from .types import TSQUERY as TSQUERY
1962
1963
  from .types import TSVECTOR as TSVECTOR
1963
1964
  from ... import exc
1964
1965
  from ... import schema
@@ -2168,6 +2169,8 @@ ischema_names = {
2168
2169
  "boolean": BOOLEAN,
2169
2170
  "interval": INTERVAL,
2170
2171
  "tsvector": TSVECTOR,
2172
+ "tsquery": TSQUERY,
2173
+ "regconfig": REGCONFIG,
2171
2174
  }
2172
2175
 
2173
2176
 
@@ -115,6 +115,7 @@ class HSTORE(
115
115
 
116
116
  operator_classes = (
117
117
  OperatorClass.BASE
118
+ | OperatorClass.EQUALITY
118
119
  | OperatorClass.CONTAINS
119
120
  | OperatorClass.INDEXABLE
120
121
  | OperatorClass.CONCATENABLE
@@ -19,6 +19,7 @@ from typing import Sequence
19
19
  from typing import Tuple
20
20
  from typing import Type
21
21
  from typing import TYPE_CHECKING
22
+ from typing import TypeVar
22
23
 
23
24
  if TYPE_CHECKING:
24
25
  from .result import _KeyType
@@ -43,6 +44,8 @@ def _is_compiled() -> bool:
43
44
 
44
45
  # END GENERATED CYTHON IMPORT
45
46
 
47
+ _BR = TypeVar("_BR", bound="BaseRow")
48
+
46
49
 
47
50
  @cython.cclass
48
51
  class BaseRow:
@@ -92,6 +95,15 @@ class BaseRow:
92
95
  object.__setattr__(self, "_key_to_index", key_to_index)
93
96
  object.__setattr__(self, "_data", data)
94
97
 
98
+ def _as_row_class(self, cls: Type[_BR]) -> _BR:
99
+ """Return a new object of the given :class:`.BaseRow` subclass
100
+ that shares this row's data, without re-applying processors.
101
+
102
+ """
103
+ new: BaseRow = cls.__new__(cls)
104
+ new._set_attrs(self._parent, self._key_to_index, self._data)
105
+ return new # type: ignore[return-value]
106
+
95
107
  def __reduce__(self) -> Tuple[Any, Any]:
96
108
  return (
97
109
  rowproxy_reconstructor,
@@ -1008,7 +1008,7 @@ class Dialect(EventTarget):
1008
1008
  inject this handler at the connection/cursor level, rather than
1009
1009
  having JSON data returned as a string to be handled by the type
1010
1010
 
1011
- ..versionadded:: 2.1
1011
+ .. versionadded:: 2.1
1012
1012
 
1013
1013
  """
1014
1014
 
@@ -1586,6 +1586,9 @@ class TupleResult(FilterResult[_R], util.TypingOnly):
1586
1586
  ...
1587
1587
 
1588
1588
 
1589
+ _row_to_mapping = operator.methodcaller("_as_row_class", RowMapping)
1590
+
1591
+
1589
1592
  class MappingResult(_WithKeys, FilterResult[RowMapping]):
1590
1593
  """A wrapper for a :class:`_engine.Result` that returns dictionary values
1591
1594
  rather than :class:`_engine.Row` values.
@@ -1599,7 +1602,7 @@ class MappingResult(_WithKeys, FilterResult[RowMapping]):
1599
1602
 
1600
1603
  _generate_rows = True
1601
1604
 
1602
- _post_creational_filter = operator.attrgetter("_mapping")
1605
+ _post_creational_filter = _row_to_mapping
1603
1606
 
1604
1607
  def __init__(self, result: Result[Unpack[TupleAny]]):
1605
1608
  self._real_result = result
sqlalchemy/engine/row.py CHANGED
@@ -184,7 +184,7 @@ class Row(BaseRow, _RowBase[Unpack[_Ts]], Generic[Unpack[_Ts]]): # type: ignore
184
184
  .. versionadded:: 1.4
185
185
 
186
186
  """
187
- return RowMapping(self._parent, None, self._key_to_index, self._data)
187
+ return self._as_row_class(RowMapping)
188
188
 
189
189
  def _filter_on_values(
190
190
  self, processor: Optional[_ProcessorsType]
sqlalchemy/engine/url.py CHANGED
@@ -414,7 +414,7 @@ class URL(NamedTuple):
414
414
 
415
415
  def update_query_pairs(
416
416
  self,
417
- key_value_pairs: Iterable[Tuple[str, Union[str, List[str]]]],
417
+ key_value_pairs: Iterable[Tuple[str, Union[str, Sequence[str]]]],
418
418
  append: bool = False,
419
419
  ) -> URL:
420
420
  """Return a new :class:`_engine.URL` object with the
@@ -435,8 +435,24 @@ class URL(NamedTuple):
435
435
  >>> str(url)
436
436
  'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
437
437
 
438
- :param key_value_pairs: A sequence of tuples containing two strings
439
- each.
438
+ A value may also be given as a sequence of strings, which is
439
+ equivalent to passing the same key once for each string; the
440
+ above example may also be expressed as::
441
+
442
+ >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname")
443
+ >>> url = url.update_query_pairs(
444
+ ... [
445
+ ... ("alt_host", ["host1", "host2"]),
446
+ ... ("ssl_cipher", "/path/to/crt"),
447
+ ... ]
448
+ ... )
449
+ >>> str(url)
450
+ 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
451
+
452
+ :param key_value_pairs: A sequence of tuples, each containing a
453
+ string key and a value that is either a string or a sequence of
454
+ strings. A key may appear more than once, in which case all of
455
+ its values are combined in the order given.
440
456
 
441
457
  :param append: if True, parameters in the existing query string will
442
458
  not be removed; new parameters will be in addition to those present.
@@ -445,6 +461,9 @@ class URL(NamedTuple):
445
461
 
446
462
  .. versionadded:: 1.4
447
463
 
464
+ .. versionchanged:: 2.0.58, 2.1.9 A value may be given as a sequence
465
+ of strings, including for a key that appears more than once.
466
+
448
467
  .. seealso::
449
468
 
450
469
  :attr:`_engine.URL.query`
@@ -456,12 +475,13 @@ class URL(NamedTuple):
456
475
  """ # noqa: E501
457
476
 
458
477
  existing_query = self.query
459
- new_keys: Dict[str, Union[str, List[str]]] = {}
478
+ new_keys: Dict[str, Union[str, Sequence[str]]] = {}
460
479
 
461
480
  for key, value in key_value_pairs:
462
481
  if key in new_keys:
463
- new_keys[key] = util.to_list(new_keys[key])
464
- cast("List[str]", new_keys[key]).append(cast(str, value))
482
+ current_as_list = util.to_list(new_keys[key])
483
+ current_as_list.extend(util.to_list(value))
484
+ new_keys[key] = current_as_list
465
485
  else:
466
486
  new_keys[key] = (
467
487
  list(value) if isinstance(value, (list, tuple)) else value
@@ -487,17 +507,12 @@ class URL(NamedTuple):
487
507
  }
488
508
  )
489
509
  else:
490
- new_query = self.query.union(
491
- {
492
- k: tuple(v) if isinstance(v, list) else v
493
- for k, v in new_keys.items()
494
- }
495
- )
510
+ new_query = {**self.query, **new_keys}
496
511
  return self.set(query=new_query)
497
512
 
498
513
  def update_query_dict(
499
514
  self,
500
- query_parameters: Mapping[str, Union[str, List[str]]],
515
+ query_parameters: Mapping[str, Union[str, Sequence[str]]],
501
516
  append: bool = False,
502
517
  ) -> URL:
503
518
  """Return a new :class:`_engine.URL` object with the
@@ -24,6 +24,7 @@ from ...engine import Result
24
24
  from ...engine._result_cy import _RowData
25
25
  from ...engine.result import _NO_ROW
26
26
  from ...engine.result import _R
27
+ from ...engine.result import _row_to_mapping
27
28
  from ...engine.result import _WithKeys
28
29
  from ...engine.result import FilterResult
29
30
  from ...engine.result import FrozenResult
@@ -672,7 +673,7 @@ class AsyncMappingResult(_WithKeys, AsyncCommon[RowMapping]):
672
673
 
673
674
  _generate_rows = True
674
675
 
675
- _post_creational_filter = operator.attrgetter("_mapping")
676
+ _post_creational_filter = _row_to_mapping
676
677
 
677
678
  def __init__(self, result: AsyncResult[Unpack[TupleAny]]):
678
679
  # rows are fetched from the sync Result; metadata and unique state
@@ -1289,7 +1289,7 @@ class async_scoped_session(Generic[_AS]):
1289
1289
 
1290
1290
  Raises :class:`_exc.NoResultFound` if the query selects no rows.
1291
1291
 
1292
- ..versionadded: 2.0.22
1292
+ .. versionadded:: 2.0.22
1293
1293
 
1294
1294
  .. seealso::
1295
1295
 
@@ -832,7 +832,7 @@ class AsyncSession(ReversibleProxy[Session]):
832
832
 
833
833
  Raises :class:`_exc.NoResultFound` if the query selects no rows.
834
834
 
835
- ..versionadded: 2.0.22
835
+ .. versionadded:: 2.0.22
836
836
 
837
837
  .. seealso::
838
838
 
@@ -441,8 +441,9 @@ class DeferredReflection:
441
441
  :param bind: :class:`_engine.Engine` or :class:`_engine.Connection`
442
442
  instance
443
443
 
444
- ..versionchanged:: 2.0.16 a :class:`_engine.Connection` is also
445
- accepted.
444
+ .. versionchanged::
445
+
446
+ 2.0.16 a :class:`_engine.Connection` is also accepted.
446
447
 
447
448
  :param \**reflect_kw: additional keyword arguments passed to
448
449
  :meth:`_schema.MetaData.reflect`, such as
sqlalchemy/ext/hybrid.py CHANGED
@@ -1000,8 +1000,8 @@ example of ``Point`` and ``Vertex`` from that section using hybrids, where
1000
1000
 
1001
1001
  Above, the ``operate()`` method is where the most "hybrid" behavior takes
1002
1002
  place, making use of ``op()`` (the Python operator function in use) along
1003
- with the the bitwise ``&`` operator provides us with the SQL AND operator
1004
- in a SQL context, and boolean "and" in a Python boolean context.
1003
+ with the bitwise ``&`` operator provides us with the SQL AND operator in a SQL
1004
+ context, and boolean "and" in a Python boolean context.
1005
1005
 
1006
1006
  Following from there, the owning ``Vertex`` class now uses hybrids to
1007
1007
  represent ``start`` and ``end``::
sqlalchemy/orm/context.py CHANGED
@@ -62,6 +62,7 @@ from ..sql.base import ExecutableStatement
62
62
  from ..sql.base import Generative
63
63
  from ..sql.base import Options
64
64
  from ..sql.dml import UpdateBase
65
+ from ..sql.elements import ColumnClause
65
66
  from ..sql.elements import GroupedElement
66
67
  from ..sql.elements import TextClause
67
68
  from ..sql.selectable import CompoundSelectState
@@ -89,6 +90,7 @@ if TYPE_CHECKING:
89
90
  from ..engine import Result
90
91
  from ..engine.interfaces import _CoreSingleExecuteParams
91
92
  from ..sql._typing import _ColumnsClauseArgument
93
+ from ..sql.base import ExecutableOption
92
94
  from ..sql.compiler import SQLCompiler
93
95
  from ..sql.dml import _DMLTableElement
94
96
  from ..sql.elements import ColumnElement
@@ -230,6 +232,39 @@ class QueryContext:
230
232
  def _get_top_level_context(self) -> QueryContext:
231
233
  return self.top_level_context or self
232
234
 
235
+ def _loader_strategy_options(self) -> Tuple[ExecutableOption, ...]:
236
+ """Return the options to be used by a loader strategy that emits
237
+ a new statement on behalf of this query, such as a selectin
238
+ loader or a selectin polymorphic loader.
239
+
240
+ The loader strategy is given paths and entities in terms of the
241
+ cached statement, i.e. ``compile_state.select_statement``, which
242
+ may not be the statement passed by the user. While the two are of
243
+ identical structure, entities like :class:`.AliasedInsp` from
244
+ :func:`_orm.aliased` or :func:`_orm.with_polymorphic` will usually
245
+ be a different object identity in each, and will not match up with
246
+ paths and loader lookups. So options with paths need to come from
247
+ the cached statement, while other options like
248
+ :func:`_orm.with_loader_criteria` need the latest state from the
249
+ uncached statement; as of #8399 each option decides this for itself
250
+ given both versions of itself.
251
+
252
+ """
253
+ orig_query = self.compile_state.select_statement
254
+
255
+ if orig_query is self.user_passed_query:
256
+ return orig_query._with_options
257
+
258
+ return tuple(
259
+ orig_opt._adapt_cached_option_to_uncached_option(
260
+ self, uncached_opt
261
+ )
262
+ for orig_opt, uncached_opt in zip(
263
+ orig_query._with_options,
264
+ self.user_passed_query._with_options,
265
+ )
266
+ )
267
+
233
268
 
234
269
  _orm_load_exec_options = util.immutabledict(
235
270
  {"_result_disable_adapt_to_context": True}
@@ -1740,12 +1775,43 @@ class _ORMSelectCompileState(_ORMCompileState, SelectState):
1740
1775
  **self._select_args,
1741
1776
  )
1742
1777
 
1778
+ # tables that are directly in the FROM list of the inner statement,
1779
+ # as opposed to being present only by way of an alias
1780
+ inner_tables = {
1781
+ elem
1782
+ for from_ in inner.get_final_froms()
1783
+ for elem in sql_util.surface_selectables(from_)
1784
+ if elem._is_table
1785
+ }
1786
+
1787
+ def _exclude_fn(elem):
1788
+ # a column of an un-aliased table is at the root of the lineage
1789
+ # of every column derived from that table, so
1790
+ # corresponding_column() can match it to a column of any alias
1791
+ # of that table; a column of an alias only matches columns
1792
+ # derived from that same alias. so skip adapting a column
1793
+ # that's attached to an un-aliased table when that table isn't
1794
+ # present as a plain table in the inner statement's FROM list,
1795
+ # either directly or within a join. the inner statement may
1796
+ # still have a column derived from that table by way of an
1797
+ # alias, such as that of an aliased() joined inheritance
1798
+ # subclass, but that alias refers to different rows, #13798
1799
+ return (
1800
+ isinstance(elem, ColumnClause)
1801
+ and elem.table is not None
1802
+ and elem.table._is_table
1803
+ and elem.table not in inner_tables
1804
+ )
1805
+
1743
1806
  inner = inner.alias()
1744
1807
 
1745
1808
  equivs = self._all_equivs()
1746
1809
 
1747
1810
  self.compound_eager_adapter = ORMStatementAdapter(
1748
- _TraceAdaptRole.COMPOUND_EAGER_STATEMENT, inner, equivalents=equivs
1811
+ _TraceAdaptRole.COMPOUND_EAGER_STATEMENT,
1812
+ inner,
1813
+ equivalents=equivs,
1814
+ exclude_fn=_exclude_fn,
1749
1815
  )
1750
1816
 
1751
1817
  statement = future.select(
@@ -357,6 +357,9 @@ class _OneToManyDP(_DependencyProcessor):
357
357
  (child_saves, after_save),
358
358
  (parent_saves, after_save),
359
359
  (after_save, child_post_updates),
360
+ (child_saves, before_delete),
361
+ (before_delete, child_post_updates),
362
+ (child_post_updates, parent_deletes),
360
363
  (before_delete, child_pre_updates),
361
364
  (child_pre_updates, parent_deletes),
362
365
  (child_pre_updates, child_deletes),
sqlalchemy/orm/events.py CHANGED
@@ -2574,8 +2574,7 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
2574
2574
  True, this will be the key used in the operation, such as
2575
2575
  ``collection[some_key_or_index] = value``.
2576
2576
  The parameter is not passed
2577
- to the event at all if the the
2578
- :paramref:`.AttributeEvents.include_key`
2577
+ to the event at all if the :paramref:`.AttributeEvents.include_key`
2579
2578
  was not used to set up the event; this is to allow backwards
2580
2579
  compatibility with existing event handlers that don't include the
2581
2580
  ``key`` parameter.
@@ -2629,8 +2628,7 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
2629
2628
  True, this will be the key used in the operation, such as
2630
2629
  ``collection[some_key_or_index] = value``.
2631
2630
  The parameter is not passed
2632
- to the event at all if the the
2633
- :paramref:`.AttributeEvents.include_key`
2631
+ to the event at all if the :paramref:`.AttributeEvents.include_key`
2634
2632
  was not used to set up the event; this is to allow backwards
2635
2633
  compatibility with existing event handlers that don't include the
2636
2634
  ``key`` parameter.
@@ -2697,8 +2695,7 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
2697
2695
  :paramref:`.AttributeEvents.include_key` parameter set to
2698
2696
  True, this will be the sequence of keys used in the operation,
2699
2697
  typically only for a dictionary update. The parameter is not passed
2700
- to the event at all if the the
2701
- :paramref:`.AttributeEvents.include_key`
2698
+ to the event at all if the :paramref:`.AttributeEvents.include_key`
2702
2699
  was not used to set up the event; this is to allow backwards
2703
2700
  compatibility with existing event handlers that don't include the
2704
2701
  ``key`` parameter.
@@ -2736,8 +2733,7 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
2736
2733
  :paramref:`.AttributeEvents.include_key` parameter set to
2737
2734
  True, this will be the key used in the operation, such as
2738
2735
  ``del collection[some_key_or_index]``. The parameter is not passed
2739
- to the event at all if the the
2740
- :paramref:`.AttributeEvents.include_key`
2736
+ to the event at all if the :paramref:`.AttributeEvents.include_key`
2741
2737
  was not used to set up the event; this is to allow backwards
2742
2738
  compatibility with existing event handlers that don't include the
2743
2739
  ``key`` parameter.
@@ -71,6 +71,7 @@ from ..sql.base import ExecutableOption
71
71
  from ..sql.cache_key import HasCacheKey
72
72
  from ..sql.operators import ColumnOperators
73
73
  from ..sql.schema import Column
74
+ from ..sql.schema import DefaultGenerator
74
75
  from ..sql.type_api import TypeEngine
75
76
  from ..util import warn_deprecated
76
77
  from ..util.typing import RODescriptorReference
@@ -418,7 +419,16 @@ class _DataclassDefaultsDontSet(_DCAttributeOptions):
418
419
  self._attribute_options.dataclasses_default_factory
419
420
  )
420
421
 
421
- if dataclasses_default is not _NoArg.NO_ARG and not callable(
422
+ if isinstance(dataclasses_default, DefaultGenerator):
423
+ # a ColumnDefault or Sequence passed as default, including the
424
+ # default established by orm_insert_sentinel(), applies to the
425
+ # Column only and is not a Python value for the attribute,
426
+ # #13788
427
+ self._default_scalar_value = None
428
+ return self._attribute_options._replace(
429
+ dataclasses_default=DONT_SET,
430
+ )
431
+ elif dataclasses_default is not _NoArg.NO_ARG and not callable(
422
432
  dataclasses_default
423
433
  ):
424
434
  self._default_scalar_value = (
sqlalchemy/orm/loading.py CHANGED
@@ -40,6 +40,8 @@ from .context import _ORMCompileState
40
40
  from .context import FromStatement
41
41
  from .context import QueryContext
42
42
  from .strategies import _SelectInLoader
43
+ from .strategy_options import Load
44
+ from .util import _entity_corresponds_to
43
45
  from .util import _none_set
44
46
  from .util import state_str
45
47
  from .. import exc as sa_exc
@@ -1297,17 +1299,34 @@ def _load_subclass_via_in(
1297
1299
  if not states:
1298
1300
  return
1299
1301
 
1300
- orig_query = context.query
1301
-
1302
1302
  if path.parent:
1303
1303
  enable_opt_lcl = enable_opt._prepend_path(path)
1304
1304
  disable_opt_lcl = disable_opt._prepend_path(path)
1305
1305
  else:
1306
1306
  enable_opt_lcl = enable_opt
1307
1307
  disable_opt_lcl = disable_opt
1308
- options = (
1309
- (enable_opt_lcl,) + orig_query._with_options + (disable_opt_lcl,)
1310
- )
1308
+
1309
+ # options need to be in terms of the cached statement in order
1310
+ # to line up with "path"; see #13777
1311
+ query_options = context._loader_strategy_options()
1312
+
1313
+ if not path.parent:
1314
+ # for a top level entity, there's no current path to select
1315
+ # among the options of the parent query, which are processed
1316
+ # against the root entity of our query as is. leave out
1317
+ # those against some other entity, such as an aliased() or
1318
+ # with_polymorphic() of the base or another entity in the
1319
+ # statement; these would raise for not linking to our root
1320
+ # entity, and were applied by the parent query already.
1321
+ # see #13780
1322
+ query_options = tuple(
1323
+ opt
1324
+ for opt in query_options
1325
+ if not isinstance(opt, Load)
1326
+ or _entity_corresponds_to(entity, opt.path[0])
1327
+ )
1328
+
1329
+ options = (enable_opt_lcl,) + query_options + (disable_opt_lcl,)
1311
1330
 
1312
1331
  q2 = q.options(*options)
1313
1332
 
@@ -88,6 +88,7 @@ from ..sql.elements import ColumnClause
88
88
  from ..sql.elements import ColumnElement
89
89
  from ..sql.util import _deep_annotate
90
90
  from ..sql.util import _deep_deannotate
91
+ from ..sql.util import _lateral_correlated_froms
91
92
  from ..sql.util import _shallow_annotate
92
93
  from ..sql.util import adapt_criterion_to_null
93
94
  from ..sql.util import ClauseAdapter
@@ -2274,6 +2275,21 @@ class RelationshipProperty(
2274
2275
  def _is_self_referential(self) -> bool:
2275
2276
  return self.mapper.common_parent(self.parent)
2276
2277
 
2278
+ @util.memoized_property
2279
+ def _target_correlates_to_parent(self) -> bool:
2280
+ """Return True if the target selectable, such as a LATERAL
2281
+ subquery, correlates to the parent's table.
2282
+
2283
+ Such a target can only be loaded in a query where the parent's
2284
+ table, or an alias of it, is present in the FROM clause.
2285
+
2286
+ """
2287
+ return bool(
2288
+ _lateral_correlated_froms(
2289
+ self.entity.selectable, self.parent.selectable
2290
+ )
2291
+ )
2292
+
2277
2293
  def _create_joins(
2278
2294
  self,
2279
2295
  source_polymorphic: bool = False,