mapped_collection.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. # orm/mapped_collection.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. from __future__ import annotations
  8. import operator
  9. from typing import Any
  10. from typing import Callable
  11. from typing import Dict
  12. from typing import Generic
  13. from typing import List
  14. from typing import Optional
  15. from typing import Sequence
  16. from typing import Tuple
  17. from typing import Type
  18. from typing import TYPE_CHECKING
  19. from typing import TypeVar
  20. from typing import Union
  21. from . import base
  22. from .collections import collection
  23. from .collections import collection_adapter
  24. from .. import exc as sa_exc
  25. from .. import util
  26. from ..sql import coercions
  27. from ..sql import expression
  28. from ..sql import roles
  29. from ..util.typing import Literal
  30. if TYPE_CHECKING:
  31. from . import AttributeEventToken
  32. from . import Mapper
  33. from .collections import CollectionAdapter
  34. from ..sql.elements import ColumnElement
  35. _KT = TypeVar("_KT", bound=Any)
  36. _VT = TypeVar("_VT", bound=Any)
  37. _F = TypeVar("_F", bound=Callable[[Any], Any])
  38. class _PlainColumnGetter(Generic[_KT]):
  39. """Plain column getter, stores collection of Column objects
  40. directly.
  41. Serializes to a :class:`._SerializableColumnGetterV2`
  42. which has more expensive __call__() performance
  43. and some rare caveats.
  44. """
  45. __slots__ = ("cols", "composite")
  46. def __init__(self, cols: Sequence[ColumnElement[_KT]]) -> None:
  47. self.cols = cols
  48. self.composite = len(cols) > 1
  49. def __reduce__(
  50. self,
  51. ) -> Tuple[
  52. Type[_SerializableColumnGetterV2[_KT]],
  53. Tuple[Sequence[Tuple[Optional[str], Optional[str]]]],
  54. ]:
  55. return _SerializableColumnGetterV2._reduce_from_cols(self.cols)
  56. def _cols(self, mapper: Mapper[_KT]) -> Sequence[ColumnElement[_KT]]:
  57. return self.cols
  58. def __call__(self, value: _KT) -> Union[_KT, Tuple[_KT, ...]]:
  59. state = base.instance_state(value)
  60. m = base._state_mapper(state)
  61. key: List[_KT] = [
  62. m._get_state_attr_by_column(state, state.dict, col)
  63. for col in self._cols(m)
  64. ]
  65. if self.composite:
  66. return tuple(key)
  67. else:
  68. obj = key[0]
  69. if obj is None:
  70. return _UNMAPPED_AMBIGUOUS_NONE
  71. else:
  72. return obj
  73. class _SerializableColumnGetterV2(_PlainColumnGetter[_KT]):
  74. """Updated serializable getter which deals with
  75. multi-table mapped classes.
  76. Two extremely unusual cases are not supported.
  77. Mappings which have tables across multiple metadata
  78. objects, or which are mapped to non-Table selectables
  79. linked across inheriting mappers may fail to function
  80. here.
  81. """
  82. __slots__ = ("colkeys",)
  83. def __init__(
  84. self, colkeys: Sequence[Tuple[Optional[str], Optional[str]]]
  85. ) -> None:
  86. self.colkeys = colkeys
  87. self.composite = len(colkeys) > 1
  88. def __reduce__(
  89. self,
  90. ) -> Tuple[
  91. Type[_SerializableColumnGetterV2[_KT]],
  92. Tuple[Sequence[Tuple[Optional[str], Optional[str]]]],
  93. ]:
  94. return self.__class__, (self.colkeys,)
  95. @classmethod
  96. def _reduce_from_cols(
  97. cls, cols: Sequence[ColumnElement[_KT]]
  98. ) -> Tuple[
  99. Type[_SerializableColumnGetterV2[_KT]],
  100. Tuple[Sequence[Tuple[Optional[str], Optional[str]]]],
  101. ]:
  102. def _table_key(c: ColumnElement[_KT]) -> Optional[str]:
  103. if not isinstance(c.table, expression.TableClause):
  104. return None
  105. else:
  106. return c.table.key # type: ignore
  107. colkeys = [(c.key, _table_key(c)) for c in cols]
  108. return _SerializableColumnGetterV2, (colkeys,)
  109. def _cols(self, mapper: Mapper[_KT]) -> Sequence[ColumnElement[_KT]]:
  110. cols: List[ColumnElement[_KT]] = []
  111. metadata = getattr(mapper.local_table, "metadata", None)
  112. for ckey, tkey in self.colkeys:
  113. if tkey is None or metadata is None or tkey not in metadata:
  114. cols.append(mapper.local_table.c[ckey]) # type: ignore
  115. else:
  116. cols.append(metadata.tables[tkey].c[ckey])
  117. return cols
  118. def column_keyed_dict(
  119. mapping_spec: Union[Type[_KT], Callable[[_KT], _VT]],
  120. *,
  121. ignore_unpopulated_attribute: bool = False,
  122. ) -> Type[KeyFuncDict[_KT, _KT]]:
  123. """A dictionary-based collection type with column-based keying.
  124. .. versionchanged:: 2.0 Renamed :data:`.column_mapped_collection` to
  125. :class:`.column_keyed_dict`.
  126. Returns a :class:`.KeyFuncDict` factory which will produce new
  127. dictionary keys based on the value of a particular :class:`.Column`-mapped
  128. attribute on ORM mapped instances to be added to the dictionary.
  129. .. note:: the value of the target attribute must be assigned with its
  130. value at the time that the object is being added to the
  131. dictionary collection. Additionally, changes to the key attribute
  132. are **not tracked**, which means the key in the dictionary is not
  133. automatically synchronized with the key value on the target object
  134. itself. See :ref:`key_collections_mutations` for further details.
  135. .. seealso::
  136. :ref:`orm_dictionary_collection` - background on use
  137. :param mapping_spec: a :class:`_schema.Column` object that is expected
  138. to be mapped by the target mapper to a particular attribute on the
  139. mapped class, the value of which on a particular instance is to be used
  140. as the key for a new dictionary entry for that instance.
  141. :param ignore_unpopulated_attribute: if True, and the mapped attribute
  142. indicated by the given :class:`_schema.Column` target attribute
  143. on an object is not populated at all, the operation will be silently
  144. skipped. By default, an error is raised.
  145. .. versionadded:: 2.0 an error is raised by default if the attribute
  146. being used for the dictionary key is determined that it was never
  147. populated with any value. The
  148. :paramref:`_orm.column_keyed_dict.ignore_unpopulated_attribute`
  149. parameter may be set which will instead indicate that this condition
  150. should be ignored, and the append operation silently skipped.
  151. This is in contrast to the behavior of the 1.x series which would
  152. erroneously populate the value in the dictionary with an arbitrary key
  153. value of ``None``.
  154. """
  155. cols = [
  156. coercions.expect(roles.ColumnArgumentRole, q, argname="mapping_spec")
  157. for q in util.to_list(mapping_spec)
  158. ]
  159. keyfunc = _PlainColumnGetter(cols)
  160. return _mapped_collection_cls(
  161. keyfunc,
  162. ignore_unpopulated_attribute=ignore_unpopulated_attribute,
  163. )
  164. _UNMAPPED_AMBIGUOUS_NONE = object()
  165. class _AttrGetter:
  166. __slots__ = ("attr_name", "getter")
  167. def __init__(self, attr_name: str):
  168. self.attr_name = attr_name
  169. self.getter = operator.attrgetter(attr_name)
  170. def __call__(self, mapped_object: Any) -> Any:
  171. obj = self.getter(mapped_object)
  172. if obj is None:
  173. state = base.instance_state(mapped_object)
  174. mp = state.mapper
  175. if self.attr_name in mp.attrs:
  176. dict_ = state.dict
  177. obj = dict_.get(self.attr_name, base.NO_VALUE)
  178. if obj is None:
  179. return _UNMAPPED_AMBIGUOUS_NONE
  180. else:
  181. return _UNMAPPED_AMBIGUOUS_NONE
  182. return obj
  183. def __reduce__(self) -> Tuple[Type[_AttrGetter], Tuple[str]]:
  184. return _AttrGetter, (self.attr_name,)
  185. def attribute_keyed_dict(
  186. attr_name: str, *, ignore_unpopulated_attribute: bool = False
  187. ) -> Type[KeyFuncDict[Any, Any]]:
  188. """A dictionary-based collection type with attribute-based keying.
  189. .. versionchanged:: 2.0 Renamed :data:`.attribute_mapped_collection` to
  190. :func:`.attribute_keyed_dict`.
  191. Returns a :class:`.KeyFuncDict` factory which will produce new
  192. dictionary keys based on the value of a particular named attribute on
  193. ORM mapped instances to be added to the dictionary.
  194. .. note:: the value of the target attribute must be assigned with its
  195. value at the time that the object is being added to the
  196. dictionary collection. Additionally, changes to the key attribute
  197. are **not tracked**, which means the key in the dictionary is not
  198. automatically synchronized with the key value on the target object
  199. itself. See :ref:`key_collections_mutations` for further details.
  200. .. seealso::
  201. :ref:`orm_dictionary_collection` - background on use
  202. :param attr_name: string name of an ORM-mapped attribute
  203. on the mapped class, the value of which on a particular instance
  204. is to be used as the key for a new dictionary entry for that instance.
  205. :param ignore_unpopulated_attribute: if True, and the target attribute
  206. on an object is not populated at all, the operation will be silently
  207. skipped. By default, an error is raised.
  208. .. versionadded:: 2.0 an error is raised by default if the attribute
  209. being used for the dictionary key is determined that it was never
  210. populated with any value. The
  211. :paramref:`_orm.attribute_keyed_dict.ignore_unpopulated_attribute`
  212. parameter may be set which will instead indicate that this condition
  213. should be ignored, and the append operation silently skipped.
  214. This is in contrast to the behavior of the 1.x series which would
  215. erroneously populate the value in the dictionary with an arbitrary key
  216. value of ``None``.
  217. """
  218. return _mapped_collection_cls(
  219. _AttrGetter(attr_name),
  220. ignore_unpopulated_attribute=ignore_unpopulated_attribute,
  221. )
  222. def keyfunc_mapping(
  223. keyfunc: _F,
  224. *,
  225. ignore_unpopulated_attribute: bool = False,
  226. ) -> Type[KeyFuncDict[_KT, Any]]:
  227. """A dictionary-based collection type with arbitrary keying.
  228. .. versionchanged:: 2.0 Renamed :data:`.mapped_collection` to
  229. :func:`.keyfunc_mapping`.
  230. Returns a :class:`.KeyFuncDict` factory with a keying function
  231. generated from keyfunc, a callable that takes an entity and returns a
  232. key value.
  233. .. note:: the given keyfunc is called only once at the time that the
  234. target object is being added to the collection. Changes to the
  235. effective value returned by the function are not tracked.
  236. .. seealso::
  237. :ref:`orm_dictionary_collection` - background on use
  238. :param keyfunc: a callable that will be passed the ORM-mapped instance
  239. which should then generate a new key to use in the dictionary.
  240. If the value returned is :attr:`.LoaderCallableStatus.NO_VALUE`, an error
  241. is raised.
  242. :param ignore_unpopulated_attribute: if True, and the callable returns
  243. :attr:`.LoaderCallableStatus.NO_VALUE` for a particular instance, the
  244. operation will be silently skipped. By default, an error is raised.
  245. .. versionadded:: 2.0 an error is raised by default if the callable
  246. being used for the dictionary key returns
  247. :attr:`.LoaderCallableStatus.NO_VALUE`, which in an ORM attribute
  248. context indicates an attribute that was never populated with any value.
  249. The :paramref:`_orm.mapped_collection.ignore_unpopulated_attribute`
  250. parameter may be set which will instead indicate that this condition
  251. should be ignored, and the append operation silently skipped. This is
  252. in contrast to the behavior of the 1.x series which would erroneously
  253. populate the value in the dictionary with an arbitrary key value of
  254. ``None``.
  255. """
  256. return _mapped_collection_cls(
  257. keyfunc, ignore_unpopulated_attribute=ignore_unpopulated_attribute
  258. )
  259. class KeyFuncDict(Dict[_KT, _VT]):
  260. """Base for ORM mapped dictionary classes.
  261. Extends the ``dict`` type with additional methods needed by SQLAlchemy ORM
  262. collection classes. Use of :class:`_orm.KeyFuncDict` is most directly
  263. by using the :func:`.attribute_keyed_dict` or
  264. :func:`.column_keyed_dict` class factories.
  265. :class:`_orm.KeyFuncDict` may also serve as the base for user-defined
  266. custom dictionary classes.
  267. .. versionchanged:: 2.0 Renamed :class:`.MappedCollection` to
  268. :class:`.KeyFuncDict`.
  269. .. seealso::
  270. :func:`_orm.attribute_keyed_dict`
  271. :func:`_orm.column_keyed_dict`
  272. :ref:`orm_dictionary_collection`
  273. :ref:`orm_custom_collection`
  274. """
  275. def __init__(
  276. self,
  277. keyfunc: _F,
  278. *dict_args: Any,
  279. ignore_unpopulated_attribute: bool = False,
  280. ) -> None:
  281. """Create a new collection with keying provided by keyfunc.
  282. keyfunc may be any callable that takes an object and returns an object
  283. for use as a dictionary key.
  284. The keyfunc will be called every time the ORM needs to add a member by
  285. value-only (such as when loading instances from the database) or
  286. remove a member. The usual cautions about dictionary keying apply-
  287. ``keyfunc(object)`` should return the same output for the life of the
  288. collection. Keying based on mutable properties can result in
  289. unreachable instances "lost" in the collection.
  290. """
  291. self.keyfunc = keyfunc
  292. self.ignore_unpopulated_attribute = ignore_unpopulated_attribute
  293. super().__init__(*dict_args)
  294. @classmethod
  295. def _unreduce(
  296. cls,
  297. keyfunc: _F,
  298. values: Dict[_KT, _KT],
  299. adapter: Optional[CollectionAdapter] = None,
  300. ) -> "KeyFuncDict[_KT, _KT]":
  301. mp: KeyFuncDict[_KT, _KT] = KeyFuncDict(keyfunc)
  302. mp.update(values)
  303. # note that the adapter sets itself up onto this collection
  304. # when its `__setstate__` method is called
  305. return mp
  306. def __reduce__(
  307. self,
  308. ) -> Tuple[
  309. Callable[[_KT, _KT], KeyFuncDict[_KT, _KT]],
  310. Tuple[Any, Union[Dict[_KT, _KT], Dict[_KT, _KT]], CollectionAdapter],
  311. ]:
  312. return (
  313. KeyFuncDict._unreduce,
  314. (
  315. self.keyfunc,
  316. dict(self),
  317. collection_adapter(self),
  318. ),
  319. )
  320. @util.preload_module("sqlalchemy.orm.attributes")
  321. def _raise_for_unpopulated(
  322. self,
  323. value: _KT,
  324. initiator: Union[AttributeEventToken, Literal[None, False]] = None,
  325. *,
  326. warn_only: bool,
  327. ) -> None:
  328. mapper = base.instance_state(value).mapper
  329. attributes = util.preloaded.orm_attributes
  330. if not isinstance(initiator, attributes.AttributeEventToken):
  331. relationship = "unknown relationship"
  332. elif initiator.key in mapper.attrs:
  333. relationship = f"{mapper.attrs[initiator.key]}"
  334. else:
  335. relationship = initiator.key
  336. if warn_only:
  337. util.warn(
  338. f"Attribute keyed dictionary value for "
  339. f"attribute '{relationship}' was None; this will raise "
  340. "in a future release. "
  341. f"To skip this assignment entirely, "
  342. f'Set the "ignore_unpopulated_attribute=True" '
  343. f"parameter on the mapped collection factory."
  344. )
  345. else:
  346. raise sa_exc.InvalidRequestError(
  347. "In event triggered from population of "
  348. f"attribute '{relationship}' "
  349. "(potentially from a backref), "
  350. f"can't populate value in KeyFuncDict; "
  351. "dictionary key "
  352. f"derived from {base.instance_str(value)} is not "
  353. f"populated. Ensure appropriate state is set up on "
  354. f"the {base.instance_str(value)} object "
  355. f"before assigning to the {relationship} attribute. "
  356. f"To skip this assignment entirely, "
  357. f'Set the "ignore_unpopulated_attribute=True" '
  358. f"parameter on the mapped collection factory."
  359. )
  360. @collection.appender # type: ignore[misc]
  361. @collection.internally_instrumented # type: ignore[misc]
  362. def set(
  363. self,
  364. value: _KT,
  365. _sa_initiator: Union[AttributeEventToken, Literal[None, False]] = None,
  366. ) -> None:
  367. """Add an item by value, consulting the keyfunc for the key."""
  368. key = self.keyfunc(value)
  369. if key is base.NO_VALUE:
  370. if not self.ignore_unpopulated_attribute:
  371. self._raise_for_unpopulated(
  372. value, _sa_initiator, warn_only=False
  373. )
  374. else:
  375. return
  376. elif key is _UNMAPPED_AMBIGUOUS_NONE:
  377. if not self.ignore_unpopulated_attribute:
  378. self._raise_for_unpopulated(
  379. value, _sa_initiator, warn_only=True
  380. )
  381. key = None
  382. else:
  383. return
  384. self.__setitem__(key, value, _sa_initiator) # type: ignore[call-arg]
  385. @collection.remover # type: ignore[misc]
  386. @collection.internally_instrumented # type: ignore[misc]
  387. def remove(
  388. self,
  389. value: _KT,
  390. _sa_initiator: Union[AttributeEventToken, Literal[None, False]] = None,
  391. ) -> None:
  392. """Remove an item by value, consulting the keyfunc for the key."""
  393. key = self.keyfunc(value)
  394. if key is base.NO_VALUE:
  395. if not self.ignore_unpopulated_attribute:
  396. self._raise_for_unpopulated(
  397. value, _sa_initiator, warn_only=False
  398. )
  399. return
  400. elif key is _UNMAPPED_AMBIGUOUS_NONE:
  401. if not self.ignore_unpopulated_attribute:
  402. self._raise_for_unpopulated(
  403. value, _sa_initiator, warn_only=True
  404. )
  405. key = None
  406. else:
  407. return
  408. # Let self[key] raise if key is not in this collection
  409. # testlib.pragma exempt:__ne__
  410. if self[key] != value:
  411. raise sa_exc.InvalidRequestError(
  412. "Can not remove '%s': collection holds '%s' for key '%s'. "
  413. "Possible cause: is the KeyFuncDict key function "
  414. "based on mutable properties or properties that only obtain "
  415. "values after flush?" % (value, self[key], key)
  416. )
  417. self.__delitem__(key, _sa_initiator) # type: ignore[call-arg]
  418. def _mapped_collection_cls(
  419. keyfunc: _F, ignore_unpopulated_attribute: bool
  420. ) -> Type[KeyFuncDict[_KT, _KT]]:
  421. class _MKeyfuncMapped(KeyFuncDict[_KT, _KT]):
  422. def __init__(self, *dict_args: Any) -> None:
  423. super().__init__(
  424. keyfunc,
  425. *dict_args,
  426. ignore_unpopulated_attribute=ignore_unpopulated_attribute,
  427. )
  428. return _MKeyfuncMapped
  429. MappedCollection = KeyFuncDict
  430. """A synonym for :class:`.KeyFuncDict`.
  431. .. versionchanged:: 2.0 Renamed :class:`.MappedCollection` to
  432. :class:`.KeyFuncDict`.
  433. """
  434. mapped_collection = keyfunc_mapping
  435. """A synonym for :func:`_orm.keyfunc_mapping`.
  436. .. versionchanged:: 2.0 Renamed :data:`.mapped_collection` to
  437. :func:`_orm.keyfunc_mapping`
  438. """
  439. attribute_mapped_collection = attribute_keyed_dict
  440. """A synonym for :func:`_orm.attribute_keyed_dict`.
  441. .. versionchanged:: 2.0 Renamed :data:`.attribute_mapped_collection` to
  442. :func:`_orm.attribute_keyed_dict`
  443. """
  444. column_mapped_collection = column_keyed_dict
  445. """A synonym for :func:`_orm.column_keyed_dict.
  446. .. versionchanged:: 2.0 Renamed :func:`.column_mapped_collection` to
  447. :func:`_orm.column_keyed_dict`
  448. """