interfaces.py 47 KB

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