base.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. # orm/base.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. """Constants and rudimental functions used throughout the ORM."""
  8. from __future__ import annotations
  9. from enum import Enum
  10. import operator
  11. import typing
  12. from typing import Any
  13. from typing import Callable
  14. from typing import Dict
  15. from typing import Generic
  16. from typing import no_type_check
  17. from typing import Optional
  18. from typing import overload
  19. from typing import Tuple
  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. _none_only_set = frozenset([None])
  210. _SET_DEFERRED_EXPIRED = util.symbol("SET_DEFERRED_EXPIRED")
  211. _DEFER_FOR_STATE = util.symbol("DEFER_FOR_STATE")
  212. _RAISE_FOR_STATE = util.symbol("RAISE_FOR_STATE")
  213. _F = TypeVar("_F", bound=Callable[..., Any])
  214. _Self = TypeVar("_Self")
  215. def _assertions(
  216. *assertions: Any,
  217. ) -> Callable[[_F], _F]:
  218. @util.decorator
  219. def generate(fn: _F, self: _Self, *args: Any, **kw: Any) -> _Self:
  220. for assertion in assertions:
  221. assertion(self, fn.__name__)
  222. fn(self, *args, **kw)
  223. return self
  224. return generate
  225. if TYPE_CHECKING:
  226. def manager_of_class(cls: Type[_O]) -> ClassManager[_O]: ...
  227. @overload
  228. def opt_manager_of_class(cls: AliasedClass[Any]) -> None: ...
  229. @overload
  230. def opt_manager_of_class(
  231. cls: _ExternalEntityType[_O],
  232. ) -> Optional[ClassManager[_O]]: ...
  233. def opt_manager_of_class(
  234. cls: _ExternalEntityType[_O],
  235. ) -> Optional[ClassManager[_O]]: ...
  236. def instance_state(instance: _O) -> InstanceState[_O]: ...
  237. def instance_dict(instance: object) -> Dict[str, Any]: ...
  238. else:
  239. # these can be replaced by sqlalchemy.ext.instrumentation
  240. # if augmented class instrumentation is enabled.
  241. def manager_of_class(cls):
  242. try:
  243. return cls.__dict__[DEFAULT_MANAGER_ATTR]
  244. except KeyError as ke:
  245. raise exc.UnmappedClassError(
  246. cls, f"Can't locate an instrumentation manager for class {cls}"
  247. ) from ke
  248. def opt_manager_of_class(cls):
  249. return cls.__dict__.get(DEFAULT_MANAGER_ATTR)
  250. instance_state = operator.attrgetter(DEFAULT_STATE_ATTR)
  251. instance_dict = operator.attrgetter("__dict__")
  252. def instance_str(instance: object) -> str:
  253. """Return a string describing an instance."""
  254. return state_str(instance_state(instance))
  255. def state_str(state: InstanceState[Any]) -> str:
  256. """Return a string describing an instance via its InstanceState."""
  257. if state is None:
  258. return "None"
  259. else:
  260. return "<%s at 0x%x>" % (state.class_.__name__, id(state.obj()))
  261. def state_class_str(state: InstanceState[Any]) -> str:
  262. """Return a string describing an instance's class via its
  263. InstanceState.
  264. """
  265. if state is None:
  266. return "None"
  267. else:
  268. return "<%s>" % (state.class_.__name__,)
  269. def attribute_str(instance: object, attribute: str) -> str:
  270. return instance_str(instance) + "." + attribute
  271. def state_attribute_str(state: InstanceState[Any], attribute: str) -> str:
  272. return state_str(state) + "." + attribute
  273. def object_mapper(instance: _T) -> Mapper[_T]:
  274. """Given an object, return the primary Mapper associated with the object
  275. instance.
  276. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError`
  277. if no mapping is configured.
  278. This function is available via the inspection system as::
  279. inspect(instance).mapper
  280. Using the inspection system will raise
  281. :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is
  282. not part of a mapping.
  283. """
  284. return object_state(instance).mapper
  285. def object_state(instance: _T) -> InstanceState[_T]:
  286. """Given an object, return the :class:`.InstanceState`
  287. associated with the object.
  288. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError`
  289. if no mapping is configured.
  290. Equivalent functionality is available via the :func:`_sa.inspect`
  291. function as::
  292. inspect(instance)
  293. Using the inspection system will raise
  294. :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is
  295. not part of a mapping.
  296. """
  297. state = _inspect_mapped_object(instance)
  298. if state is None:
  299. raise exc.UnmappedInstanceError(instance)
  300. else:
  301. return state
  302. @inspection._inspects(object)
  303. def _inspect_mapped_object(instance: _T) -> Optional[InstanceState[_T]]:
  304. try:
  305. return instance_state(instance)
  306. except (exc.UnmappedClassError,) + exc.NO_STATE:
  307. return None
  308. def _class_to_mapper(
  309. class_or_mapper: Union[Mapper[_T], Type[_T]],
  310. ) -> Mapper[_T]:
  311. # can't get mypy to see an overload for this
  312. insp = inspection.inspect(class_or_mapper, False)
  313. if insp is not None:
  314. return insp.mapper # type: ignore
  315. else:
  316. assert isinstance(class_or_mapper, type)
  317. raise exc.UnmappedClassError(class_or_mapper)
  318. def _mapper_or_none(
  319. entity: Union[Type[_T], _InternalEntityType[_T]],
  320. ) -> Optional[Mapper[_T]]:
  321. """Return the :class:`_orm.Mapper` for the given class or None if the
  322. class is not mapped.
  323. """
  324. # can't get mypy to see an overload for this
  325. insp = inspection.inspect(entity, False)
  326. if insp is not None:
  327. return insp.mapper # type: ignore
  328. else:
  329. return None
  330. def _is_mapped_class(entity: Any) -> bool:
  331. """Return True if the given object is a mapped class,
  332. :class:`_orm.Mapper`, or :class:`.AliasedClass`.
  333. """
  334. insp = inspection.inspect(entity, False)
  335. return (
  336. insp is not None
  337. and not insp.is_clause_element
  338. and (insp.is_mapper or insp.is_aliased_class)
  339. )
  340. def _is_aliased_class(entity: Any) -> bool:
  341. insp = inspection.inspect(entity, False)
  342. return insp is not None and getattr(insp, "is_aliased_class", False)
  343. @no_type_check
  344. def _entity_descriptor(entity: _EntityType[Any], key: str) -> Any:
  345. """Return a class attribute given an entity and string name.
  346. May return :class:`.InstrumentedAttribute` or user-defined
  347. attribute.
  348. """
  349. insp = inspection.inspect(entity)
  350. if insp.is_selectable:
  351. description = entity
  352. entity = insp.c
  353. elif insp.is_aliased_class:
  354. entity = insp.entity
  355. description = entity
  356. elif hasattr(insp, "mapper"):
  357. description = entity = insp.mapper.class_
  358. else:
  359. description = entity
  360. try:
  361. return getattr(entity, key)
  362. except AttributeError as err:
  363. raise sa_exc.InvalidRequestError(
  364. "Entity '%s' has no property '%s'" % (description, key)
  365. ) from err
  366. if TYPE_CHECKING:
  367. def _state_mapper(state: InstanceState[_O]) -> Mapper[_O]: ...
  368. else:
  369. _state_mapper = util.dottedgetter("manager.mapper")
  370. def _inspect_mapped_class(
  371. class_: Type[_O], configure: bool = False
  372. ) -> Optional[Mapper[_O]]:
  373. try:
  374. class_manager = opt_manager_of_class(class_)
  375. if class_manager is None or not class_manager.is_mapped:
  376. return None
  377. mapper = class_manager.mapper
  378. except exc.NO_STATE:
  379. return None
  380. else:
  381. if configure:
  382. mapper._check_configure()
  383. return mapper
  384. def _parse_mapper_argument(arg: Union[Mapper[_O], Type[_O]]) -> Mapper[_O]:
  385. insp = inspection.inspect(arg, raiseerr=False)
  386. if insp_is_mapper(insp):
  387. return insp
  388. raise sa_exc.ArgumentError(f"Mapper or mapped class expected, got {arg!r}")
  389. def class_mapper(class_: Type[_O], configure: bool = True) -> Mapper[_O]:
  390. """Given a class, return the primary :class:`_orm.Mapper` associated
  391. with the key.
  392. Raises :exc:`.UnmappedClassError` if no mapping is configured
  393. on the given class, or :exc:`.ArgumentError` if a non-class
  394. object is passed.
  395. Equivalent functionality is available via the :func:`_sa.inspect`
  396. function as::
  397. inspect(some_mapped_class)
  398. Using the inspection system will raise
  399. :class:`sqlalchemy.exc.NoInspectionAvailable` if the class is not mapped.
  400. """
  401. mapper = _inspect_mapped_class(class_, configure=configure)
  402. if mapper is None:
  403. if not isinstance(class_, type):
  404. raise sa_exc.ArgumentError(
  405. "Class object expected, got '%r'." % (class_,)
  406. )
  407. raise exc.UnmappedClassError(class_)
  408. else:
  409. return mapper
  410. class InspectionAttr:
  411. """A base class applied to all ORM objects and attributes that are
  412. related to things that can be returned by the :func:`_sa.inspect` function.
  413. The attributes defined here allow the usage of simple boolean
  414. checks to test basic facts about the object returned.
  415. While the boolean checks here are basically the same as using
  416. the Python isinstance() function, the flags here can be used without
  417. the need to import all of these classes, and also such that
  418. the SQLAlchemy class system can change while leaving the flags
  419. here intact for forwards-compatibility.
  420. """
  421. __slots__: Tuple[str, ...] = ()
  422. is_selectable = False
  423. """Return True if this object is an instance of
  424. :class:`_expression.Selectable`."""
  425. is_aliased_class = False
  426. """True if this object is an instance of :class:`.AliasedClass`."""
  427. is_instance = False
  428. """True if this object is an instance of :class:`.InstanceState`."""
  429. is_mapper = False
  430. """True if this object is an instance of :class:`_orm.Mapper`."""
  431. is_bundle = False
  432. """True if this object is an instance of :class:`.Bundle`."""
  433. is_property = False
  434. """True if this object is an instance of :class:`.MapperProperty`."""
  435. is_attribute = False
  436. """True if this object is a Python :term:`descriptor`.
  437. This can refer to one of many types. Usually a
  438. :class:`.QueryableAttribute` which handles attributes events on behalf
  439. of a :class:`.MapperProperty`. But can also be an extension type
  440. such as :class:`.AssociationProxy` or :class:`.hybrid_property`.
  441. The :attr:`.InspectionAttr.extension_type` will refer to a constant
  442. identifying the specific subtype.
  443. .. seealso::
  444. :attr:`_orm.Mapper.all_orm_descriptors`
  445. """
  446. _is_internal_proxy = False
  447. """True if this object is an internal proxy object.
  448. .. versionadded:: 1.2.12
  449. """
  450. is_clause_element = False
  451. """True if this object is an instance of
  452. :class:`_expression.ClauseElement`."""
  453. extension_type: InspectionAttrExtensionType = NotExtension.NOT_EXTENSION
  454. """The extension type, if any.
  455. Defaults to :attr:`.interfaces.NotExtension.NOT_EXTENSION`
  456. .. seealso::
  457. :class:`.HybridExtensionType`
  458. :class:`.AssociationProxyExtensionType`
  459. """
  460. class InspectionAttrInfo(InspectionAttr):
  461. """Adds the ``.info`` attribute to :class:`.InspectionAttr`.
  462. The rationale for :class:`.InspectionAttr` vs. :class:`.InspectionAttrInfo`
  463. is that the former is compatible as a mixin for classes that specify
  464. ``__slots__``; this is essentially an implementation artifact.
  465. """
  466. __slots__ = ()
  467. @util.ro_memoized_property
  468. def info(self) -> _InfoType:
  469. """Info dictionary associated with the object, allowing user-defined
  470. data to be associated with this :class:`.InspectionAttr`.
  471. The dictionary is generated when first accessed. Alternatively,
  472. it can be specified as a constructor argument to the
  473. :func:`.column_property`, :func:`_orm.relationship`, or
  474. :func:`.composite`
  475. functions.
  476. .. seealso::
  477. :attr:`.QueryableAttribute.info`
  478. :attr:`.SchemaItem.info`
  479. """
  480. return {}
  481. class SQLORMOperations(SQLCoreOperations[_T_co], TypingOnly):
  482. __slots__ = ()
  483. if typing.TYPE_CHECKING:
  484. def of_type(
  485. self, class_: _EntityType[Any]
  486. ) -> PropComparator[_T_co]: ...
  487. def and_(
  488. self, *criteria: _ColumnExpressionArgument[bool]
  489. ) -> PropComparator[bool]: ...
  490. def any( # noqa: A001
  491. self,
  492. criterion: Optional[_ColumnExpressionArgument[bool]] = None,
  493. **kwargs: Any,
  494. ) -> ColumnElement[bool]: ...
  495. def has(
  496. self,
  497. criterion: Optional[_ColumnExpressionArgument[bool]] = None,
  498. **kwargs: Any,
  499. ) -> ColumnElement[bool]: ...
  500. class ORMDescriptor(Generic[_T_co], TypingOnly):
  501. """Represent any Python descriptor that provides a SQL expression
  502. construct at the class level."""
  503. __slots__ = ()
  504. if typing.TYPE_CHECKING:
  505. @overload
  506. def __get__(
  507. self, instance: Any, owner: Literal[None]
  508. ) -> ORMDescriptor[_T_co]: ...
  509. @overload
  510. def __get__(
  511. self, instance: Literal[None], owner: Any
  512. ) -> SQLCoreOperations[_T_co]: ...
  513. @overload
  514. def __get__(self, instance: object, owner: Any) -> _T_co: ...
  515. def __get__(
  516. self, instance: object, owner: Any
  517. ) -> Union[ORMDescriptor[_T_co], SQLCoreOperations[_T_co], _T_co]: ...
  518. class _MappedAnnotationBase(Generic[_T_co], TypingOnly):
  519. """common class for Mapped and similar ORM container classes.
  520. these are classes that can appear on the left side of an ORM declarative
  521. mapping, containing a mapped class or in some cases a collection
  522. surrounding a mapped class.
  523. """
  524. __slots__ = ()
  525. class SQLORMExpression(
  526. SQLORMOperations[_T_co], SQLColumnExpression[_T_co], TypingOnly
  527. ):
  528. """A type that may be used to indicate any ORM-level attribute or
  529. object that acts in place of one, in the context of SQL expression
  530. construction.
  531. :class:`.SQLORMExpression` extends from the Core
  532. :class:`.SQLColumnExpression` to add additional SQL methods that are ORM
  533. specific, such as :meth:`.PropComparator.of_type`, and is part of the bases
  534. for :class:`.InstrumentedAttribute`. It may be used in :pep:`484` typing to
  535. indicate arguments or return values that should behave as ORM-level
  536. attribute expressions.
  537. .. versionadded:: 2.0.0b4
  538. """
  539. __slots__ = ()
  540. class Mapped(
  541. SQLORMExpression[_T_co],
  542. ORMDescriptor[_T_co],
  543. _MappedAnnotationBase[_T_co],
  544. roles.DDLConstraintColumnRole,
  545. ):
  546. """Represent an ORM mapped attribute on a mapped class.
  547. This class represents the complete descriptor interface for any class
  548. attribute that will have been :term:`instrumented` by the ORM
  549. :class:`_orm.Mapper` class. Provides appropriate information to type
  550. checkers such as pylance and mypy so that ORM-mapped attributes
  551. are correctly typed.
  552. The most prominent use of :class:`_orm.Mapped` is in
  553. the :ref:`Declarative Mapping <orm_explicit_declarative_base>` form
  554. of :class:`_orm.Mapper` configuration, where used explicitly it drives
  555. the configuration of ORM attributes such as :func:`_orm.mapped_class`
  556. and :func:`_orm.relationship`.
  557. .. seealso::
  558. :ref:`orm_explicit_declarative_base`
  559. :ref:`orm_declarative_table`
  560. .. tip::
  561. The :class:`_orm.Mapped` class represents attributes that are handled
  562. directly by the :class:`_orm.Mapper` class. It does not include other
  563. Python descriptor classes that are provided as extensions, including
  564. :ref:`hybrids_toplevel` and the :ref:`associationproxy_toplevel`.
  565. While these systems still make use of ORM-specific superclasses
  566. and structures, they are not :term:`instrumented` by the
  567. :class:`_orm.Mapper` and instead provide their own functionality
  568. when they are accessed on a class.
  569. .. versionadded:: 1.4
  570. """
  571. __slots__ = ()
  572. if typing.TYPE_CHECKING:
  573. @overload
  574. def __get__(
  575. self, instance: None, owner: Any
  576. ) -> InstrumentedAttribute[_T_co]: ...
  577. @overload
  578. def __get__(self, instance: object, owner: Any) -> _T_co: ...
  579. def __get__(
  580. self, instance: Optional[object], owner: Any
  581. ) -> Union[InstrumentedAttribute[_T_co], _T_co]: ...
  582. @classmethod
  583. def _empty_constructor(cls, arg1: Any) -> Mapped[_T_co]: ...
  584. def __set__(
  585. self, instance: Any, value: Union[SQLCoreOperations[_T_co], _T_co]
  586. ) -> None: ...
  587. def __delete__(self, instance: Any) -> None: ...
  588. class _MappedAttribute(Generic[_T_co], TypingOnly):
  589. """Mixin for attributes which should be replaced by mapper-assigned
  590. attributes.
  591. """
  592. __slots__ = ()
  593. class _DeclarativeMapped(Mapped[_T_co], _MappedAttribute[_T_co]):
  594. """Mixin for :class:`.MapperProperty` subclasses that allows them to
  595. be compatible with ORM-annotated declarative mappings.
  596. """
  597. __slots__ = ()
  598. # MappedSQLExpression, Relationship, Composite etc. dont actually do
  599. # SQL expression behavior. yet there is code that compares them with
  600. # __eq__(), __ne__(), etc. Since #8847 made Mapped even more full
  601. # featured including ColumnOperators, we need to have those methods
  602. # be no-ops for these objects, so return NotImplemented to fall back
  603. # to normal comparison behavior.
  604. def operate(self, op: OperatorType, *other: Any, **kwargs: Any) -> Any:
  605. return NotImplemented
  606. __sa_operate__ = operate
  607. def reverse_operate(
  608. self, op: OperatorType, other: Any, **kwargs: Any
  609. ) -> Any:
  610. return NotImplemented
  611. class DynamicMapped(_MappedAnnotationBase[_T_co]):
  612. """Represent the ORM mapped attribute type for a "dynamic" relationship.
  613. The :class:`_orm.DynamicMapped` type annotation may be used in an
  614. :ref:`Annotated Declarative Table <orm_declarative_mapped_column>` mapping
  615. to indicate that the ``lazy="dynamic"`` loader strategy should be used
  616. for a particular :func:`_orm.relationship`.
  617. .. legacy:: The "dynamic" lazy loader strategy is the legacy form of what
  618. is now the "write_only" strategy described in the section
  619. :ref:`write_only_relationship`.
  620. E.g.::
  621. class User(Base):
  622. __tablename__ = "user"
  623. id: Mapped[int] = mapped_column(primary_key=True)
  624. addresses: DynamicMapped[Address] = relationship(
  625. cascade="all,delete-orphan"
  626. )
  627. See the section :ref:`dynamic_relationship` for background.
  628. .. versionadded:: 2.0
  629. .. seealso::
  630. :ref:`dynamic_relationship` - complete background
  631. :class:`.WriteOnlyMapped` - fully 2.0 style version
  632. """
  633. __slots__ = ()
  634. if TYPE_CHECKING:
  635. @overload
  636. def __get__(
  637. self, instance: None, owner: Any
  638. ) -> InstrumentedAttribute[_T_co]: ...
  639. @overload
  640. def __get__(
  641. self, instance: object, owner: Any
  642. ) -> AppenderQuery[_T_co]: ...
  643. def __get__(
  644. self, instance: Optional[object], owner: Any
  645. ) -> Union[InstrumentedAttribute[_T_co], AppenderQuery[_T_co]]: ...
  646. def __set__(
  647. self, instance: Any, value: typing.Collection[_T_co]
  648. ) -> None: ...
  649. class WriteOnlyMapped(_MappedAnnotationBase[_T_co]):
  650. """Represent the ORM mapped attribute type for a "write only" relationship.
  651. The :class:`_orm.WriteOnlyMapped` type annotation may be used in an
  652. :ref:`Annotated Declarative Table <orm_declarative_mapped_column>` mapping
  653. to indicate that the ``lazy="write_only"`` loader strategy should be used
  654. for a particular :func:`_orm.relationship`.
  655. E.g.::
  656. class User(Base):
  657. __tablename__ = "user"
  658. id: Mapped[int] = mapped_column(primary_key=True)
  659. addresses: WriteOnlyMapped[Address] = relationship(
  660. cascade="all,delete-orphan"
  661. )
  662. See the section :ref:`write_only_relationship` for background.
  663. .. versionadded:: 2.0
  664. .. seealso::
  665. :ref:`write_only_relationship` - complete background
  666. :class:`.DynamicMapped` - includes legacy :class:`_orm.Query` support
  667. """
  668. __slots__ = ()
  669. if TYPE_CHECKING:
  670. @overload
  671. def __get__(
  672. self, instance: None, owner: Any
  673. ) -> InstrumentedAttribute[_T_co]: ...
  674. @overload
  675. def __get__(
  676. self, instance: object, owner: Any
  677. ) -> WriteOnlyCollection[_T_co]: ...
  678. def __get__(
  679. self, instance: Optional[object], owner: Any
  680. ) -> Union[
  681. InstrumentedAttribute[_T_co], WriteOnlyCollection[_T_co]
  682. ]: ...
  683. def __set__(
  684. self, instance: Any, value: typing.Collection[_T_co]
  685. ) -> None: ...