interfaces.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. # orm/interfaces.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """
  8. Contains various base classes used throughout the ORM.
  9. Defines some key base classes prominent within the internals.
  10. This module and the classes within are mostly private, though some attributes
  11. are exposed when inspecting mappings.
  12. """
  13. from __future__ import annotations
  14. import collections
  15. import dataclasses
  16. import typing
  17. from typing import Any
  18. from typing import Callable
  19. from typing import cast
  20. from typing import ClassVar
  21. from typing import Dict
  22. from typing import Generic
  23. from typing import Iterator
  24. from typing import List
  25. from typing import NamedTuple
  26. from typing import NoReturn
  27. from typing import Optional
  28. from typing import Sequence
  29. from typing import Set
  30. from typing import Tuple
  31. from typing import Type
  32. from typing import TYPE_CHECKING
  33. from typing import TypeVar
  34. from typing import Union
  35. from . import exc as orm_exc
  36. from . import path_registry
  37. from .base import _MappedAttribute as _MappedAttribute
  38. from .base import EXT_CONTINUE as EXT_CONTINUE # noqa: F401
  39. from .base import EXT_SKIP as EXT_SKIP # noqa: F401
  40. from .base import EXT_STOP as EXT_STOP # noqa: F401
  41. from .base import InspectionAttr as InspectionAttr # noqa: F401
  42. from .base import InspectionAttrInfo as InspectionAttrInfo
  43. from .base import MANYTOMANY as MANYTOMANY # noqa: F401
  44. from .base import MANYTOONE as MANYTOONE # noqa: F401
  45. from .base import NO_KEY as NO_KEY # noqa: F401
  46. from .base import NO_VALUE as NO_VALUE # noqa: F401
  47. from .base import NotExtension as NotExtension # noqa: F401
  48. from .base import ONETOMANY as ONETOMANY # noqa: F401
  49. from .base import RelationshipDirection as RelationshipDirection # noqa: F401
  50. from .base import SQLORMOperations
  51. from .. import ColumnElement
  52. from .. import exc as sa_exc
  53. from .. import inspection
  54. from .. import util
  55. from ..sql import operators
  56. from ..sql import roles
  57. from ..sql import visitors
  58. from ..sql.base import _NoArg
  59. from ..sql.base import ExecutableOption
  60. from ..sql.cache_key import HasCacheKey
  61. from ..sql.operators import ColumnOperators
  62. from ..sql.schema import Column
  63. from ..sql.type_api import TypeEngine
  64. from ..util import warn_deprecated
  65. from ..util.typing import RODescriptorReference
  66. from ..util.typing import TypedDict
  67. if typing.TYPE_CHECKING:
  68. from ._typing import _EntityType
  69. from ._typing import _IdentityKeyType
  70. from ._typing import _InstanceDict
  71. from ._typing import _InternalEntityType
  72. from ._typing import _ORMAdapterProto
  73. from .attributes import InstrumentedAttribute
  74. from .base import Mapped
  75. from .context import _MapperEntity
  76. from .context import ORMCompileState
  77. from .context import QueryContext
  78. from .decl_api import RegistryType
  79. from .decl_base import _ClassScanMapperConfig
  80. from .loading import _PopulatorDict
  81. from .mapper import Mapper
  82. from .path_registry import AbstractEntityRegistry
  83. from .query import Query
  84. from .session import Session
  85. from .state import InstanceState
  86. from .strategy_options import _LoadElement
  87. from .util import AliasedInsp
  88. from .util import ORMAdapter
  89. from ..engine.result import Result
  90. from ..sql._typing import _ColumnExpressionArgument
  91. from ..sql._typing import _ColumnsClauseArgument
  92. from ..sql._typing import _DMLColumnArgument
  93. from ..sql._typing import _InfoType
  94. from ..sql.operators import OperatorType
  95. from ..sql.visitors import _TraverseInternalsType
  96. from ..util.typing import _AnnotationScanType
  97. _StrategyKey = Tuple[Any, ...]
  98. _T = TypeVar("_T", bound=Any)
  99. _T_co = TypeVar("_T_co", bound=Any, covariant=True)
  100. _TLS = TypeVar("_TLS", bound="Type[LoaderStrategy]")
  101. class ORMStatementRole(roles.StatementRole):
  102. __slots__ = ()
  103. _role_name = (
  104. "Executable SQL or text() construct, including ORM aware objects"
  105. )
  106. class ORMColumnsClauseRole(
  107. roles.ColumnsClauseRole, roles.TypedColumnsClauseRole[_T]
  108. ):
  109. __slots__ = ()
  110. _role_name = "ORM mapped entity, aliased entity, or Column expression"
  111. class ORMEntityColumnsClauseRole(ORMColumnsClauseRole[_T]):
  112. __slots__ = ()
  113. _role_name = "ORM mapped or aliased entity"
  114. class ORMFromClauseRole(roles.StrictFromClauseRole):
  115. __slots__ = ()
  116. _role_name = "ORM mapped entity, aliased entity, or FROM expression"
  117. class ORMColumnDescription(TypedDict):
  118. name: str
  119. # TODO: add python_type and sql_type here; combining them
  120. # into "type" is a bad idea
  121. type: Union[Type[Any], TypeEngine[Any]]
  122. aliased: bool
  123. expr: _ColumnsClauseArgument[Any]
  124. entity: Optional[_ColumnsClauseArgument[Any]]
  125. class _IntrospectsAnnotations:
  126. __slots__ = ()
  127. @classmethod
  128. def _mapper_property_name(cls) -> str:
  129. return cls.__name__
  130. def found_in_pep593_annotated(self) -> Any:
  131. """return a copy of this object to use in declarative when the
  132. object is found inside of an Annotated object."""
  133. raise NotImplementedError(
  134. f"Use of the {self._mapper_property_name()!r} "
  135. "construct inside of an Annotated object is not yet supported."
  136. )
  137. def declarative_scan(
  138. self,
  139. decl_scan: _ClassScanMapperConfig,
  140. registry: RegistryType,
  141. cls: Type[Any],
  142. originating_module: Optional[str],
  143. key: str,
  144. mapped_container: Optional[Type[Mapped[Any]]],
  145. annotation: Optional[_AnnotationScanType],
  146. extracted_mapped_annotation: Optional[_AnnotationScanType],
  147. is_dataclass_field: bool,
  148. ) -> None:
  149. """Perform class-specific initializaton at early declarative scanning
  150. time.
  151. .. versionadded:: 2.0
  152. """
  153. def _raise_for_required(self, key: str, cls: Type[Any]) -> NoReturn:
  154. raise sa_exc.ArgumentError(
  155. f"Python typing annotation is required for attribute "
  156. f'"{cls.__name__}.{key}" when primary argument(s) for '
  157. f'"{self._mapper_property_name()}" '
  158. "construct are None or not present"
  159. )
  160. class _AttributeOptions(NamedTuple):
  161. """define Python-local attribute behavior options common to all
  162. :class:`.MapperProperty` objects.
  163. Currently this includes dataclass-generation arguments.
  164. .. versionadded:: 2.0
  165. """
  166. dataclasses_init: Union[_NoArg, bool]
  167. dataclasses_repr: Union[_NoArg, bool]
  168. dataclasses_default: Union[_NoArg, Any]
  169. dataclasses_default_factory: Union[_NoArg, Callable[[], Any]]
  170. dataclasses_compare: Union[_NoArg, bool]
  171. dataclasses_kw_only: Union[_NoArg, bool]
  172. dataclasses_hash: Union[_NoArg, bool, None]
  173. def _as_dataclass_field(self, key: str) -> Any:
  174. """Return a ``dataclasses.Field`` object given these arguments."""
  175. kw: Dict[str, Any] = {}
  176. if self.dataclasses_default_factory is not _NoArg.NO_ARG:
  177. kw["default_factory"] = self.dataclasses_default_factory
  178. if self.dataclasses_default is not _NoArg.NO_ARG:
  179. kw["default"] = self.dataclasses_default
  180. if self.dataclasses_init is not _NoArg.NO_ARG:
  181. kw["init"] = self.dataclasses_init
  182. if self.dataclasses_repr is not _NoArg.NO_ARG:
  183. kw["repr"] = self.dataclasses_repr
  184. if self.dataclasses_compare is not _NoArg.NO_ARG:
  185. kw["compare"] = self.dataclasses_compare
  186. if self.dataclasses_kw_only is not _NoArg.NO_ARG:
  187. kw["kw_only"] = self.dataclasses_kw_only
  188. if self.dataclasses_hash is not _NoArg.NO_ARG:
  189. kw["hash"] = self.dataclasses_hash
  190. if "default" in kw and callable(kw["default"]):
  191. # callable defaults are ambiguous. deprecate them in favour of
  192. # insert_default or default_factory. #9936
  193. warn_deprecated(
  194. f"Callable object passed to the ``default`` parameter for "
  195. f"attribute {key!r} in a ORM-mapped Dataclasses context is "
  196. "ambiguous, "
  197. "and this use will raise an error in a future release. "
  198. "If this callable is intended to produce Core level INSERT "
  199. "default values for an underlying ``Column``, use "
  200. "the ``mapped_column.insert_default`` parameter instead. "
  201. "To establish this callable as providing a default value "
  202. "for instances of the dataclass itself, use the "
  203. "``default_factory`` dataclasses parameter.",
  204. "2.0",
  205. )
  206. if (
  207. "init" in kw
  208. and not kw["init"]
  209. and "default" in kw
  210. and not callable(kw["default"]) # ignore callable defaults. #9936
  211. and "default_factory" not in kw # illegal but let dc.field raise
  212. ):
  213. # fix for #9879
  214. default = kw.pop("default")
  215. kw["default_factory"] = lambda: default
  216. return dataclasses.field(**kw)
  217. @classmethod
  218. def _get_arguments_for_make_dataclass(
  219. cls,
  220. key: str,
  221. annotation: _AnnotationScanType,
  222. mapped_container: Optional[Any],
  223. elem: _T,
  224. ) -> Union[
  225. Tuple[str, _AnnotationScanType],
  226. Tuple[str, _AnnotationScanType, dataclasses.Field[Any]],
  227. ]:
  228. """given attribute key, annotation, and value from a class, return
  229. the argument tuple we would pass to dataclasses.make_dataclass()
  230. for this attribute.
  231. """
  232. if isinstance(elem, _DCAttributeOptions):
  233. dc_field = elem._attribute_options._as_dataclass_field(key)
  234. return (key, annotation, dc_field)
  235. elif elem is not _NoArg.NO_ARG:
  236. # why is typing not erroring on this?
  237. return (key, annotation, elem)
  238. elif mapped_container is not None:
  239. # it's Mapped[], but there's no "element", which means declarative
  240. # did not actually do anything for this field. this shouldn't
  241. # happen.
  242. # previously, this would occur because _scan_attributes would
  243. # skip a field that's on an already mapped superclass, but it
  244. # would still include it in the annotations, leading
  245. # to issue #8718
  246. assert False, "Mapped[] received without a mapping declaration"
  247. else:
  248. # plain dataclass field, not mapped. Is only possible
  249. # if __allow_unmapped__ is set up. I can see this mode causing
  250. # problems...
  251. return (key, annotation)
  252. _DEFAULT_ATTRIBUTE_OPTIONS = _AttributeOptions(
  253. _NoArg.NO_ARG,
  254. _NoArg.NO_ARG,
  255. _NoArg.NO_ARG,
  256. _NoArg.NO_ARG,
  257. _NoArg.NO_ARG,
  258. _NoArg.NO_ARG,
  259. _NoArg.NO_ARG,
  260. )
  261. _DEFAULT_READONLY_ATTRIBUTE_OPTIONS = _AttributeOptions(
  262. False,
  263. _NoArg.NO_ARG,
  264. _NoArg.NO_ARG,
  265. _NoArg.NO_ARG,
  266. _NoArg.NO_ARG,
  267. _NoArg.NO_ARG,
  268. _NoArg.NO_ARG,
  269. )
  270. class _DCAttributeOptions:
  271. """mixin for descriptors or configurational objects that include dataclass
  272. field options.
  273. This includes :class:`.MapperProperty`, :class:`._MapsColumn` within
  274. the ORM, but also includes :class:`.AssociationProxy` within ext.
  275. Can in theory be used for other descriptors that serve a similar role
  276. as association proxy. (*maybe* hybrids, not sure yet.)
  277. """
  278. __slots__ = ()
  279. _attribute_options: _AttributeOptions
  280. """behavioral options for ORM-enabled Python attributes
  281. .. versionadded:: 2.0
  282. """
  283. _has_dataclass_arguments: bool
  284. class _MapsColumns(_DCAttributeOptions, _MappedAttribute[_T]):
  285. """interface for declarative-capable construct that delivers one or more
  286. Column objects to the declarative process to be part of a Table.
  287. """
  288. __slots__ = ()
  289. @property
  290. def mapper_property_to_assign(self) -> Optional[MapperProperty[_T]]:
  291. """return a MapperProperty to be assigned to the declarative mapping"""
  292. raise NotImplementedError()
  293. @property
  294. def columns_to_assign(self) -> List[Tuple[Column[_T], int]]:
  295. """A list of Column objects that should be declaratively added to the
  296. new Table object.
  297. """
  298. raise NotImplementedError()
  299. # NOTE: MapperProperty needs to extend _MappedAttribute so that declarative
  300. # typing works, i.e. "Mapped[A] = relationship()". This introduces an
  301. # inconvenience which is that all the MapperProperty objects are treated
  302. # as descriptors by typing tools, which are misled by this as assignment /
  303. # access to a descriptor attribute wants to move through __get__.
  304. # Therefore, references to MapperProperty as an instance variable, such
  305. # as in PropComparator, may have some special typing workarounds such as the
  306. # use of sqlalchemy.util.typing.DescriptorReference to avoid mis-interpretation
  307. # by typing tools
  308. @inspection._self_inspects
  309. class MapperProperty(
  310. HasCacheKey,
  311. _DCAttributeOptions,
  312. _MappedAttribute[_T],
  313. InspectionAttrInfo,
  314. util.MemoizedSlots,
  315. ):
  316. """Represent a particular class attribute mapped by :class:`_orm.Mapper`.
  317. The most common occurrences of :class:`.MapperProperty` are the
  318. mapped :class:`_schema.Column`, which is represented in a mapping as
  319. an instance of :class:`.ColumnProperty`,
  320. and a reference to another class produced by :func:`_orm.relationship`,
  321. represented in the mapping as an instance of
  322. :class:`.Relationship`.
  323. """
  324. __slots__ = (
  325. "_configure_started",
  326. "_configure_finished",
  327. "_attribute_options",
  328. "_has_dataclass_arguments",
  329. "parent",
  330. "key",
  331. "info",
  332. "doc",
  333. )
  334. _cache_key_traversal: _TraverseInternalsType = [
  335. ("parent", visitors.ExtendedInternalTraversal.dp_has_cache_key),
  336. ("key", visitors.ExtendedInternalTraversal.dp_string),
  337. ]
  338. if not TYPE_CHECKING:
  339. cascade = None
  340. is_property = True
  341. """Part of the InspectionAttr interface; states this object is a
  342. mapper property.
  343. """
  344. comparator: PropComparator[_T]
  345. """The :class:`_orm.PropComparator` instance that implements SQL
  346. expression construction on behalf of this mapped attribute."""
  347. key: str
  348. """name of class attribute"""
  349. parent: Mapper[Any]
  350. """the :class:`.Mapper` managing this property."""
  351. _is_relationship = False
  352. _links_to_entity: bool
  353. """True if this MapperProperty refers to a mapped entity.
  354. Should only be True for Relationship, False for all others.
  355. """
  356. doc: Optional[str]
  357. """optional documentation string"""
  358. info: _InfoType
  359. """Info dictionary associated with the object, allowing user-defined
  360. data to be associated with this :class:`.InspectionAttr`.
  361. The dictionary is generated when first accessed. Alternatively,
  362. it can be specified as a constructor argument to the
  363. :func:`.column_property`, :func:`_orm.relationship`, or :func:`.composite`
  364. functions.
  365. .. seealso::
  366. :attr:`.QueryableAttribute.info`
  367. :attr:`.SchemaItem.info`
  368. """
  369. def _memoized_attr_info(self) -> _InfoType:
  370. """Info dictionary associated with the object, allowing user-defined
  371. data to be associated with this :class:`.InspectionAttr`.
  372. The dictionary is generated when first accessed. Alternatively,
  373. it can be specified as a constructor argument to the
  374. :func:`.column_property`, :func:`_orm.relationship`, or
  375. :func:`.composite`
  376. functions.
  377. .. seealso::
  378. :attr:`.QueryableAttribute.info`
  379. :attr:`.SchemaItem.info`
  380. """
  381. return {}
  382. def setup(
  383. self,
  384. context: ORMCompileState,
  385. query_entity: _MapperEntity,
  386. path: AbstractEntityRegistry,
  387. adapter: Optional[ORMAdapter],
  388. **kwargs: Any,
  389. ) -> None:
  390. """Called by Query for the purposes of constructing a SQL statement.
  391. Each MapperProperty associated with the target mapper processes the
  392. statement referenced by the query context, adding columns and/or
  393. criterion as appropriate.
  394. """
  395. def create_row_processor(
  396. self,
  397. context: ORMCompileState,
  398. query_entity: _MapperEntity,
  399. path: AbstractEntityRegistry,
  400. mapper: Mapper[Any],
  401. result: Result[Any],
  402. adapter: Optional[ORMAdapter],
  403. populators: _PopulatorDict,
  404. ) -> None:
  405. """Produce row processing functions and append to the given
  406. set of populators lists.
  407. """
  408. def cascade_iterator(
  409. self,
  410. type_: str,
  411. state: InstanceState[Any],
  412. dict_: _InstanceDict,
  413. visited_states: Set[InstanceState[Any]],
  414. halt_on: Optional[Callable[[InstanceState[Any]], bool]] = None,
  415. ) -> Iterator[
  416. Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]
  417. ]:
  418. """Iterate through instances related to the given instance for
  419. a particular 'cascade', starting with this MapperProperty.
  420. Return an iterator3-tuples (instance, mapper, state).
  421. Note that the 'cascade' collection on this MapperProperty is
  422. checked first for the given type before cascade_iterator is called.
  423. This method typically only applies to Relationship.
  424. """
  425. return iter(())
  426. def set_parent(self, parent: Mapper[Any], init: bool) -> None:
  427. """Set the parent mapper that references this MapperProperty.
  428. This method is overridden by some subclasses to perform extra
  429. setup when the mapper is first known.
  430. """
  431. self.parent = parent
  432. def instrument_class(self, mapper: Mapper[Any]) -> None:
  433. """Hook called by the Mapper to the property to initiate
  434. instrumentation of the class attribute managed by this
  435. MapperProperty.
  436. The MapperProperty here will typically call out to the
  437. attributes module to set up an InstrumentedAttribute.
  438. This step is the first of two steps to set up an InstrumentedAttribute,
  439. and is called early in the mapper setup process.
  440. The second step is typically the init_class_attribute step,
  441. called from StrategizedProperty via the post_instrument_class()
  442. hook. This step assigns additional state to the InstrumentedAttribute
  443. (specifically the "impl") which has been determined after the
  444. MapperProperty has determined what kind of persistence
  445. management it needs to do (e.g. scalar, object, collection, etc).
  446. """
  447. def __init__(
  448. self,
  449. attribute_options: Optional[_AttributeOptions] = None,
  450. _assume_readonly_dc_attributes: bool = False,
  451. ) -> None:
  452. self._configure_started = False
  453. self._configure_finished = False
  454. if _assume_readonly_dc_attributes:
  455. default_attrs = _DEFAULT_READONLY_ATTRIBUTE_OPTIONS
  456. else:
  457. default_attrs = _DEFAULT_ATTRIBUTE_OPTIONS
  458. if attribute_options and attribute_options != default_attrs:
  459. self._has_dataclass_arguments = True
  460. self._attribute_options = attribute_options
  461. else:
  462. self._has_dataclass_arguments = False
  463. self._attribute_options = default_attrs
  464. def init(self) -> None:
  465. """Called after all mappers are created to assemble
  466. relationships between mappers and perform other post-mapper-creation
  467. initialization steps.
  468. """
  469. self._configure_started = True
  470. self.do_init()
  471. self._configure_finished = True
  472. @property
  473. def class_attribute(self) -> InstrumentedAttribute[_T]:
  474. """Return the class-bound descriptor corresponding to this
  475. :class:`.MapperProperty`.
  476. This is basically a ``getattr()`` call::
  477. return getattr(self.parent.class_, self.key)
  478. I.e. if this :class:`.MapperProperty` were named ``addresses``,
  479. and the class to which it is mapped is ``User``, this sequence
  480. is possible::
  481. >>> from sqlalchemy import inspect
  482. >>> mapper = inspect(User)
  483. >>> addresses_property = mapper.attrs.addresses
  484. >>> addresses_property.class_attribute is User.addresses
  485. True
  486. >>> User.addresses.property is addresses_property
  487. True
  488. """
  489. return getattr(self.parent.class_, self.key) # type: ignore
  490. def do_init(self) -> None:
  491. """Perform subclass-specific initialization post-mapper-creation
  492. steps.
  493. This is a template method called by the ``MapperProperty``
  494. object's init() method.
  495. """
  496. def post_instrument_class(self, mapper: Mapper[Any]) -> None:
  497. """Perform instrumentation adjustments that need to occur
  498. after init() has completed.
  499. The given Mapper is the Mapper invoking the operation, which
  500. may not be the same Mapper as self.parent in an inheritance
  501. scenario; however, Mapper will always at least be a sub-mapper of
  502. self.parent.
  503. This method is typically used by StrategizedProperty, which delegates
  504. it to LoaderStrategy.init_class_attribute() to perform final setup
  505. on the class-bound InstrumentedAttribute.
  506. """
  507. def merge(
  508. self,
  509. session: Session,
  510. source_state: InstanceState[Any],
  511. source_dict: _InstanceDict,
  512. dest_state: InstanceState[Any],
  513. dest_dict: _InstanceDict,
  514. load: bool,
  515. _recursive: Dict[Any, object],
  516. _resolve_conflict_map: Dict[_IdentityKeyType[Any], object],
  517. ) -> None:
  518. """Merge the attribute represented by this ``MapperProperty``
  519. from source to destination object.
  520. """
  521. def __repr__(self) -> str:
  522. return "<%s at 0x%x; %s>" % (
  523. self.__class__.__name__,
  524. id(self),
  525. getattr(self, "key", "no key"),
  526. )
  527. @inspection._self_inspects
  528. class PropComparator(SQLORMOperations[_T_co], Generic[_T_co], ColumnOperators):
  529. r"""Defines SQL operations for ORM mapped attributes.
  530. SQLAlchemy allows for operators to
  531. be redefined at both the Core and ORM level. :class:`.PropComparator`
  532. is the base class of operator redefinition for ORM-level operations,
  533. including those of :class:`.ColumnProperty`,
  534. :class:`.Relationship`, and :class:`.Composite`.
  535. User-defined subclasses of :class:`.PropComparator` may be created. The
  536. built-in Python comparison and math operator methods, such as
  537. :meth:`.operators.ColumnOperators.__eq__`,
  538. :meth:`.operators.ColumnOperators.__lt__`, and
  539. :meth:`.operators.ColumnOperators.__add__`, can be overridden to provide
  540. new operator behavior. The custom :class:`.PropComparator` is passed to
  541. the :class:`.MapperProperty` instance via the ``comparator_factory``
  542. argument. In each case,
  543. the appropriate subclass of :class:`.PropComparator` should be used::
  544. # definition of custom PropComparator subclasses
  545. from sqlalchemy.orm.properties import (
  546. ColumnProperty,
  547. Composite,
  548. Relationship,
  549. )
  550. class MyColumnComparator(ColumnProperty.Comparator):
  551. def __eq__(self, other):
  552. return self.__clause_element__() == other
  553. class MyRelationshipComparator(Relationship.Comparator):
  554. def any(self, expression):
  555. "define the 'any' operation"
  556. # ...
  557. class MyCompositeComparator(Composite.Comparator):
  558. def __gt__(self, other):
  559. "redefine the 'greater than' operation"
  560. return sql.and_(
  561. *[
  562. a > b
  563. for a, b in zip(
  564. self.__clause_element__().clauses,
  565. other.__composite_values__(),
  566. )
  567. ]
  568. )
  569. # application of custom PropComparator subclasses
  570. from sqlalchemy.orm import column_property, relationship, composite
  571. from sqlalchemy import Column, String
  572. class SomeMappedClass(Base):
  573. some_column = column_property(
  574. Column("some_column", String),
  575. comparator_factory=MyColumnComparator,
  576. )
  577. some_relationship = relationship(
  578. SomeOtherClass, comparator_factory=MyRelationshipComparator
  579. )
  580. some_composite = composite(
  581. Column("a", String),
  582. Column("b", String),
  583. comparator_factory=MyCompositeComparator,
  584. )
  585. Note that for column-level operator redefinition, it's usually
  586. simpler to define the operators at the Core level, using the
  587. :attr:`.TypeEngine.comparator_factory` attribute. See
  588. :ref:`types_operators` for more detail.
  589. .. seealso::
  590. :class:`.ColumnProperty.Comparator`
  591. :class:`.Relationship.Comparator`
  592. :class:`.Composite.Comparator`
  593. :class:`.ColumnOperators`
  594. :ref:`types_operators`
  595. :attr:`.TypeEngine.comparator_factory`
  596. """
  597. __slots__ = "prop", "_parententity", "_adapt_to_entity"
  598. __visit_name__ = "orm_prop_comparator"
  599. _parententity: _InternalEntityType[Any]
  600. _adapt_to_entity: Optional[AliasedInsp[Any]]
  601. prop: RODescriptorReference[MapperProperty[_T_co]]
  602. def __init__(
  603. self,
  604. prop: MapperProperty[_T],
  605. parentmapper: _InternalEntityType[Any],
  606. adapt_to_entity: Optional[AliasedInsp[Any]] = None,
  607. ):
  608. self.prop = prop
  609. self._parententity = adapt_to_entity or parentmapper
  610. self._adapt_to_entity = adapt_to_entity
  611. @util.non_memoized_property
  612. def property(self) -> MapperProperty[_T_co]:
  613. """Return the :class:`.MapperProperty` associated with this
  614. :class:`.PropComparator`.
  615. Return values here will commonly be instances of
  616. :class:`.ColumnProperty` or :class:`.Relationship`.
  617. """
  618. return self.prop
  619. def __clause_element__(self) -> roles.ColumnsClauseRole:
  620. raise NotImplementedError("%r" % self)
  621. def _bulk_update_tuples(
  622. self, value: Any
  623. ) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
  624. """Receive a SQL expression that represents a value in the SET
  625. clause of an UPDATE statement.
  626. Return a tuple that can be passed to a :class:`_expression.Update`
  627. construct.
  628. """
  629. return [(cast("_DMLColumnArgument", self.__clause_element__()), value)]
  630. def adapt_to_entity(
  631. self, adapt_to_entity: AliasedInsp[Any]
  632. ) -> PropComparator[_T_co]:
  633. """Return a copy of this PropComparator which will use the given
  634. :class:`.AliasedInsp` to produce corresponding expressions.
  635. """
  636. return self.__class__(self.prop, self._parententity, adapt_to_entity)
  637. @util.ro_non_memoized_property
  638. def _parentmapper(self) -> Mapper[Any]:
  639. """legacy; this is renamed to _parententity to be
  640. compatible with QueryableAttribute."""
  641. return self._parententity.mapper
  642. def _criterion_exists(
  643. self,
  644. criterion: Optional[_ColumnExpressionArgument[bool]] = None,
  645. **kwargs: Any,
  646. ) -> ColumnElement[Any]:
  647. return self.prop.comparator._criterion_exists(criterion, **kwargs)
  648. @util.ro_non_memoized_property
  649. def adapter(self) -> Optional[_ORMAdapterProto]:
  650. """Produce a callable that adapts column expressions
  651. to suit an aliased version of this comparator.
  652. """
  653. if self._adapt_to_entity is None:
  654. return None
  655. else:
  656. return self._adapt_to_entity._orm_adapt_element
  657. @util.ro_non_memoized_property
  658. def info(self) -> _InfoType:
  659. return self.prop.info
  660. @staticmethod
  661. def _any_op(a: Any, b: Any, **kwargs: Any) -> Any:
  662. return a.any(b, **kwargs)
  663. @staticmethod
  664. def _has_op(left: Any, other: Any, **kwargs: Any) -> Any:
  665. return left.has(other, **kwargs)
  666. @staticmethod
  667. def _of_type_op(a: Any, class_: Any) -> Any:
  668. return a.of_type(class_)
  669. any_op = cast(operators.OperatorType, _any_op)
  670. has_op = cast(operators.OperatorType, _has_op)
  671. of_type_op = cast(operators.OperatorType, _of_type_op)
  672. if typing.TYPE_CHECKING:
  673. def operate(
  674. self, op: OperatorType, *other: Any, **kwargs: Any
  675. ) -> ColumnElement[Any]: ...
  676. def reverse_operate(
  677. self, op: OperatorType, other: Any, **kwargs: Any
  678. ) -> ColumnElement[Any]: ...
  679. def of_type(self, class_: _EntityType[Any]) -> PropComparator[_T_co]:
  680. r"""Redefine this object in terms of a polymorphic subclass,
  681. :func:`_orm.with_polymorphic` construct, or :func:`_orm.aliased`
  682. construct.
  683. Returns a new PropComparator from which further criterion can be
  684. evaluated.
  685. e.g.::
  686. query.join(Company.employees.of_type(Engineer)).filter(
  687. Engineer.name == "foo"
  688. )
  689. :param \class_: a class or mapper indicating that criterion will be
  690. against this specific subclass.
  691. .. seealso::
  692. :ref:`orm_queryguide_joining_relationships_aliased` - in the
  693. :ref:`queryguide_toplevel`
  694. :ref:`inheritance_of_type`
  695. """
  696. return self.operate(PropComparator.of_type_op, class_) # type: ignore
  697. def and_(
  698. self, *criteria: _ColumnExpressionArgument[bool]
  699. ) -> PropComparator[bool]:
  700. """Add additional criteria to the ON clause that's represented by this
  701. relationship attribute.
  702. E.g.::
  703. stmt = select(User).join(
  704. User.addresses.and_(Address.email_address != "foo")
  705. )
  706. stmt = select(User).options(
  707. joinedload(User.addresses.and_(Address.email_address != "foo"))
  708. )
  709. .. versionadded:: 1.4
  710. .. seealso::
  711. :ref:`orm_queryguide_join_on_augmented`
  712. :ref:`loader_option_criteria`
  713. :func:`.with_loader_criteria`
  714. """
  715. return self.operate(operators.and_, *criteria) # type: ignore
  716. def any(
  717. self,
  718. criterion: Optional[_ColumnExpressionArgument[bool]] = None,
  719. **kwargs: Any,
  720. ) -> ColumnElement[bool]:
  721. r"""Return a SQL expression representing true if this element
  722. references a member which meets the given criterion.
  723. The usual implementation of ``any()`` is
  724. :meth:`.Relationship.Comparator.any`.
  725. :param criterion: an optional ClauseElement formulated against the
  726. member class' table or attributes.
  727. :param \**kwargs: key/value pairs corresponding to member class
  728. attribute names which will be compared via equality to the
  729. corresponding values.
  730. """
  731. return self.operate(PropComparator.any_op, criterion, **kwargs)
  732. def has(
  733. self,
  734. criterion: Optional[_ColumnExpressionArgument[bool]] = None,
  735. **kwargs: Any,
  736. ) -> ColumnElement[bool]:
  737. r"""Return a SQL expression representing true if this element
  738. references a member which meets the given criterion.
  739. The usual implementation of ``has()`` is
  740. :meth:`.Relationship.Comparator.has`.
  741. :param criterion: an optional ClauseElement formulated against the
  742. member class' table or attributes.
  743. :param \**kwargs: key/value pairs corresponding to member class
  744. attribute names which will be compared via equality to the
  745. corresponding values.
  746. """
  747. return self.operate(PropComparator.has_op, criterion, **kwargs)
  748. class StrategizedProperty(MapperProperty[_T]):
  749. """A MapperProperty which uses selectable strategies to affect
  750. loading behavior.
  751. There is a single strategy selected by default. Alternate
  752. strategies can be selected at Query time through the usage of
  753. ``StrategizedOption`` objects via the Query.options() method.
  754. The mechanics of StrategizedProperty are used for every Query
  755. invocation for every mapped attribute participating in that Query,
  756. to determine first how the attribute will be rendered in SQL
  757. and secondly how the attribute will retrieve a value from a result
  758. row and apply it to a mapped object. The routines here are very
  759. performance-critical.
  760. """
  761. __slots__ = (
  762. "_strategies",
  763. "strategy",
  764. "_wildcard_token",
  765. "_default_path_loader_key",
  766. "strategy_key",
  767. )
  768. inherit_cache = True
  769. strategy_wildcard_key: ClassVar[str]
  770. strategy_key: _StrategyKey
  771. _strategies: Dict[_StrategyKey, LoaderStrategy]
  772. def _memoized_attr__wildcard_token(self) -> Tuple[str]:
  773. return (
  774. f"{self.strategy_wildcard_key}:{path_registry._WILDCARD_TOKEN}",
  775. )
  776. def _memoized_attr__default_path_loader_key(
  777. self,
  778. ) -> Tuple[str, Tuple[str]]:
  779. return (
  780. "loader",
  781. (f"{self.strategy_wildcard_key}:{path_registry._DEFAULT_TOKEN}",),
  782. )
  783. def _get_context_loader(
  784. self, context: ORMCompileState, path: AbstractEntityRegistry
  785. ) -> Optional[_LoadElement]:
  786. load: Optional[_LoadElement] = None
  787. search_path = path[self]
  788. # search among: exact match, "attr.*", "default" strategy
  789. # if any.
  790. for path_key in (
  791. search_path._loader_key,
  792. search_path._wildcard_path_loader_key,
  793. search_path._default_path_loader_key,
  794. ):
  795. if path_key in context.attributes:
  796. load = context.attributes[path_key]
  797. break
  798. # note that if strategy_options.Load is placing non-actionable
  799. # objects in the context like defaultload(), we would
  800. # need to continue the loop here if we got such an
  801. # option as below.
  802. # if load.strategy or load.local_opts:
  803. # break
  804. return load
  805. def _get_strategy(self, key: _StrategyKey) -> LoaderStrategy:
  806. try:
  807. return self._strategies[key]
  808. except KeyError:
  809. pass
  810. # run outside to prevent transfer of exception context
  811. cls = self._strategy_lookup(self, *key)
  812. # this previously was setting self._strategies[cls], that's
  813. # a bad idea; should use strategy key at all times because every
  814. # strategy has multiple keys at this point
  815. self._strategies[key] = strategy = cls(self, key)
  816. return strategy
  817. def setup(
  818. self,
  819. context: ORMCompileState,
  820. query_entity: _MapperEntity,
  821. path: AbstractEntityRegistry,
  822. adapter: Optional[ORMAdapter],
  823. **kwargs: Any,
  824. ) -> None:
  825. loader = self._get_context_loader(context, path)
  826. if loader and loader.strategy:
  827. strat = self._get_strategy(loader.strategy)
  828. else:
  829. strat = self.strategy
  830. strat.setup_query(
  831. context, query_entity, path, loader, adapter, **kwargs
  832. )
  833. def create_row_processor(
  834. self,
  835. context: ORMCompileState,
  836. query_entity: _MapperEntity,
  837. path: AbstractEntityRegistry,
  838. mapper: Mapper[Any],
  839. result: Result[Any],
  840. adapter: Optional[ORMAdapter],
  841. populators: _PopulatorDict,
  842. ) -> None:
  843. loader = self._get_context_loader(context, path)
  844. if loader and loader.strategy:
  845. strat = self._get_strategy(loader.strategy)
  846. else:
  847. strat = self.strategy
  848. strat.create_row_processor(
  849. context,
  850. query_entity,
  851. path,
  852. loader,
  853. mapper,
  854. result,
  855. adapter,
  856. populators,
  857. )
  858. def do_init(self) -> None:
  859. self._strategies = {}
  860. self.strategy = self._get_strategy(self.strategy_key)
  861. def post_instrument_class(self, mapper: Mapper[Any]) -> None:
  862. if (
  863. not self.parent.non_primary
  864. and not mapper.class_manager._attr_has_impl(self.key)
  865. ):
  866. self.strategy.init_class_attribute(mapper)
  867. _all_strategies: collections.defaultdict[
  868. Type[MapperProperty[Any]], Dict[_StrategyKey, Type[LoaderStrategy]]
  869. ] = collections.defaultdict(dict)
  870. @classmethod
  871. def strategy_for(cls, **kw: Any) -> Callable[[_TLS], _TLS]:
  872. def decorate(dec_cls: _TLS) -> _TLS:
  873. # ensure each subclass of the strategy has its
  874. # own _strategy_keys collection
  875. if "_strategy_keys" not in dec_cls.__dict__:
  876. dec_cls._strategy_keys = []
  877. key = tuple(sorted(kw.items()))
  878. cls._all_strategies[cls][key] = dec_cls
  879. dec_cls._strategy_keys.append(key)
  880. return dec_cls
  881. return decorate
  882. @classmethod
  883. def _strategy_lookup(
  884. cls, requesting_property: MapperProperty[Any], *key: Any
  885. ) -> Type[LoaderStrategy]:
  886. requesting_property.parent._with_polymorphic_mappers
  887. for prop_cls in cls.__mro__:
  888. if prop_cls in cls._all_strategies:
  889. if TYPE_CHECKING:
  890. assert issubclass(prop_cls, MapperProperty)
  891. strategies = cls._all_strategies[prop_cls]
  892. try:
  893. return strategies[key]
  894. except KeyError:
  895. pass
  896. for property_type, strats in cls._all_strategies.items():
  897. if key in strats:
  898. intended_property_type = property_type
  899. actual_strategy = strats[key]
  900. break
  901. else:
  902. intended_property_type = None
  903. actual_strategy = None
  904. raise orm_exc.LoaderStrategyException(
  905. cls,
  906. requesting_property,
  907. intended_property_type,
  908. actual_strategy,
  909. key,
  910. )
  911. class ORMOption(ExecutableOption):
  912. """Base class for option objects that are passed to ORM queries.
  913. These options may be consumed by :meth:`.Query.options`,
  914. :meth:`.Select.options`, or in a more general sense by any
  915. :meth:`.Executable.options` method. They are interpreted at
  916. statement compile time or execution time in modern use. The
  917. deprecated :class:`.MapperOption` is consumed at ORM query construction
  918. time.
  919. .. versionadded:: 1.4
  920. """
  921. __slots__ = ()
  922. _is_legacy_option = False
  923. propagate_to_loaders = False
  924. """if True, indicate this option should be carried along
  925. to "secondary" SELECT statements that occur for relationship
  926. lazy loaders as well as attribute load / refresh operations.
  927. """
  928. _is_core = False
  929. _is_user_defined = False
  930. _is_compile_state = False
  931. _is_criteria_option = False
  932. _is_strategy_option = False
  933. def _adapt_cached_option_to_uncached_option(
  934. self, context: QueryContext, uncached_opt: ORMOption
  935. ) -> ORMOption:
  936. """adapt this option to the "uncached" version of itself in a
  937. loader strategy context.
  938. given "self" which is an option from a cached query, as well as the
  939. corresponding option from the uncached version of the same query,
  940. return the option we should use in a new query, in the context of a
  941. loader strategy being asked to load related rows on behalf of that
  942. cached query, which is assumed to be building a new query based on
  943. entities passed to us from the cached query.
  944. Currently this routine chooses between "self" and "uncached" without
  945. manufacturing anything new. If the option is itself a loader strategy
  946. option which has a path, that path needs to match to the entities being
  947. passed to us by the cached query, so the :class:`_orm.Load` subclass
  948. overrides this to return "self". For all other options, we return the
  949. uncached form which may have changing state, such as a
  950. with_loader_criteria() option which will very often have new state.
  951. This routine could in the future involve
  952. generating a new option based on both inputs if use cases arise,
  953. such as if with_loader_criteria() needed to match up to
  954. ``AliasedClass`` instances given in the parent query.
  955. However, longer term it might be better to restructure things such that
  956. ``AliasedClass`` entities are always matched up on their cache key,
  957. instead of identity, in things like paths and such, so that this whole
  958. issue of "the uncached option does not match the entities" goes away.
  959. However this would make ``PathRegistry`` more complicated and difficult
  960. to debug as well as potentially less performant in that it would be
  961. hashing enormous cache keys rather than a simple AliasedInsp. UNLESS,
  962. we could get cache keys overall to be reliably hashed into something
  963. like an md5 key.
  964. .. versionadded:: 1.4.41
  965. """
  966. if uncached_opt is not None:
  967. return uncached_opt
  968. else:
  969. return self
  970. class CompileStateOption(HasCacheKey, ORMOption):
  971. """base for :class:`.ORMOption` classes that affect the compilation of
  972. a SQL query and therefore need to be part of the cache key.
  973. .. note:: :class:`.CompileStateOption` is generally non-public and
  974. should not be used as a base class for user-defined options; instead,
  975. use :class:`.UserDefinedOption`, which is easier to use as it does not
  976. interact with ORM compilation internals or caching.
  977. :class:`.CompileStateOption` defines an internal attribute
  978. ``_is_compile_state=True`` which has the effect of the ORM compilation
  979. routines for SELECT and other statements will call upon these options when
  980. a SQL string is being compiled. As such, these classes implement
  981. :class:`.HasCacheKey` and need to provide robust ``_cache_key_traversal``
  982. structures.
  983. The :class:`.CompileStateOption` class is used to implement the ORM
  984. :class:`.LoaderOption` and :class:`.CriteriaOption` classes.
  985. .. versionadded:: 1.4.28
  986. """
  987. __slots__ = ()
  988. _is_compile_state = True
  989. def process_compile_state(self, compile_state: ORMCompileState) -> None:
  990. """Apply a modification to a given :class:`.ORMCompileState`.
  991. This method is part of the implementation of a particular
  992. :class:`.CompileStateOption` and is only invoked internally
  993. when an ORM query is compiled.
  994. """
  995. def process_compile_state_replaced_entities(
  996. self,
  997. compile_state: ORMCompileState,
  998. mapper_entities: Sequence[_MapperEntity],
  999. ) -> None:
  1000. """Apply a modification to a given :class:`.ORMCompileState`,
  1001. given entities that were replaced by with_only_columns() or
  1002. with_entities().
  1003. This method is part of the implementation of a particular
  1004. :class:`.CompileStateOption` and is only invoked internally
  1005. when an ORM query is compiled.
  1006. .. versionadded:: 1.4.19
  1007. """
  1008. class LoaderOption(CompileStateOption):
  1009. """Describe a loader modification to an ORM statement at compilation time.
  1010. .. versionadded:: 1.4
  1011. """
  1012. __slots__ = ()
  1013. def process_compile_state_replaced_entities(
  1014. self,
  1015. compile_state: ORMCompileState,
  1016. mapper_entities: Sequence[_MapperEntity],
  1017. ) -> None:
  1018. self.process_compile_state(compile_state)
  1019. class CriteriaOption(CompileStateOption):
  1020. """Describe a WHERE criteria modification to an ORM statement at
  1021. compilation time.
  1022. .. versionadded:: 1.4
  1023. """
  1024. __slots__ = ()
  1025. _is_criteria_option = True
  1026. def get_global_criteria(self, attributes: Dict[str, Any]) -> None:
  1027. """update additional entity criteria options in the given
  1028. attributes dictionary.
  1029. """
  1030. class UserDefinedOption(ORMOption):
  1031. """Base class for a user-defined option that can be consumed from the
  1032. :meth:`.SessionEvents.do_orm_execute` event hook.
  1033. """
  1034. __slots__ = ("payload",)
  1035. _is_legacy_option = False
  1036. _is_user_defined = True
  1037. propagate_to_loaders = False
  1038. """if True, indicate this option should be carried along
  1039. to "secondary" Query objects produced during lazy loads
  1040. or refresh operations.
  1041. """
  1042. def __init__(self, payload: Optional[Any] = None):
  1043. self.payload = payload
  1044. @util.deprecated_cls(
  1045. "1.4",
  1046. "The :class:`.MapperOption class is deprecated and will be removed "
  1047. "in a future release. For "
  1048. "modifications to queries on a per-execution basis, use the "
  1049. ":class:`.UserDefinedOption` class to establish state within a "
  1050. ":class:`.Query` or other Core statement, then use the "
  1051. ":meth:`.SessionEvents.before_orm_execute` hook to consume them.",
  1052. constructor=None,
  1053. )
  1054. class MapperOption(ORMOption):
  1055. """Describe a modification to a Query"""
  1056. __slots__ = ()
  1057. _is_legacy_option = True
  1058. propagate_to_loaders = False
  1059. """if True, indicate this option should be carried along
  1060. to "secondary" Query objects produced during lazy loads
  1061. or refresh operations.
  1062. """
  1063. def process_query(self, query: Query[Any]) -> None:
  1064. """Apply a modification to the given :class:`_query.Query`."""
  1065. def process_query_conditionally(self, query: Query[Any]) -> None:
  1066. """same as process_query(), except that this option may not
  1067. apply to the given query.
  1068. This is typically applied during a lazy load or scalar refresh
  1069. operation to propagate options stated in the original Query to the
  1070. new Query being used for the load. It occurs for those options that
  1071. specify propagate_to_loaders=True.
  1072. """
  1073. self.process_query(query)
  1074. class LoaderStrategy:
  1075. """Describe the loading behavior of a StrategizedProperty object.
  1076. The ``LoaderStrategy`` interacts with the querying process in three
  1077. ways:
  1078. * it controls the configuration of the ``InstrumentedAttribute``
  1079. placed on a class to handle the behavior of the attribute. this
  1080. may involve setting up class-level callable functions to fire
  1081. off a select operation when the attribute is first accessed
  1082. (i.e. a lazy load)
  1083. * it processes the ``QueryContext`` at statement construction time,
  1084. where it can modify the SQL statement that is being produced.
  1085. For example, simple column attributes will add their represented
  1086. column to the list of selected columns, a joined eager loader
  1087. may establish join clauses to add to the statement.
  1088. * It produces "row processor" functions at result fetching time.
  1089. These "row processor" functions populate a particular attribute
  1090. on a particular mapped instance.
  1091. """
  1092. __slots__ = (
  1093. "parent_property",
  1094. "is_class_level",
  1095. "parent",
  1096. "key",
  1097. "strategy_key",
  1098. "strategy_opts",
  1099. )
  1100. _strategy_keys: ClassVar[List[_StrategyKey]]
  1101. def __init__(
  1102. self, parent: MapperProperty[Any], strategy_key: _StrategyKey
  1103. ):
  1104. self.parent_property = parent
  1105. self.is_class_level = False
  1106. self.parent = self.parent_property.parent
  1107. self.key = self.parent_property.key
  1108. self.strategy_key = strategy_key
  1109. self.strategy_opts = dict(strategy_key)
  1110. def init_class_attribute(self, mapper: Mapper[Any]) -> None:
  1111. pass
  1112. def setup_query(
  1113. self,
  1114. compile_state: ORMCompileState,
  1115. query_entity: _MapperEntity,
  1116. path: AbstractEntityRegistry,
  1117. loadopt: Optional[_LoadElement],
  1118. adapter: Optional[ORMAdapter],
  1119. **kwargs: Any,
  1120. ) -> None:
  1121. """Establish column and other state for a given QueryContext.
  1122. This method fulfills the contract specified by MapperProperty.setup().
  1123. StrategizedProperty delegates its setup() method
  1124. directly to this method.
  1125. """
  1126. def create_row_processor(
  1127. self,
  1128. context: ORMCompileState,
  1129. query_entity: _MapperEntity,
  1130. path: AbstractEntityRegistry,
  1131. loadopt: Optional[_LoadElement],
  1132. mapper: Mapper[Any],
  1133. result: Result[Any],
  1134. adapter: Optional[ORMAdapter],
  1135. populators: _PopulatorDict,
  1136. ) -> None:
  1137. """Establish row processing functions for a given QueryContext.
  1138. This method fulfills the contract specified by
  1139. MapperProperty.create_row_processor().
  1140. StrategizedProperty delegates its create_row_processor() method
  1141. directly to this method.
  1142. """
  1143. def __str__(self) -> str:
  1144. return str(self.parent_property)