base.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. # orm/base.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. """Constants and rudimental functions used throughout the ORM.
  8. """
  9. from __future__ import annotations
  10. from enum import Enum
  11. import operator
  12. import typing
  13. from typing import Any
  14. from typing import Callable
  15. from typing import Dict
  16. from typing import Generic
  17. from typing import no_type_check
  18. from typing import Optional
  19. from typing import overload
  20. from typing import Type
  21. from typing import TYPE_CHECKING
  22. from typing import TypeVar
  23. from typing import Union
  24. from . import exc
  25. from ._typing import insp_is_mapper
  26. from .. import exc as sa_exc
  27. from .. import inspection
  28. from .. import util
  29. from ..sql import roles
  30. from ..sql.elements import SQLColumnExpression
  31. from ..sql.elements import SQLCoreOperations
  32. from ..util import FastIntFlag
  33. from ..util.langhelpers import TypingOnly
  34. from ..util.typing import Literal
  35. if typing.TYPE_CHECKING:
  36. from ._typing import _EntityType
  37. from ._typing import _ExternalEntityType
  38. from ._typing import _InternalEntityType
  39. from .attributes import InstrumentedAttribute
  40. from .dynamic import AppenderQuery
  41. from .instrumentation import ClassManager
  42. from .interfaces import PropComparator
  43. from .mapper import Mapper
  44. from .state import InstanceState
  45. from .util import AliasedClass
  46. from .writeonly import WriteOnlyCollection
  47. from ..sql._typing import _ColumnExpressionArgument
  48. from ..sql._typing import _InfoType
  49. from ..sql.elements import ColumnElement
  50. from ..sql.operators import OperatorType
  51. _T = TypeVar("_T", bound=Any)
  52. _T_co = TypeVar("_T_co", bound=Any, covariant=True)
  53. _O = TypeVar("_O", bound=object)
  54. class LoaderCallableStatus(Enum):
  55. PASSIVE_NO_RESULT = 0
  56. """Symbol returned by a loader callable or other attribute/history
  57. retrieval operation when a value could not be determined, based
  58. on loader callable flags.
  59. """
  60. PASSIVE_CLASS_MISMATCH = 1
  61. """Symbol indicating that an object is locally present for a given
  62. primary key identity but it is not of the requested class. The
  63. return value is therefore None and no SQL should be emitted."""
  64. ATTR_WAS_SET = 2
  65. """Symbol returned by a loader callable to indicate the
  66. retrieved value, or values, were assigned to their attributes
  67. on the target object.
  68. """
  69. ATTR_EMPTY = 3
  70. """Symbol used internally to indicate an attribute had no callable."""
  71. NO_VALUE = 4
  72. """Symbol which may be placed as the 'previous' value of an attribute,
  73. indicating no value was loaded for an attribute when it was modified,
  74. and flags indicated we were not to load it.
  75. """
  76. NEVER_SET = NO_VALUE
  77. """
  78. Synonymous with NO_VALUE
  79. .. versionchanged:: 1.4 NEVER_SET was merged with NO_VALUE
  80. """
  81. (
  82. PASSIVE_NO_RESULT,
  83. PASSIVE_CLASS_MISMATCH,
  84. ATTR_WAS_SET,
  85. ATTR_EMPTY,
  86. NO_VALUE,
  87. ) = tuple(LoaderCallableStatus)
  88. NEVER_SET = NO_VALUE
  89. class PassiveFlag(FastIntFlag):
  90. """Bitflag interface that passes options onto loader callables"""
  91. NO_CHANGE = 0
  92. """No callables or SQL should be emitted on attribute access
  93. and no state should change
  94. """
  95. CALLABLES_OK = 1
  96. """Loader callables can be fired off if a value
  97. is not present.
  98. """
  99. SQL_OK = 2
  100. """Loader callables can emit SQL at least on scalar value attributes."""
  101. RELATED_OBJECT_OK = 4
  102. """Callables can use SQL to load related objects as well
  103. as scalar value attributes.
  104. """
  105. INIT_OK = 8
  106. """Attributes should be initialized with a blank
  107. value (None or an empty collection) upon get, if no other
  108. value can be obtained.
  109. """
  110. NON_PERSISTENT_OK = 16
  111. """Callables can be emitted if the parent is not persistent."""
  112. LOAD_AGAINST_COMMITTED = 32
  113. """Callables should use committed values as primary/foreign keys during a
  114. load.
  115. """
  116. NO_AUTOFLUSH = 64
  117. """Loader callables should disable autoflush.""",
  118. NO_RAISE = 128
  119. """Loader callables should not raise any assertions"""
  120. DEFERRED_HISTORY_LOAD = 256
  121. """indicates special load of the previous value of an attribute"""
  122. INCLUDE_PENDING_MUTATIONS = 512
  123. # pre-packaged sets of flags used as inputs
  124. PASSIVE_OFF = (
  125. RELATED_OBJECT_OK | NON_PERSISTENT_OK | INIT_OK | CALLABLES_OK | SQL_OK
  126. )
  127. "Callables can be emitted in all cases."
  128. PASSIVE_RETURN_NO_VALUE = PASSIVE_OFF ^ INIT_OK
  129. """PASSIVE_OFF ^ INIT_OK"""
  130. PASSIVE_NO_INITIALIZE = PASSIVE_RETURN_NO_VALUE ^ CALLABLES_OK
  131. "PASSIVE_RETURN_NO_VALUE ^ CALLABLES_OK"
  132. PASSIVE_NO_FETCH = PASSIVE_OFF ^ SQL_OK
  133. "PASSIVE_OFF ^ SQL_OK"
  134. PASSIVE_NO_FETCH_RELATED = PASSIVE_OFF ^ RELATED_OBJECT_OK
  135. "PASSIVE_OFF ^ RELATED_OBJECT_OK"
  136. PASSIVE_ONLY_PERSISTENT = PASSIVE_OFF ^ NON_PERSISTENT_OK
  137. "PASSIVE_OFF ^ NON_PERSISTENT_OK"
  138. PASSIVE_MERGE = PASSIVE_OFF | NO_RAISE
  139. """PASSIVE_OFF | NO_RAISE
  140. Symbol used specifically for session.merge() and similar cases
  141. """
  142. (
  143. NO_CHANGE,
  144. CALLABLES_OK,
  145. SQL_OK,
  146. RELATED_OBJECT_OK,
  147. INIT_OK,
  148. NON_PERSISTENT_OK,
  149. LOAD_AGAINST_COMMITTED,
  150. NO_AUTOFLUSH,
  151. NO_RAISE,
  152. DEFERRED_HISTORY_LOAD,
  153. INCLUDE_PENDING_MUTATIONS,
  154. PASSIVE_OFF,
  155. PASSIVE_RETURN_NO_VALUE,
  156. PASSIVE_NO_INITIALIZE,
  157. PASSIVE_NO_FETCH,
  158. PASSIVE_NO_FETCH_RELATED,
  159. PASSIVE_ONLY_PERSISTENT,
  160. PASSIVE_MERGE,
  161. ) = PassiveFlag.__members__.values()
  162. DEFAULT_MANAGER_ATTR = "_sa_class_manager"
  163. DEFAULT_STATE_ATTR = "_sa_instance_state"
  164. class EventConstants(Enum):
  165. EXT_CONTINUE = 1
  166. EXT_STOP = 2
  167. EXT_SKIP = 3
  168. NO_KEY = 4
  169. """indicates an :class:`.AttributeEvent` event that did not have any
  170. key argument.
  171. .. versionadded:: 2.0
  172. """
  173. EXT_CONTINUE, EXT_STOP, EXT_SKIP, NO_KEY = tuple(EventConstants)
  174. class RelationshipDirection(Enum):
  175. """enumeration which indicates the 'direction' of a
  176. :class:`_orm.RelationshipProperty`.
  177. :class:`.RelationshipDirection` is accessible from the
  178. :attr:`_orm.Relationship.direction` attribute of
  179. :class:`_orm.RelationshipProperty`.
  180. """
  181. ONETOMANY = 1
  182. """Indicates the one-to-many direction for a :func:`_orm.relationship`.
  183. This symbol is typically used by the internals but may be exposed within
  184. certain API features.
  185. """
  186. MANYTOONE = 2
  187. """Indicates the many-to-one direction for a :func:`_orm.relationship`.
  188. This symbol is typically used by the internals but may be exposed within
  189. certain API features.
  190. """
  191. MANYTOMANY = 3
  192. """Indicates the many-to-many direction for a :func:`_orm.relationship`.
  193. This symbol is typically used by the internals but may be exposed within
  194. certain API features.
  195. """
  196. ONETOMANY, MANYTOONE, MANYTOMANY = tuple(RelationshipDirection)
  197. class InspectionAttrExtensionType(Enum):
  198. """Symbols indicating the type of extension that a
  199. :class:`.InspectionAttr` is part of."""
  200. class NotExtension(InspectionAttrExtensionType):
  201. NOT_EXTENSION = "not_extension"
  202. """Symbol indicating an :class:`InspectionAttr` that's
  203. not part of sqlalchemy.ext.
  204. Is assigned to the :attr:`.InspectionAttr.extension_type`
  205. attribute.
  206. """
  207. _never_set = frozenset([NEVER_SET])
  208. _none_set = frozenset([None, NEVER_SET, PASSIVE_NO_RESULT])
  209. _SET_DEFERRED_EXPIRED = util.symbol("SET_DEFERRED_EXPIRED")
  210. _DEFER_FOR_STATE = util.symbol("DEFER_FOR_STATE")
  211. _RAISE_FOR_STATE = util.symbol("RAISE_FOR_STATE")
  212. _F = TypeVar("_F", bound=Callable[..., Any])
  213. _Self = TypeVar("_Self")
  214. def _assertions(
  215. *assertions: Any,
  216. ) -> Callable[[_F], _F]:
  217. @util.decorator
  218. def generate(fn: _F, self: _Self, *args: Any, **kw: Any) -> _Self:
  219. for assertion in assertions:
  220. assertion(self, fn.__name__)
  221. fn(self, *args, **kw)
  222. return self
  223. return generate
  224. if TYPE_CHECKING:
  225. def manager_of_class(cls: Type[_O]) -> ClassManager[_O]:
  226. ...
  227. @overload
  228. def opt_manager_of_class(cls: AliasedClass[Any]) -> None:
  229. ...
  230. @overload
  231. def opt_manager_of_class(
  232. cls: _ExternalEntityType[_O],
  233. ) -> Optional[ClassManager[_O]]:
  234. ...
  235. def opt_manager_of_class(
  236. cls: _ExternalEntityType[_O],
  237. ) -> Optional[ClassManager[_O]]:
  238. ...
  239. def instance_state(instance: _O) -> InstanceState[_O]:
  240. ...
  241. def instance_dict(instance: object) -> Dict[str, Any]:
  242. ...
  243. else:
  244. # these can be replaced by sqlalchemy.ext.instrumentation
  245. # if augmented class instrumentation is enabled.
  246. def manager_of_class(cls):
  247. try:
  248. return cls.__dict__[DEFAULT_MANAGER_ATTR]
  249. except KeyError as ke:
  250. raise exc.UnmappedClassError(
  251. cls, f"Can't locate an instrumentation manager for class {cls}"
  252. ) from ke
  253. def opt_manager_of_class(cls):
  254. return cls.__dict__.get(DEFAULT_MANAGER_ATTR)
  255. instance_state = operator.attrgetter(DEFAULT_STATE_ATTR)
  256. instance_dict = operator.attrgetter("__dict__")
  257. def instance_str(instance: object) -> str:
  258. """Return a string describing an instance."""
  259. return state_str(instance_state(instance))
  260. def state_str(state: InstanceState[Any]) -> str:
  261. """Return a string describing an instance via its InstanceState."""
  262. if state is None:
  263. return "None"
  264. else:
  265. return "<%s at 0x%x>" % (state.class_.__name__, id(state.obj()))
  266. def state_class_str(state: InstanceState[Any]) -> str:
  267. """Return a string describing an instance's class via its
  268. InstanceState.
  269. """
  270. if state is None:
  271. return "None"
  272. else:
  273. return "<%s>" % (state.class_.__name__,)
  274. def attribute_str(instance: object, attribute: str) -> str:
  275. return instance_str(instance) + "." + attribute
  276. def state_attribute_str(state: InstanceState[Any], attribute: str) -> str:
  277. return state_str(state) + "." + attribute
  278. def object_mapper(instance: _T) -> Mapper[_T]:
  279. """Given an object, return the primary Mapper associated with the object
  280. instance.
  281. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError`
  282. if no mapping is configured.
  283. This function is available via the inspection system as::
  284. inspect(instance).mapper
  285. Using the inspection system will raise
  286. :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is
  287. not part of a mapping.
  288. """
  289. return object_state(instance).mapper
  290. def object_state(instance: _T) -> InstanceState[_T]:
  291. """Given an object, return the :class:`.InstanceState`
  292. associated with the object.
  293. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError`
  294. if no mapping is configured.
  295. Equivalent functionality is available via the :func:`_sa.inspect`
  296. function as::
  297. inspect(instance)
  298. Using the inspection system will raise
  299. :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is
  300. not part of a mapping.
  301. """
  302. state = _inspect_mapped_object(instance)
  303. if state is None:
  304. raise exc.UnmappedInstanceError(instance)
  305. else:
  306. return state
  307. @inspection._inspects(object)
  308. def _inspect_mapped_object(instance: _T) -> Optional[InstanceState[_T]]:
  309. try:
  310. return instance_state(instance)
  311. except (exc.UnmappedClassError,) + exc.NO_STATE:
  312. return None
  313. def _class_to_mapper(
  314. class_or_mapper: Union[Mapper[_T], Type[_T]]
  315. ) -> Mapper[_T]:
  316. # can't get mypy to see an overload for this
  317. insp = inspection.inspect(class_or_mapper, False)
  318. if insp is not None:
  319. return insp.mapper # type: ignore
  320. else:
  321. assert isinstance(class_or_mapper, type)
  322. raise exc.UnmappedClassError(class_or_mapper)
  323. def _mapper_or_none(
  324. entity: Union[Type[_T], _InternalEntityType[_T]]
  325. ) -> Optional[Mapper[_T]]:
  326. """Return the :class:`_orm.Mapper` for the given class or None if the
  327. class is not mapped.
  328. """
  329. # can't get mypy to see an overload for this
  330. insp = inspection.inspect(entity, False)
  331. if insp is not None:
  332. return insp.mapper # type: ignore
  333. else:
  334. return None
  335. def _is_mapped_class(entity: Any) -> bool:
  336. """Return True if the given object is a mapped class,
  337. :class:`_orm.Mapper`, or :class:`.AliasedClass`.
  338. """
  339. insp = inspection.inspect(entity, False)
  340. return (
  341. insp is not None
  342. and not insp.is_clause_element
  343. and (insp.is_mapper or insp.is_aliased_class)
  344. )
  345. def _is_aliased_class(entity: Any) -> bool:
  346. insp = inspection.inspect(entity, False)
  347. return insp is not None and getattr(insp, "is_aliased_class", False)
  348. @no_type_check
  349. def _entity_descriptor(entity: _EntityType[Any], key: str) -> Any:
  350. """Return a class attribute given an entity and string name.
  351. May return :class:`.InstrumentedAttribute` or user-defined
  352. attribute.
  353. """
  354. insp = inspection.inspect(entity)
  355. if insp.is_selectable:
  356. description = entity
  357. entity = insp.c
  358. elif insp.is_aliased_class:
  359. entity = insp.entity
  360. description = entity
  361. elif hasattr(insp, "mapper"):
  362. description = entity = insp.mapper.class_
  363. else:
  364. description = entity
  365. try:
  366. return getattr(entity, key)
  367. except AttributeError as err:
  368. raise sa_exc.InvalidRequestError(
  369. "Entity '%s' has no property '%s'" % (description, key)
  370. ) from err
  371. if TYPE_CHECKING:
  372. def _state_mapper(state: InstanceState[_O]) -> Mapper[_O]:
  373. ...
  374. else:
  375. _state_mapper = util.dottedgetter("manager.mapper")
  376. def _inspect_mapped_class(
  377. class_: Type[_O], configure: bool = False
  378. ) -> Optional[Mapper[_O]]:
  379. try:
  380. class_manager = opt_manager_of_class(class_)
  381. if class_manager is None or not class_manager.is_mapped:
  382. return None
  383. mapper = class_manager.mapper
  384. except exc.NO_STATE:
  385. return None
  386. else:
  387. if configure:
  388. mapper._check_configure()
  389. return mapper
  390. def _parse_mapper_argument(arg: Union[Mapper[_O], Type[_O]]) -> Mapper[_O]:
  391. insp = inspection.inspect(arg, raiseerr=False)
  392. if insp_is_mapper(insp):
  393. return insp
  394. raise sa_exc.ArgumentError(f"Mapper or mapped class expected, got {arg!r}")
  395. def class_mapper(class_: Type[_O], configure: bool = True) -> Mapper[_O]:
  396. """Given a class, return the primary :class:`_orm.Mapper` associated
  397. with the key.
  398. Raises :exc:`.UnmappedClassError` if no mapping is configured
  399. on the given class, or :exc:`.ArgumentError` if a non-class
  400. object is passed.
  401. Equivalent functionality is available via the :func:`_sa.inspect`
  402. function as::
  403. inspect(some_mapped_class)
  404. Using the inspection system will raise
  405. :class:`sqlalchemy.exc.NoInspectionAvailable` if the class is not mapped.
  406. """
  407. mapper = _inspect_mapped_class(class_, configure=configure)
  408. if mapper is None:
  409. if not isinstance(class_, type):
  410. raise sa_exc.ArgumentError(
  411. "Class object expected, got '%r'." % (class_,)
  412. )
  413. raise exc.UnmappedClassError(class_)
  414. else:
  415. return mapper
  416. class InspectionAttr:
  417. """A base class applied to all ORM objects and attributes that are
  418. related to things that can be returned by the :func:`_sa.inspect` function.
  419. The attributes defined here allow the usage of simple boolean
  420. checks to test basic facts about the object returned.
  421. While the boolean checks here are basically the same as using
  422. the Python isinstance() function, the flags here can be used without
  423. the need to import all of these classes, and also such that
  424. the SQLAlchemy class system can change while leaving the flags
  425. here intact for forwards-compatibility.
  426. """
  427. __slots__ = ()
  428. is_selectable = False
  429. """Return True if this object is an instance of
  430. :class:`_expression.Selectable`."""
  431. is_aliased_class = False
  432. """True if this object is an instance of :class:`.AliasedClass`."""
  433. is_instance = False
  434. """True if this object is an instance of :class:`.InstanceState`."""
  435. is_mapper = False
  436. """True if this object is an instance of :class:`_orm.Mapper`."""
  437. is_bundle = False
  438. """True if this object is an instance of :class:`.Bundle`."""
  439. is_property = False
  440. """True if this object is an instance of :class:`.MapperProperty`."""
  441. is_attribute = False
  442. """True if this object is a Python :term:`descriptor`.
  443. This can refer to one of many types. Usually a
  444. :class:`.QueryableAttribute` which handles attributes events on behalf
  445. of a :class:`.MapperProperty`. But can also be an extension type
  446. such as :class:`.AssociationProxy` or :class:`.hybrid_property`.
  447. The :attr:`.InspectionAttr.extension_type` will refer to a constant
  448. identifying the specific subtype.
  449. .. seealso::
  450. :attr:`_orm.Mapper.all_orm_descriptors`
  451. """
  452. _is_internal_proxy = False
  453. """True if this object is an internal proxy object.
  454. .. versionadded:: 1.2.12
  455. """
  456. is_clause_element = False
  457. """True if this object is an instance of
  458. :class:`_expression.ClauseElement`."""
  459. extension_type: InspectionAttrExtensionType = NotExtension.NOT_EXTENSION
  460. """The extension type, if any.
  461. Defaults to :attr:`.interfaces.NotExtension.NOT_EXTENSION`
  462. .. seealso::
  463. :class:`.HybridExtensionType`
  464. :class:`.AssociationProxyExtensionType`
  465. """
  466. class InspectionAttrInfo(InspectionAttr):
  467. """Adds the ``.info`` attribute to :class:`.InspectionAttr`.
  468. The rationale for :class:`.InspectionAttr` vs. :class:`.InspectionAttrInfo`
  469. is that the former is compatible as a mixin for classes that specify
  470. ``__slots__``; this is essentially an implementation artifact.
  471. """
  472. __slots__ = ()
  473. @util.ro_memoized_property
  474. def info(self) -> _InfoType:
  475. """Info dictionary associated with the object, allowing user-defined
  476. data to be associated with this :class:`.InspectionAttr`.
  477. The dictionary is generated when first accessed. Alternatively,
  478. it can be specified as a constructor argument to the
  479. :func:`.column_property`, :func:`_orm.relationship`, or
  480. :func:`.composite`
  481. functions.
  482. .. seealso::
  483. :attr:`.QueryableAttribute.info`
  484. :attr:`.SchemaItem.info`
  485. """
  486. return {}
  487. class SQLORMOperations(SQLCoreOperations[_T_co], TypingOnly):
  488. __slots__ = ()
  489. if typing.TYPE_CHECKING:
  490. def of_type(self, class_: _EntityType[Any]) -> PropComparator[_T_co]:
  491. ...
  492. def and_(
  493. self, *criteria: _ColumnExpressionArgument[bool]
  494. ) -> PropComparator[bool]:
  495. ...
  496. def any( # noqa: A001
  497. self,
  498. criterion: Optional[_ColumnExpressionArgument[bool]] = None,
  499. **kwargs: Any,
  500. ) -> ColumnElement[bool]:
  501. ...
  502. def has(
  503. self,
  504. criterion: Optional[_ColumnExpressionArgument[bool]] = None,
  505. **kwargs: Any,
  506. ) -> ColumnElement[bool]:
  507. ...
  508. class ORMDescriptor(Generic[_T_co], TypingOnly):
  509. """Represent any Python descriptor that provides a SQL expression
  510. construct at the class level."""
  511. __slots__ = ()
  512. if typing.TYPE_CHECKING:
  513. @overload
  514. def __get__(
  515. self, instance: Any, owner: Literal[None]
  516. ) -> ORMDescriptor[_T_co]:
  517. ...
  518. @overload
  519. def __get__(
  520. self, instance: Literal[None], owner: Any
  521. ) -> SQLCoreOperations[_T_co]:
  522. ...
  523. @overload
  524. def __get__(self, instance: object, owner: Any) -> _T_co:
  525. ...
  526. def __get__(
  527. self, instance: object, owner: Any
  528. ) -> Union[ORMDescriptor[_T_co], SQLCoreOperations[_T_co], _T_co]:
  529. ...
  530. class _MappedAnnotationBase(Generic[_T_co], TypingOnly):
  531. """common class for Mapped and similar ORM container classes.
  532. these are classes that can appear on the left side of an ORM declarative
  533. mapping, containing a mapped class or in some cases a collection
  534. surrounding a mapped class.
  535. """
  536. __slots__ = ()
  537. class SQLORMExpression(
  538. SQLORMOperations[_T_co], SQLColumnExpression[_T_co], TypingOnly
  539. ):
  540. """A type that may be used to indicate any ORM-level attribute or
  541. object that acts in place of one, in the context of SQL expression
  542. construction.
  543. :class:`.SQLORMExpression` extends from the Core
  544. :class:`.SQLColumnExpression` to add additional SQL methods that are ORM
  545. specific, such as :meth:`.PropComparator.of_type`, and is part of the bases
  546. for :class:`.InstrumentedAttribute`. It may be used in :pep:`484` typing to
  547. indicate arguments or return values that should behave as ORM-level
  548. attribute expressions.
  549. .. versionadded:: 2.0.0b4
  550. """
  551. __slots__ = ()
  552. class Mapped(
  553. SQLORMExpression[_T_co],
  554. ORMDescriptor[_T_co],
  555. _MappedAnnotationBase[_T_co],
  556. roles.DDLConstraintColumnRole,
  557. ):
  558. """Represent an ORM mapped attribute on a mapped class.
  559. This class represents the complete descriptor interface for any class
  560. attribute that will have been :term:`instrumented` by the ORM
  561. :class:`_orm.Mapper` class. Provides appropriate information to type
  562. checkers such as pylance and mypy so that ORM-mapped attributes
  563. are correctly typed.
  564. The most prominent use of :class:`_orm.Mapped` is in
  565. the :ref:`Declarative Mapping <orm_explicit_declarative_base>` form
  566. of :class:`_orm.Mapper` configuration, where used explicitly it drives
  567. the configuration of ORM attributes such as :func:`_orm.mapped_class`
  568. and :func:`_orm.relationship`.
  569. .. seealso::
  570. :ref:`orm_explicit_declarative_base`
  571. :ref:`orm_declarative_table`
  572. .. tip::
  573. The :class:`_orm.Mapped` class represents attributes that are handled
  574. directly by the :class:`_orm.Mapper` class. It does not include other
  575. Python descriptor classes that are provided as extensions, including
  576. :ref:`hybrids_toplevel` and the :ref:`associationproxy_toplevel`.
  577. While these systems still make use of ORM-specific superclasses
  578. and structures, they are not :term:`instrumented` by the
  579. :class:`_orm.Mapper` and instead provide their own functionality
  580. when they are accessed on a class.
  581. .. versionadded:: 1.4
  582. """
  583. __slots__ = ()
  584. if typing.TYPE_CHECKING:
  585. @overload
  586. def __get__(
  587. self, instance: None, owner: Any
  588. ) -> InstrumentedAttribute[_T_co]:
  589. ...
  590. @overload
  591. def __get__(self, instance: object, owner: Any) -> _T_co:
  592. ...
  593. def __get__(
  594. self, instance: Optional[object], owner: Any
  595. ) -> Union[InstrumentedAttribute[_T_co], _T_co]:
  596. ...
  597. @classmethod
  598. def _empty_constructor(cls, arg1: Any) -> Mapped[_T_co]:
  599. ...
  600. def __set__(
  601. self, instance: Any, value: Union[SQLCoreOperations[_T_co], _T_co]
  602. ) -> None:
  603. ...
  604. def __delete__(self, instance: Any) -> None:
  605. ...
  606. class _MappedAttribute(Generic[_T_co], TypingOnly):
  607. """Mixin for attributes which should be replaced by mapper-assigned
  608. attributes.
  609. """
  610. __slots__ = ()
  611. class _DeclarativeMapped(Mapped[_T_co], _MappedAttribute[_T_co]):
  612. """Mixin for :class:`.MapperProperty` subclasses that allows them to
  613. be compatible with ORM-annotated declarative mappings.
  614. """
  615. __slots__ = ()
  616. # MappedSQLExpression, Relationship, Composite etc. dont actually do
  617. # SQL expression behavior. yet there is code that compares them with
  618. # __eq__(), __ne__(), etc. Since #8847 made Mapped even more full
  619. # featured including ColumnOperators, we need to have those methods
  620. # be no-ops for these objects, so return NotImplemented to fall back
  621. # to normal comparison behavior.
  622. def operate(self, op: OperatorType, *other: Any, **kwargs: Any) -> Any:
  623. return NotImplemented
  624. __sa_operate__ = operate
  625. def reverse_operate(
  626. self, op: OperatorType, other: Any, **kwargs: Any
  627. ) -> Any:
  628. return NotImplemented
  629. class DynamicMapped(_MappedAnnotationBase[_T_co]):
  630. """Represent the ORM mapped attribute type for a "dynamic" relationship.
  631. The :class:`_orm.DynamicMapped` type annotation may be used in an
  632. :ref:`Annotated Declarative Table <orm_declarative_mapped_column>` mapping
  633. to indicate that the ``lazy="dynamic"`` loader strategy should be used
  634. for a particular :func:`_orm.relationship`.
  635. .. legacy:: The "dynamic" lazy loader strategy is the legacy form of what
  636. is now the "write_only" strategy described in the section
  637. :ref:`write_only_relationship`.
  638. E.g.::
  639. class User(Base):
  640. __tablename__ = "user"
  641. id: Mapped[int] = mapped_column(primary_key=True)
  642. addresses: DynamicMapped[Address] = relationship(
  643. cascade="all,delete-orphan"
  644. )
  645. See the section :ref:`dynamic_relationship` for background.
  646. .. versionadded:: 2.0
  647. .. seealso::
  648. :ref:`dynamic_relationship` - complete background
  649. :class:`.WriteOnlyMapped` - fully 2.0 style version
  650. """
  651. __slots__ = ()
  652. if TYPE_CHECKING:
  653. @overload
  654. def __get__(
  655. self, instance: None, owner: Any
  656. ) -> InstrumentedAttribute[_T_co]:
  657. ...
  658. @overload
  659. def __get__(
  660. self, instance: object, owner: Any
  661. ) -> AppenderQuery[_T_co]:
  662. ...
  663. def __get__(
  664. self, instance: Optional[object], owner: Any
  665. ) -> Union[InstrumentedAttribute[_T_co], AppenderQuery[_T_co]]:
  666. ...
  667. def __set__(
  668. self, instance: Any, value: typing.Collection[_T_co]
  669. ) -> None:
  670. ...
  671. class WriteOnlyMapped(_MappedAnnotationBase[_T_co]):
  672. """Represent the ORM mapped attribute type for a "write only" relationship.
  673. The :class:`_orm.WriteOnlyMapped` type annotation may be used in an
  674. :ref:`Annotated Declarative Table <orm_declarative_mapped_column>` mapping
  675. to indicate that the ``lazy="write_only"`` loader strategy should be used
  676. for a particular :func:`_orm.relationship`.
  677. E.g.::
  678. class User(Base):
  679. __tablename__ = "user"
  680. id: Mapped[int] = mapped_column(primary_key=True)
  681. addresses: WriteOnlyMapped[Address] = relationship(
  682. cascade="all,delete-orphan"
  683. )
  684. See the section :ref:`write_only_relationship` for background.
  685. .. versionadded:: 2.0
  686. .. seealso::
  687. :ref:`write_only_relationship` - complete background
  688. :class:`.DynamicMapped` - includes legacy :class:`_orm.Query` support
  689. """
  690. __slots__ = ()
  691. if TYPE_CHECKING:
  692. @overload
  693. def __get__(
  694. self, instance: None, owner: Any
  695. ) -> InstrumentedAttribute[_T_co]:
  696. ...
  697. @overload
  698. def __get__(
  699. self, instance: object, owner: Any
  700. ) -> WriteOnlyCollection[_T_co]:
  701. ...
  702. def __get__(
  703. self, instance: Optional[object], owner: Any
  704. ) -> Union[InstrumentedAttribute[_T_co], WriteOnlyCollection[_T_co]]:
  705. ...
  706. def __set__(
  707. self, instance: Any, value: typing.Collection[_T_co]
  708. ) -> None:
  709. ...