mutable.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. # ext/mutable.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. r"""Provide support for tracking of in-place changes to scalar values,
  8. which are propagated into ORM change events on owning parent objects.
  9. .. _mutable_scalars:
  10. Establishing Mutability on Scalar Column Values
  11. ===============================================
  12. A typical example of a "mutable" structure is a Python dictionary.
  13. Following the example introduced in :ref:`types_toplevel`, we
  14. begin with a custom type that marshals Python dictionaries into
  15. JSON strings before being persisted::
  16. from sqlalchemy.types import TypeDecorator, VARCHAR
  17. import json
  18. class JSONEncodedDict(TypeDecorator):
  19. "Represents an immutable structure as a json-encoded string."
  20. impl = VARCHAR
  21. def process_bind_param(self, value, dialect):
  22. if value is not None:
  23. value = json.dumps(value)
  24. return value
  25. def process_result_value(self, value, dialect):
  26. if value is not None:
  27. value = json.loads(value)
  28. return value
  29. The usage of ``json`` is only for the purposes of example. The
  30. :mod:`sqlalchemy.ext.mutable` extension can be used
  31. with any type whose target Python type may be mutable, including
  32. :class:`.PickleType`, :class:`_postgresql.ARRAY`, etc.
  33. When using the :mod:`sqlalchemy.ext.mutable` extension, the value itself
  34. tracks all parents which reference it. Below, we illustrate a simple
  35. version of the :class:`.MutableDict` dictionary object, which applies
  36. the :class:`.Mutable` mixin to a plain Python dictionary::
  37. from sqlalchemy.ext.mutable import Mutable
  38. class MutableDict(Mutable, dict):
  39. @classmethod
  40. def coerce(cls, key, value):
  41. "Convert plain dictionaries to MutableDict."
  42. if not isinstance(value, MutableDict):
  43. if isinstance(value, dict):
  44. return MutableDict(value)
  45. # this call will raise ValueError
  46. return Mutable.coerce(key, value)
  47. else:
  48. return value
  49. def __setitem__(self, key, value):
  50. "Detect dictionary set events and emit change events."
  51. dict.__setitem__(self, key, value)
  52. self.changed()
  53. def __delitem__(self, key):
  54. "Detect dictionary del events and emit change events."
  55. dict.__delitem__(self, key)
  56. self.changed()
  57. The above dictionary class takes the approach of subclassing the Python
  58. built-in ``dict`` to produce a dict
  59. subclass which routes all mutation events through ``__setitem__``. There are
  60. variants on this approach, such as subclassing ``UserDict.UserDict`` or
  61. ``collections.MutableMapping``; the part that's important to this example is
  62. that the :meth:`.Mutable.changed` method is called whenever an in-place
  63. change to the datastructure takes place.
  64. We also redefine the :meth:`.Mutable.coerce` method which will be used to
  65. convert any values that are not instances of ``MutableDict``, such
  66. as the plain dictionaries returned by the ``json`` module, into the
  67. appropriate type. Defining this method is optional; we could just as well
  68. created our ``JSONEncodedDict`` such that it always returns an instance
  69. of ``MutableDict``, and additionally ensured that all calling code
  70. uses ``MutableDict`` explicitly. When :meth:`.Mutable.coerce` is not
  71. overridden, any values applied to a parent object which are not instances
  72. of the mutable type will raise a ``ValueError``.
  73. Our new ``MutableDict`` type offers a class method
  74. :meth:`~.Mutable.as_mutable` which we can use within column metadata
  75. to associate with types. This method grabs the given type object or
  76. class and associates a listener that will detect all future mappings
  77. of this type, applying event listening instrumentation to the mapped
  78. attribute. Such as, with classical table metadata::
  79. from sqlalchemy import Table, Column, Integer
  80. my_data = Table(
  81. "my_data",
  82. metadata,
  83. Column("id", Integer, primary_key=True),
  84. Column("data", MutableDict.as_mutable(JSONEncodedDict)),
  85. )
  86. Above, :meth:`~.Mutable.as_mutable` returns an instance of ``JSONEncodedDict``
  87. (if the type object was not an instance already), which will intercept any
  88. attributes which are mapped against this type. Below we establish a simple
  89. mapping against the ``my_data`` table::
  90. from sqlalchemy.orm import DeclarativeBase
  91. from sqlalchemy.orm import Mapped
  92. from sqlalchemy.orm import mapped_column
  93. class Base(DeclarativeBase):
  94. pass
  95. class MyDataClass(Base):
  96. __tablename__ = "my_data"
  97. id: Mapped[int] = mapped_column(primary_key=True)
  98. data: Mapped[dict[str, str]] = mapped_column(
  99. MutableDict.as_mutable(JSONEncodedDict)
  100. )
  101. The ``MyDataClass.data`` member will now be notified of in place changes
  102. to its value.
  103. Any in-place changes to the ``MyDataClass.data`` member
  104. will flag the attribute as "dirty" on the parent object::
  105. >>> from sqlalchemy.orm import Session
  106. >>> sess = Session(some_engine)
  107. >>> m1 = MyDataClass(data={"value1": "foo"})
  108. >>> sess.add(m1)
  109. >>> sess.commit()
  110. >>> m1.data["value1"] = "bar"
  111. >>> assert m1 in sess.dirty
  112. True
  113. The ``MutableDict`` can be associated with all future instances
  114. of ``JSONEncodedDict`` in one step, using
  115. :meth:`~.Mutable.associate_with`. This is similar to
  116. :meth:`~.Mutable.as_mutable` except it will intercept all occurrences
  117. of ``MutableDict`` in all mappings unconditionally, without
  118. the need to declare it individually::
  119. from sqlalchemy.orm import DeclarativeBase
  120. from sqlalchemy.orm import Mapped
  121. from sqlalchemy.orm import mapped_column
  122. MutableDict.associate_with(JSONEncodedDict)
  123. class Base(DeclarativeBase):
  124. pass
  125. class MyDataClass(Base):
  126. __tablename__ = "my_data"
  127. id: Mapped[int] = mapped_column(primary_key=True)
  128. data: Mapped[dict[str, str]] = mapped_column(JSONEncodedDict)
  129. Supporting Pickling
  130. --------------------
  131. The key to the :mod:`sqlalchemy.ext.mutable` extension relies upon the
  132. placement of a ``weakref.WeakKeyDictionary`` upon the value object, which
  133. stores a mapping of parent mapped objects keyed to the attribute name under
  134. which they are associated with this value. ``WeakKeyDictionary`` objects are
  135. not picklable, due to the fact that they contain weakrefs and function
  136. callbacks. In our case, this is a good thing, since if this dictionary were
  137. picklable, it could lead to an excessively large pickle size for our value
  138. objects that are pickled by themselves outside of the context of the parent.
  139. The developer responsibility here is only to provide a ``__getstate__`` method
  140. that excludes the :meth:`~MutableBase._parents` collection from the pickle
  141. stream::
  142. class MyMutableType(Mutable):
  143. def __getstate__(self):
  144. d = self.__dict__.copy()
  145. d.pop("_parents", None)
  146. return d
  147. With our dictionary example, we need to return the contents of the dict itself
  148. (and also restore them on __setstate__)::
  149. class MutableDict(Mutable, dict):
  150. # ....
  151. def __getstate__(self):
  152. return dict(self)
  153. def __setstate__(self, state):
  154. self.update(state)
  155. In the case that our mutable value object is pickled as it is attached to one
  156. or more parent objects that are also part of the pickle, the :class:`.Mutable`
  157. mixin will re-establish the :attr:`.Mutable._parents` collection on each value
  158. object as the owning parents themselves are unpickled.
  159. Receiving Events
  160. ----------------
  161. The :meth:`.AttributeEvents.modified` event handler may be used to receive
  162. an event when a mutable scalar emits a change event. This event handler
  163. is called when the :func:`.attributes.flag_modified` function is called
  164. from within the mutable extension::
  165. from sqlalchemy.orm import DeclarativeBase
  166. from sqlalchemy.orm import Mapped
  167. from sqlalchemy.orm import mapped_column
  168. from sqlalchemy import event
  169. class Base(DeclarativeBase):
  170. pass
  171. class MyDataClass(Base):
  172. __tablename__ = "my_data"
  173. id: Mapped[int] = mapped_column(primary_key=True)
  174. data: Mapped[dict[str, str]] = mapped_column(
  175. MutableDict.as_mutable(JSONEncodedDict)
  176. )
  177. @event.listens_for(MyDataClass.data, "modified")
  178. def modified_json(instance, initiator):
  179. print("json value modified:", instance.data)
  180. .. _mutable_composites:
  181. Establishing Mutability on Composites
  182. =====================================
  183. Composites are a special ORM feature which allow a single scalar attribute to
  184. be assigned an object value which represents information "composed" from one
  185. or more columns from the underlying mapped table. The usual example is that of
  186. a geometric "point", and is introduced in :ref:`mapper_composite`.
  187. As is the case with :class:`.Mutable`, the user-defined composite class
  188. subclasses :class:`.MutableComposite` as a mixin, and detects and delivers
  189. change events to its parents via the :meth:`.MutableComposite.changed` method.
  190. In the case of a composite class, the detection is usually via the usage of the
  191. special Python method ``__setattr__()``. In the example below, we expand upon the ``Point``
  192. class introduced in :ref:`mapper_composite` to include
  193. :class:`.MutableComposite` in its bases and to route attribute set events via
  194. ``__setattr__`` to the :meth:`.MutableComposite.changed` method::
  195. import dataclasses
  196. from sqlalchemy.ext.mutable import MutableComposite
  197. @dataclasses.dataclass
  198. class Point(MutableComposite):
  199. x: int
  200. y: int
  201. def __setattr__(self, key, value):
  202. "Intercept set events"
  203. # set the attribute
  204. object.__setattr__(self, key, value)
  205. # alert all parents to the change
  206. self.changed()
  207. The :class:`.MutableComposite` class makes use of class mapping events to
  208. automatically establish listeners for any usage of :func:`_orm.composite` that
  209. specifies our ``Point`` type. Below, when ``Point`` is mapped to the ``Vertex``
  210. class, listeners are established which will route change events from ``Point``
  211. objects to each of the ``Vertex.start`` and ``Vertex.end`` attributes::
  212. from sqlalchemy.orm import DeclarativeBase, Mapped
  213. from sqlalchemy.orm import composite, mapped_column
  214. class Base(DeclarativeBase):
  215. pass
  216. class Vertex(Base):
  217. __tablename__ = "vertices"
  218. id: Mapped[int] = mapped_column(primary_key=True)
  219. start: Mapped[Point] = composite(
  220. mapped_column("x1"), mapped_column("y1")
  221. )
  222. end: Mapped[Point] = composite(
  223. mapped_column("x2"), mapped_column("y2")
  224. )
  225. def __repr__(self):
  226. return f"Vertex(start={self.start}, end={self.end})"
  227. Any in-place changes to the ``Vertex.start`` or ``Vertex.end`` members
  228. will flag the attribute as "dirty" on the parent object:
  229. .. sourcecode:: python+sql
  230. >>> from sqlalchemy.orm import Session
  231. >>> sess = Session(engine)
  232. >>> v1 = Vertex(start=Point(3, 4), end=Point(12, 15))
  233. >>> sess.add(v1)
  234. {sql}>>> sess.flush()
  235. BEGIN (implicit)
  236. INSERT INTO vertices (x1, y1, x2, y2) VALUES (?, ?, ?, ?)
  237. [...] (3, 4, 12, 15)
  238. {stop}>>> v1.end.x = 8
  239. >>> assert v1 in sess.dirty
  240. True
  241. {sql}>>> sess.commit()
  242. UPDATE vertices SET x2=? WHERE vertices.id = ?
  243. [...] (8, 1)
  244. COMMIT
  245. Coercing Mutable Composites
  246. ---------------------------
  247. The :meth:`.MutableBase.coerce` method is also supported on composite types.
  248. In the case of :class:`.MutableComposite`, the :meth:`.MutableBase.coerce`
  249. method is only called for attribute set operations, not load operations.
  250. Overriding the :meth:`.MutableBase.coerce` method is essentially equivalent
  251. to using a :func:`.validates` validation routine for all attributes which
  252. make use of the custom composite type::
  253. @dataclasses.dataclass
  254. class Point(MutableComposite):
  255. # other Point methods
  256. # ...
  257. def coerce(cls, key, value):
  258. if isinstance(value, tuple):
  259. value = Point(*value)
  260. elif not isinstance(value, Point):
  261. raise ValueError("tuple or Point expected")
  262. return value
  263. Supporting Pickling
  264. --------------------
  265. As is the case with :class:`.Mutable`, the :class:`.MutableComposite` helper
  266. class uses a ``weakref.WeakKeyDictionary`` available via the
  267. :meth:`MutableBase._parents` attribute which isn't picklable. If we need to
  268. pickle instances of ``Point`` or its owning class ``Vertex``, we at least need
  269. to define a ``__getstate__`` that doesn't include the ``_parents`` dictionary.
  270. Below we define both a ``__getstate__`` and a ``__setstate__`` that package up
  271. the minimal form of our ``Point`` class::
  272. @dataclasses.dataclass
  273. class Point(MutableComposite):
  274. # ...
  275. def __getstate__(self):
  276. return self.x, self.y
  277. def __setstate__(self, state):
  278. self.x, self.y = state
  279. As with :class:`.Mutable`, the :class:`.MutableComposite` augments the
  280. pickling process of the parent's object-relational state so that the
  281. :meth:`MutableBase._parents` collection is restored to all ``Point`` objects.
  282. """ # noqa: E501
  283. from __future__ import annotations
  284. from collections import defaultdict
  285. from typing import AbstractSet
  286. from typing import Any
  287. from typing import Dict
  288. from typing import Iterable
  289. from typing import List
  290. from typing import Optional
  291. from typing import overload
  292. from typing import Set
  293. from typing import Tuple
  294. from typing import TYPE_CHECKING
  295. from typing import TypeVar
  296. from typing import Union
  297. import weakref
  298. from weakref import WeakKeyDictionary
  299. from .. import event
  300. from .. import inspect
  301. from .. import types
  302. from .. import util
  303. from ..orm import Mapper
  304. from ..orm._typing import _ExternalEntityType
  305. from ..orm._typing import _O
  306. from ..orm._typing import _T
  307. from ..orm.attributes import AttributeEventToken
  308. from ..orm.attributes import flag_modified
  309. from ..orm.attributes import InstrumentedAttribute
  310. from ..orm.attributes import QueryableAttribute
  311. from ..orm.context import QueryContext
  312. from ..orm.decl_api import DeclarativeAttributeIntercept
  313. from ..orm.state import InstanceState
  314. from ..orm.unitofwork import UOWTransaction
  315. from ..sql._typing import _TypeEngineArgument
  316. from ..sql.base import SchemaEventTarget
  317. from ..sql.schema import Column
  318. from ..sql.type_api import TypeEngine
  319. from ..util import memoized_property
  320. from ..util.typing import SupportsIndex
  321. from ..util.typing import TypeGuard
  322. _KT = TypeVar("_KT") # Key type.
  323. _VT = TypeVar("_VT") # Value type.
  324. class MutableBase:
  325. """Common base class to :class:`.Mutable`
  326. and :class:`.MutableComposite`.
  327. """
  328. @memoized_property
  329. def _parents(self) -> WeakKeyDictionary[Any, Any]:
  330. """Dictionary of parent object's :class:`.InstanceState`->attribute
  331. name on the parent.
  332. This attribute is a so-called "memoized" property. It initializes
  333. itself with a new ``weakref.WeakKeyDictionary`` the first time
  334. it is accessed, returning the same object upon subsequent access.
  335. .. versionchanged:: 1.4 the :class:`.InstanceState` is now used
  336. as the key in the weak dictionary rather than the instance
  337. itself.
  338. """
  339. return weakref.WeakKeyDictionary()
  340. @classmethod
  341. def coerce(cls, key: str, value: Any) -> Optional[Any]:
  342. """Given a value, coerce it into the target type.
  343. Can be overridden by custom subclasses to coerce incoming
  344. data into a particular type.
  345. By default, raises ``ValueError``.
  346. This method is called in different scenarios depending on if
  347. the parent class is of type :class:`.Mutable` or of type
  348. :class:`.MutableComposite`. In the case of the former, it is called
  349. for both attribute-set operations as well as during ORM loading
  350. operations. For the latter, it is only called during attribute-set
  351. operations; the mechanics of the :func:`.composite` construct
  352. handle coercion during load operations.
  353. :param key: string name of the ORM-mapped attribute being set.
  354. :param value: the incoming value.
  355. :return: the method should return the coerced value, or raise
  356. ``ValueError`` if the coercion cannot be completed.
  357. """
  358. if value is None:
  359. return None
  360. msg = "Attribute '%s' does not accept objects of type %s"
  361. raise ValueError(msg % (key, type(value)))
  362. @classmethod
  363. def _get_listen_keys(cls, attribute: QueryableAttribute[Any]) -> Set[str]:
  364. """Given a descriptor attribute, return a ``set()`` of the attribute
  365. keys which indicate a change in the state of this attribute.
  366. This is normally just ``set([attribute.key])``, but can be overridden
  367. to provide for additional keys. E.g. a :class:`.MutableComposite`
  368. augments this set with the attribute keys associated with the columns
  369. that comprise the composite value.
  370. This collection is consulted in the case of intercepting the
  371. :meth:`.InstanceEvents.refresh` and
  372. :meth:`.InstanceEvents.refresh_flush` events, which pass along a list
  373. of attribute names that have been refreshed; the list is compared
  374. against this set to determine if action needs to be taken.
  375. """
  376. return {attribute.key}
  377. @classmethod
  378. def _listen_on_attribute(
  379. cls,
  380. attribute: QueryableAttribute[Any],
  381. coerce: bool,
  382. parent_cls: _ExternalEntityType[Any],
  383. ) -> None:
  384. """Establish this type as a mutation listener for the given
  385. mapped descriptor.
  386. """
  387. key = attribute.key
  388. if parent_cls is not attribute.class_:
  389. return
  390. # rely on "propagate" here
  391. parent_cls = attribute.class_
  392. listen_keys = cls._get_listen_keys(attribute)
  393. def load(state: InstanceState[_O], *args: Any) -> None:
  394. """Listen for objects loaded or refreshed.
  395. Wrap the target data member's value with
  396. ``Mutable``.
  397. """
  398. val = state.dict.get(key, None)
  399. if val is not None:
  400. if coerce:
  401. val = cls.coerce(key, val)
  402. assert val is not None
  403. state.dict[key] = val
  404. val._parents[state] = key
  405. def load_attrs(
  406. state: InstanceState[_O],
  407. ctx: Union[object, QueryContext, UOWTransaction],
  408. attrs: Iterable[Any],
  409. ) -> None:
  410. if not attrs or listen_keys.intersection(attrs):
  411. load(state)
  412. def set_(
  413. target: InstanceState[_O],
  414. value: MutableBase | None,
  415. oldvalue: MutableBase | None,
  416. initiator: AttributeEventToken,
  417. ) -> MutableBase | None:
  418. """Listen for set/replace events on the target
  419. data member.
  420. Establish a weak reference to the parent object
  421. on the incoming value, remove it for the one
  422. outgoing.
  423. """
  424. if value is oldvalue:
  425. return value
  426. if not isinstance(value, cls):
  427. value = cls.coerce(key, value)
  428. if value is not None:
  429. value._parents[target] = key
  430. if isinstance(oldvalue, cls):
  431. oldvalue._parents.pop(inspect(target), None)
  432. return value
  433. def pickle(
  434. state: InstanceState[_O], state_dict: Dict[str, Any]
  435. ) -> None:
  436. val = state.dict.get(key, None)
  437. if val is not None:
  438. if "ext.mutable.values" not in state_dict:
  439. state_dict["ext.mutable.values"] = defaultdict(list)
  440. state_dict["ext.mutable.values"][key].append(val)
  441. def unpickle(
  442. state: InstanceState[_O], state_dict: Dict[str, Any]
  443. ) -> None:
  444. if "ext.mutable.values" in state_dict:
  445. collection = state_dict["ext.mutable.values"]
  446. if isinstance(collection, list):
  447. # legacy format
  448. for val in collection:
  449. val._parents[state] = key
  450. else:
  451. for val in state_dict["ext.mutable.values"][key]:
  452. val._parents[state] = key
  453. event.listen(
  454. parent_cls,
  455. "_sa_event_merge_wo_load",
  456. load,
  457. raw=True,
  458. propagate=True,
  459. )
  460. event.listen(parent_cls, "load", load, raw=True, propagate=True)
  461. event.listen(
  462. parent_cls, "refresh", load_attrs, raw=True, propagate=True
  463. )
  464. event.listen(
  465. parent_cls, "refresh_flush", load_attrs, raw=True, propagate=True
  466. )
  467. event.listen(
  468. attribute, "set", set_, raw=True, retval=True, propagate=True
  469. )
  470. event.listen(parent_cls, "pickle", pickle, raw=True, propagate=True)
  471. event.listen(
  472. parent_cls, "unpickle", unpickle, raw=True, propagate=True
  473. )
  474. class Mutable(MutableBase):
  475. """Mixin that defines transparent propagation of change
  476. events to a parent object.
  477. See the example in :ref:`mutable_scalars` for usage information.
  478. """
  479. def changed(self) -> None:
  480. """Subclasses should call this method whenever change events occur."""
  481. for parent, key in self._parents.items():
  482. flag_modified(parent.obj(), key)
  483. @classmethod
  484. def associate_with_attribute(
  485. cls, attribute: InstrumentedAttribute[_O]
  486. ) -> None:
  487. """Establish this type as a mutation listener for the given
  488. mapped descriptor.
  489. """
  490. cls._listen_on_attribute(attribute, True, attribute.class_)
  491. @classmethod
  492. def associate_with(cls, sqltype: type) -> None:
  493. """Associate this wrapper with all future mapped columns
  494. of the given type.
  495. This is a convenience method that calls
  496. ``associate_with_attribute`` automatically.
  497. .. warning::
  498. The listeners established by this method are *global*
  499. to all mappers, and are *not* garbage collected. Only use
  500. :meth:`.associate_with` for types that are permanent to an
  501. application, not with ad-hoc types else this will cause unbounded
  502. growth in memory usage.
  503. """
  504. def listen_for_type(mapper: Mapper[_O], class_: type) -> None:
  505. if mapper.non_primary:
  506. return
  507. for prop in mapper.column_attrs:
  508. if isinstance(prop.columns[0].type, sqltype):
  509. cls.associate_with_attribute(getattr(class_, prop.key))
  510. event.listen(Mapper, "mapper_configured", listen_for_type)
  511. @classmethod
  512. def as_mutable(cls, sqltype: _TypeEngineArgument[_T]) -> TypeEngine[_T]:
  513. """Associate a SQL type with this mutable Python type.
  514. This establishes listeners that will detect ORM mappings against
  515. the given type, adding mutation event trackers to those mappings.
  516. The type is returned, unconditionally as an instance, so that
  517. :meth:`.as_mutable` can be used inline::
  518. Table(
  519. "mytable",
  520. metadata,
  521. Column("id", Integer, primary_key=True),
  522. Column("data", MyMutableType.as_mutable(PickleType)),
  523. )
  524. Note that the returned type is always an instance, even if a class
  525. is given, and that only columns which are declared specifically with
  526. that type instance receive additional instrumentation.
  527. To associate a particular mutable type with all occurrences of a
  528. particular type, use the :meth:`.Mutable.associate_with` classmethod
  529. of the particular :class:`.Mutable` subclass to establish a global
  530. association.
  531. .. warning::
  532. The listeners established by this method are *global*
  533. to all mappers, and are *not* garbage collected. Only use
  534. :meth:`.as_mutable` for types that are permanent to an application,
  535. not with ad-hoc types else this will cause unbounded growth
  536. in memory usage.
  537. """
  538. sqltype = types.to_instance(sqltype)
  539. # a SchemaType will be copied when the Column is copied,
  540. # and we'll lose our ability to link that type back to the original.
  541. # so track our original type w/ columns
  542. if isinstance(sqltype, SchemaEventTarget):
  543. @event.listens_for(sqltype, "before_parent_attach")
  544. def _add_column_memo(
  545. sqltyp: TypeEngine[Any],
  546. parent: Column[_T],
  547. ) -> None:
  548. parent.info["_ext_mutable_orig_type"] = sqltyp
  549. schema_event_check = True
  550. else:
  551. schema_event_check = False
  552. def listen_for_type(
  553. mapper: Mapper[_T],
  554. class_: Union[DeclarativeAttributeIntercept, type],
  555. ) -> None:
  556. if mapper.non_primary:
  557. return
  558. _APPLIED_KEY = "_ext_mutable_listener_applied"
  559. for prop in mapper.column_attrs:
  560. if (
  561. # all Mutable types refer to a Column that's mapped,
  562. # since this is the only kind of Core target the ORM can
  563. # "mutate"
  564. isinstance(prop.expression, Column)
  565. and (
  566. (
  567. schema_event_check
  568. and prop.expression.info.get(
  569. "_ext_mutable_orig_type"
  570. )
  571. is sqltype
  572. )
  573. or prop.expression.type is sqltype
  574. )
  575. ):
  576. if not prop.expression.info.get(_APPLIED_KEY, False):
  577. prop.expression.info[_APPLIED_KEY] = True
  578. cls.associate_with_attribute(getattr(class_, prop.key))
  579. event.listen(Mapper, "mapper_configured", listen_for_type)
  580. return sqltype
  581. class MutableComposite(MutableBase):
  582. """Mixin that defines transparent propagation of change
  583. events on a SQLAlchemy "composite" object to its
  584. owning parent or parents.
  585. See the example in :ref:`mutable_composites` for usage information.
  586. """
  587. @classmethod
  588. def _get_listen_keys(cls, attribute: QueryableAttribute[_O]) -> Set[str]:
  589. return {attribute.key}.union(attribute.property._attribute_keys)
  590. def changed(self) -> None:
  591. """Subclasses should call this method whenever change events occur."""
  592. for parent, key in self._parents.items():
  593. prop = parent.mapper.get_property(key)
  594. for value, attr_name in zip(
  595. prop._composite_values_from_instance(self),
  596. prop._attribute_keys,
  597. ):
  598. setattr(parent.obj(), attr_name, value)
  599. def _setup_composite_listener() -> None:
  600. def _listen_for_type(mapper: Mapper[_T], class_: type) -> None:
  601. for prop in mapper.iterate_properties:
  602. if (
  603. hasattr(prop, "composite_class")
  604. and isinstance(prop.composite_class, type)
  605. and issubclass(prop.composite_class, MutableComposite)
  606. ):
  607. prop.composite_class._listen_on_attribute(
  608. getattr(class_, prop.key), False, class_
  609. )
  610. if not event.contains(Mapper, "mapper_configured", _listen_for_type):
  611. event.listen(Mapper, "mapper_configured", _listen_for_type)
  612. _setup_composite_listener()
  613. class MutableDict(Mutable, Dict[_KT, _VT]):
  614. """A dictionary type that implements :class:`.Mutable`.
  615. The :class:`.MutableDict` object implements a dictionary that will
  616. emit change events to the underlying mapping when the contents of
  617. the dictionary are altered, including when values are added or removed.
  618. Note that :class:`.MutableDict` does **not** apply mutable tracking to the
  619. *values themselves* inside the dictionary. Therefore it is not a sufficient
  620. solution for the use case of tracking deep changes to a *recursive*
  621. dictionary structure, such as a JSON structure. To support this use case,
  622. build a subclass of :class:`.MutableDict` that provides appropriate
  623. coercion to the values placed in the dictionary so that they too are
  624. "mutable", and emit events up to their parent structure.
  625. .. seealso::
  626. :class:`.MutableList`
  627. :class:`.MutableSet`
  628. """
  629. def __setitem__(self, key: _KT, value: _VT) -> None:
  630. """Detect dictionary set events and emit change events."""
  631. super().__setitem__(key, value)
  632. self.changed()
  633. if TYPE_CHECKING:
  634. # from https://github.com/python/mypy/issues/14858
  635. @overload
  636. def setdefault(
  637. self: MutableDict[_KT, Optional[_T]], key: _KT, value: None = None
  638. ) -> Optional[_T]: ...
  639. @overload
  640. def setdefault(self, key: _KT, value: _VT) -> _VT: ...
  641. def setdefault(self, key: _KT, value: object = None) -> object: ...
  642. else:
  643. def setdefault(self, *arg): # noqa: F811
  644. result = super().setdefault(*arg)
  645. self.changed()
  646. return result
  647. def __delitem__(self, key: _KT) -> None:
  648. """Detect dictionary del events and emit change events."""
  649. super().__delitem__(key)
  650. self.changed()
  651. def update(self, *a: Any, **kw: _VT) -> None:
  652. super().update(*a, **kw)
  653. self.changed()
  654. if TYPE_CHECKING:
  655. @overload
  656. def pop(self, __key: _KT) -> _VT: ...
  657. @overload
  658. def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ...
  659. def pop(
  660. self, __key: _KT, __default: _VT | _T | None = None
  661. ) -> _VT | _T: ...
  662. else:
  663. def pop(self, *arg): # noqa: F811
  664. result = super().pop(*arg)
  665. self.changed()
  666. return result
  667. def popitem(self) -> Tuple[_KT, _VT]:
  668. result = super().popitem()
  669. self.changed()
  670. return result
  671. def clear(self) -> None:
  672. super().clear()
  673. self.changed()
  674. @classmethod
  675. def coerce(cls, key: str, value: Any) -> MutableDict[_KT, _VT] | None:
  676. """Convert plain dictionary to instance of this class."""
  677. if not isinstance(value, cls):
  678. if isinstance(value, dict):
  679. return cls(value)
  680. return Mutable.coerce(key, value)
  681. else:
  682. return value
  683. def __getstate__(self) -> Dict[_KT, _VT]:
  684. return dict(self)
  685. def __setstate__(
  686. self, state: Union[Dict[str, int], Dict[str, str]]
  687. ) -> None:
  688. self.update(state)
  689. class MutableList(Mutable, List[_T]):
  690. """A list type that implements :class:`.Mutable`.
  691. The :class:`.MutableList` object implements a list that will
  692. emit change events to the underlying mapping when the contents of
  693. the list are altered, including when values are added or removed.
  694. Note that :class:`.MutableList` does **not** apply mutable tracking to the
  695. *values themselves* inside the list. Therefore it is not a sufficient
  696. solution for the use case of tracking deep changes to a *recursive*
  697. mutable structure, such as a JSON structure. To support this use case,
  698. build a subclass of :class:`.MutableList` that provides appropriate
  699. coercion to the values placed in the dictionary so that they too are
  700. "mutable", and emit events up to their parent structure.
  701. .. seealso::
  702. :class:`.MutableDict`
  703. :class:`.MutableSet`
  704. """
  705. def __reduce_ex__(
  706. self, proto: SupportsIndex
  707. ) -> Tuple[type, Tuple[List[int]]]:
  708. return (self.__class__, (list(self),))
  709. # needed for backwards compatibility with
  710. # older pickles
  711. def __setstate__(self, state: Iterable[_T]) -> None:
  712. self[:] = state
  713. def is_scalar(self, value: _T | Iterable[_T]) -> TypeGuard[_T]:
  714. return not util.is_non_string_iterable(value)
  715. def is_iterable(self, value: _T | Iterable[_T]) -> TypeGuard[Iterable[_T]]:
  716. return util.is_non_string_iterable(value)
  717. def __setitem__(
  718. self, index: SupportsIndex | slice, value: _T | Iterable[_T]
  719. ) -> None:
  720. """Detect list set events and emit change events."""
  721. if isinstance(index, SupportsIndex) and self.is_scalar(value):
  722. super().__setitem__(index, value)
  723. elif isinstance(index, slice) and self.is_iterable(value):
  724. super().__setitem__(index, value)
  725. self.changed()
  726. def __delitem__(self, index: SupportsIndex | slice) -> None:
  727. """Detect list del events and emit change events."""
  728. super().__delitem__(index)
  729. self.changed()
  730. def pop(self, *arg: SupportsIndex) -> _T:
  731. result = super().pop(*arg)
  732. self.changed()
  733. return result
  734. def append(self, x: _T) -> None:
  735. super().append(x)
  736. self.changed()
  737. def extend(self, x: Iterable[_T]) -> None:
  738. super().extend(x)
  739. self.changed()
  740. def __iadd__(self, x: Iterable[_T]) -> MutableList[_T]: # type: ignore[override,misc] # noqa: E501
  741. self.extend(x)
  742. return self
  743. def insert(self, i: SupportsIndex, x: _T) -> None:
  744. super().insert(i, x)
  745. self.changed()
  746. def remove(self, i: _T) -> None:
  747. super().remove(i)
  748. self.changed()
  749. def clear(self) -> None:
  750. super().clear()
  751. self.changed()
  752. def sort(self, **kw: Any) -> None:
  753. super().sort(**kw)
  754. self.changed()
  755. def reverse(self) -> None:
  756. super().reverse()
  757. self.changed()
  758. @classmethod
  759. def coerce(
  760. cls, key: str, value: MutableList[_T] | _T
  761. ) -> Optional[MutableList[_T]]:
  762. """Convert plain list to instance of this class."""
  763. if not isinstance(value, cls):
  764. if isinstance(value, list):
  765. return cls(value)
  766. return Mutable.coerce(key, value)
  767. else:
  768. return value
  769. class MutableSet(Mutable, Set[_T]):
  770. """A set type that implements :class:`.Mutable`.
  771. The :class:`.MutableSet` object implements a set that will
  772. emit change events to the underlying mapping when the contents of
  773. the set are altered, including when values are added or removed.
  774. Note that :class:`.MutableSet` does **not** apply mutable tracking to the
  775. *values themselves* inside the set. Therefore it is not a sufficient
  776. solution for the use case of tracking deep changes to a *recursive*
  777. mutable structure. To support this use case,
  778. build a subclass of :class:`.MutableSet` that provides appropriate
  779. coercion to the values placed in the dictionary so that they too are
  780. "mutable", and emit events up to their parent structure.
  781. .. seealso::
  782. :class:`.MutableDict`
  783. :class:`.MutableList`
  784. """
  785. def update(self, *arg: Iterable[_T]) -> None:
  786. super().update(*arg)
  787. self.changed()
  788. def intersection_update(self, *arg: Iterable[Any]) -> None:
  789. super().intersection_update(*arg)
  790. self.changed()
  791. def difference_update(self, *arg: Iterable[Any]) -> None:
  792. super().difference_update(*arg)
  793. self.changed()
  794. def symmetric_difference_update(self, *arg: Iterable[_T]) -> None:
  795. super().symmetric_difference_update(*arg)
  796. self.changed()
  797. def __ior__(self, other: AbstractSet[_T]) -> MutableSet[_T]: # type: ignore[override,misc] # noqa: E501
  798. self.update(other)
  799. return self
  800. def __iand__(self, other: AbstractSet[object]) -> MutableSet[_T]:
  801. self.intersection_update(other)
  802. return self
  803. def __ixor__(self, other: AbstractSet[_T]) -> MutableSet[_T]: # type: ignore[override,misc] # noqa: E501
  804. self.symmetric_difference_update(other)
  805. return self
  806. def __isub__(self, other: AbstractSet[object]) -> MutableSet[_T]: # type: ignore[misc] # noqa: E501
  807. self.difference_update(other)
  808. return self
  809. def add(self, elem: _T) -> None:
  810. super().add(elem)
  811. self.changed()
  812. def remove(self, elem: _T) -> None:
  813. super().remove(elem)
  814. self.changed()
  815. def discard(self, elem: _T) -> None:
  816. super().discard(elem)
  817. self.changed()
  818. def pop(self, *arg: Any) -> _T:
  819. result = super().pop(*arg)
  820. self.changed()
  821. return result
  822. def clear(self) -> None:
  823. super().clear()
  824. self.changed()
  825. @classmethod
  826. def coerce(cls, index: str, value: Any) -> Optional[MutableSet[_T]]:
  827. """Convert plain set to instance of this class."""
  828. if not isinstance(value, cls):
  829. if isinstance(value, set):
  830. return cls(value)
  831. return Mutable.coerce(index, value)
  832. else:
  833. return value
  834. def __getstate__(self) -> Set[_T]:
  835. return set(self)
  836. def __setstate__(self, state: Iterable[_T]) -> None:
  837. self.update(state)
  838. def __reduce_ex__(
  839. self, proto: SupportsIndex
  840. ) -> Tuple[type, Tuple[List[int]]]:
  841. return (self.__class__, (list(self),))