mutable.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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. state.dict[key] = val
  403. val._parents[state] = key
  404. def load_attrs(
  405. state: InstanceState[_O],
  406. ctx: Union[object, QueryContext, UOWTransaction],
  407. attrs: Iterable[Any],
  408. ) -> None:
  409. if not attrs or listen_keys.intersection(attrs):
  410. load(state)
  411. def set_(
  412. target: InstanceState[_O],
  413. value: MutableBase | None,
  414. oldvalue: MutableBase | None,
  415. initiator: AttributeEventToken,
  416. ) -> MutableBase | None:
  417. """Listen for set/replace events on the target
  418. data member.
  419. Establish a weak reference to the parent object
  420. on the incoming value, remove it for the one
  421. outgoing.
  422. """
  423. if value is oldvalue:
  424. return value
  425. if not isinstance(value, cls):
  426. value = cls.coerce(key, value)
  427. if value is not None:
  428. value._parents[target] = key
  429. if isinstance(oldvalue, cls):
  430. oldvalue._parents.pop(inspect(target), None)
  431. return value
  432. def pickle(
  433. state: InstanceState[_O], state_dict: Dict[str, Any]
  434. ) -> None:
  435. val = state.dict.get(key, None)
  436. if val is not None:
  437. if "ext.mutable.values" not in state_dict:
  438. state_dict["ext.mutable.values"] = defaultdict(list)
  439. state_dict["ext.mutable.values"][key].append(val)
  440. def unpickle(
  441. state: InstanceState[_O], state_dict: Dict[str, Any]
  442. ) -> None:
  443. if "ext.mutable.values" in state_dict:
  444. collection = state_dict["ext.mutable.values"]
  445. if isinstance(collection, list):
  446. # legacy format
  447. for val in collection:
  448. val._parents[state] = key
  449. else:
  450. for val in state_dict["ext.mutable.values"][key]:
  451. val._parents[state] = key
  452. event.listen(
  453. parent_cls,
  454. "_sa_event_merge_wo_load",
  455. load,
  456. raw=True,
  457. propagate=True,
  458. )
  459. event.listen(parent_cls, "load", load, raw=True, propagate=True)
  460. event.listen(
  461. parent_cls, "refresh", load_attrs, raw=True, propagate=True
  462. )
  463. event.listen(
  464. parent_cls, "refresh_flush", load_attrs, raw=True, propagate=True
  465. )
  466. event.listen(
  467. attribute, "set", set_, raw=True, retval=True, propagate=True
  468. )
  469. event.listen(parent_cls, "pickle", pickle, raw=True, propagate=True)
  470. event.listen(
  471. parent_cls, "unpickle", unpickle, raw=True, propagate=True
  472. )
  473. class Mutable(MutableBase):
  474. """Mixin that defines transparent propagation of change
  475. events to a parent object.
  476. See the example in :ref:`mutable_scalars` for usage information.
  477. """
  478. def changed(self) -> None:
  479. """Subclasses should call this method whenever change events occur."""
  480. for parent, key in self._parents.items():
  481. flag_modified(parent.obj(), key)
  482. @classmethod
  483. def associate_with_attribute(
  484. cls, attribute: InstrumentedAttribute[_O]
  485. ) -> None:
  486. """Establish this type as a mutation listener for the given
  487. mapped descriptor.
  488. """
  489. cls._listen_on_attribute(attribute, True, attribute.class_)
  490. @classmethod
  491. def associate_with(cls, sqltype: type) -> None:
  492. """Associate this wrapper with all future mapped columns
  493. of the given type.
  494. This is a convenience method that calls
  495. ``associate_with_attribute`` automatically.
  496. .. warning::
  497. The listeners established by this method are *global*
  498. to all mappers, and are *not* garbage collected. Only use
  499. :meth:`.associate_with` for types that are permanent to an
  500. application, not with ad-hoc types else this will cause unbounded
  501. growth in memory usage.
  502. """
  503. def listen_for_type(mapper: Mapper[_O], class_: type) -> None:
  504. if mapper.non_primary:
  505. return
  506. for prop in mapper.column_attrs:
  507. if isinstance(prop.columns[0].type, sqltype):
  508. cls.associate_with_attribute(getattr(class_, prop.key))
  509. event.listen(Mapper, "mapper_configured", listen_for_type)
  510. @classmethod
  511. def as_mutable(cls, sqltype: _TypeEngineArgument[_T]) -> TypeEngine[_T]:
  512. """Associate a SQL type with this mutable Python type.
  513. This establishes listeners that will detect ORM mappings against
  514. the given type, adding mutation event trackers to those mappings.
  515. The type is returned, unconditionally as an instance, so that
  516. :meth:`.as_mutable` can be used inline::
  517. Table(
  518. "mytable",
  519. metadata,
  520. Column("id", Integer, primary_key=True),
  521. Column("data", MyMutableType.as_mutable(PickleType)),
  522. )
  523. Note that the returned type is always an instance, even if a class
  524. is given, and that only columns which are declared specifically with
  525. that type instance receive additional instrumentation.
  526. To associate a particular mutable type with all occurrences of a
  527. particular type, use the :meth:`.Mutable.associate_with` classmethod
  528. of the particular :class:`.Mutable` subclass to establish a global
  529. association.
  530. .. warning::
  531. The listeners established by this method are *global*
  532. to all mappers, and are *not* garbage collected. Only use
  533. :meth:`.as_mutable` for types that are permanent to an application,
  534. not with ad-hoc types else this will cause unbounded growth
  535. in memory usage.
  536. """
  537. sqltype = types.to_instance(sqltype)
  538. # a SchemaType will be copied when the Column is copied,
  539. # and we'll lose our ability to link that type back to the original.
  540. # so track our original type w/ columns
  541. if isinstance(sqltype, SchemaEventTarget):
  542. @event.listens_for(sqltype, "before_parent_attach")
  543. def _add_column_memo(
  544. sqltyp: TypeEngine[Any],
  545. parent: Column[_T],
  546. ) -> None:
  547. parent.info["_ext_mutable_orig_type"] = sqltyp
  548. schema_event_check = True
  549. else:
  550. schema_event_check = False
  551. def listen_for_type(
  552. mapper: Mapper[_T],
  553. class_: Union[DeclarativeAttributeIntercept, type],
  554. ) -> None:
  555. if mapper.non_primary:
  556. return
  557. _APPLIED_KEY = "_ext_mutable_listener_applied"
  558. for prop in mapper.column_attrs:
  559. if (
  560. # all Mutable types refer to a Column that's mapped,
  561. # since this is the only kind of Core target the ORM can
  562. # "mutate"
  563. isinstance(prop.expression, Column)
  564. and (
  565. (
  566. schema_event_check
  567. and prop.expression.info.get(
  568. "_ext_mutable_orig_type"
  569. )
  570. is sqltype
  571. )
  572. or prop.expression.type is sqltype
  573. )
  574. ):
  575. if not prop.expression.info.get(_APPLIED_KEY, False):
  576. prop.expression.info[_APPLIED_KEY] = True
  577. cls.associate_with_attribute(getattr(class_, prop.key))
  578. event.listen(Mapper, "mapper_configured", listen_for_type)
  579. return sqltype
  580. class MutableComposite(MutableBase):
  581. """Mixin that defines transparent propagation of change
  582. events on a SQLAlchemy "composite" object to its
  583. owning parent or parents.
  584. See the example in :ref:`mutable_composites` for usage information.
  585. """
  586. @classmethod
  587. def _get_listen_keys(cls, attribute: QueryableAttribute[_O]) -> Set[str]:
  588. return {attribute.key}.union(attribute.property._attribute_keys)
  589. def changed(self) -> None:
  590. """Subclasses should call this method whenever change events occur."""
  591. for parent, key in self._parents.items():
  592. prop = parent.mapper.get_property(key)
  593. for value, attr_name in zip(
  594. prop._composite_values_from_instance(self),
  595. prop._attribute_keys,
  596. ):
  597. setattr(parent.obj(), attr_name, value)
  598. def _setup_composite_listener() -> None:
  599. def _listen_for_type(mapper: Mapper[_T], class_: type) -> None:
  600. for prop in mapper.iterate_properties:
  601. if (
  602. hasattr(prop, "composite_class")
  603. and isinstance(prop.composite_class, type)
  604. and issubclass(prop.composite_class, MutableComposite)
  605. ):
  606. prop.composite_class._listen_on_attribute(
  607. getattr(class_, prop.key), False, class_
  608. )
  609. if not event.contains(Mapper, "mapper_configured", _listen_for_type):
  610. event.listen(Mapper, "mapper_configured", _listen_for_type)
  611. _setup_composite_listener()
  612. class MutableDict(Mutable, Dict[_KT, _VT]):
  613. """A dictionary type that implements :class:`.Mutable`.
  614. The :class:`.MutableDict` object implements a dictionary that will
  615. emit change events to the underlying mapping when the contents of
  616. the dictionary are altered, including when values are added or removed.
  617. Note that :class:`.MutableDict` does **not** apply mutable tracking to the
  618. *values themselves* inside the dictionary. Therefore it is not a sufficient
  619. solution for the use case of tracking deep changes to a *recursive*
  620. dictionary structure, such as a JSON structure. To support this use case,
  621. build a subclass of :class:`.MutableDict` that provides appropriate
  622. coercion to the values placed in the dictionary so that they too are
  623. "mutable", and emit events up to their parent structure.
  624. .. seealso::
  625. :class:`.MutableList`
  626. :class:`.MutableSet`
  627. """
  628. def __setitem__(self, key: _KT, value: _VT) -> None:
  629. """Detect dictionary set events and emit change events."""
  630. super().__setitem__(key, value)
  631. self.changed()
  632. if TYPE_CHECKING:
  633. # from https://github.com/python/mypy/issues/14858
  634. @overload
  635. def setdefault(
  636. self: MutableDict[_KT, Optional[_T]], key: _KT, value: None = None
  637. ) -> Optional[_T]: ...
  638. @overload
  639. def setdefault(self, key: _KT, value: _VT) -> _VT: ...
  640. def setdefault(self, key: _KT, value: object = None) -> object: ...
  641. else:
  642. def setdefault(self, *arg): # noqa: F811
  643. result = super().setdefault(*arg)
  644. self.changed()
  645. return result
  646. def __delitem__(self, key: _KT) -> None:
  647. """Detect dictionary del events and emit change events."""
  648. super().__delitem__(key)
  649. self.changed()
  650. def update(self, *a: Any, **kw: _VT) -> None:
  651. super().update(*a, **kw)
  652. self.changed()
  653. if TYPE_CHECKING:
  654. @overload
  655. def pop(self, __key: _KT) -> _VT: ...
  656. @overload
  657. def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ...
  658. def pop(
  659. self, __key: _KT, __default: _VT | _T | None = None
  660. ) -> _VT | _T: ...
  661. else:
  662. def pop(self, *arg): # noqa: F811
  663. result = super().pop(*arg)
  664. self.changed()
  665. return result
  666. def popitem(self) -> Tuple[_KT, _VT]:
  667. result = super().popitem()
  668. self.changed()
  669. return result
  670. def clear(self) -> None:
  671. super().clear()
  672. self.changed()
  673. @classmethod
  674. def coerce(cls, key: str, value: Any) -> MutableDict[_KT, _VT] | None:
  675. """Convert plain dictionary to instance of this class."""
  676. if not isinstance(value, cls):
  677. if isinstance(value, dict):
  678. return cls(value)
  679. return Mutable.coerce(key, value)
  680. else:
  681. return value
  682. def __getstate__(self) -> Dict[_KT, _VT]:
  683. return dict(self)
  684. def __setstate__(
  685. self, state: Union[Dict[str, int], Dict[str, str]]
  686. ) -> None:
  687. self.update(state)
  688. class MutableList(Mutable, List[_T]):
  689. """A list type that implements :class:`.Mutable`.
  690. The :class:`.MutableList` object implements a list that will
  691. emit change events to the underlying mapping when the contents of
  692. the list are altered, including when values are added or removed.
  693. Note that :class:`.MutableList` does **not** apply mutable tracking to the
  694. *values themselves* inside the list. Therefore it is not a sufficient
  695. solution for the use case of tracking deep changes to a *recursive*
  696. mutable structure, such as a JSON structure. To support this use case,
  697. build a subclass of :class:`.MutableList` that provides appropriate
  698. coercion to the values placed in the dictionary so that they too are
  699. "mutable", and emit events up to their parent structure.
  700. .. seealso::
  701. :class:`.MutableDict`
  702. :class:`.MutableSet`
  703. """
  704. def __reduce_ex__(
  705. self, proto: SupportsIndex
  706. ) -> Tuple[type, Tuple[List[int]]]:
  707. return (self.__class__, (list(self),))
  708. # needed for backwards compatibility with
  709. # older pickles
  710. def __setstate__(self, state: Iterable[_T]) -> None:
  711. self[:] = state
  712. def is_scalar(self, value: _T | Iterable[_T]) -> TypeGuard[_T]:
  713. return not util.is_non_string_iterable(value)
  714. def is_iterable(self, value: _T | Iterable[_T]) -> TypeGuard[Iterable[_T]]:
  715. return util.is_non_string_iterable(value)
  716. def __setitem__(
  717. self, index: SupportsIndex | slice, value: _T | Iterable[_T]
  718. ) -> None:
  719. """Detect list set events and emit change events."""
  720. if isinstance(index, SupportsIndex) and self.is_scalar(value):
  721. super().__setitem__(index, value)
  722. elif isinstance(index, slice) and self.is_iterable(value):
  723. super().__setitem__(index, value)
  724. self.changed()
  725. def __delitem__(self, index: SupportsIndex | slice) -> None:
  726. """Detect list del events and emit change events."""
  727. super().__delitem__(index)
  728. self.changed()
  729. def pop(self, *arg: SupportsIndex) -> _T:
  730. result = super().pop(*arg)
  731. self.changed()
  732. return result
  733. def append(self, x: _T) -> None:
  734. super().append(x)
  735. self.changed()
  736. def extend(self, x: Iterable[_T]) -> None:
  737. super().extend(x)
  738. self.changed()
  739. def __iadd__(self, x: Iterable[_T]) -> MutableList[_T]: # type: ignore[override,misc] # noqa: E501
  740. self.extend(x)
  741. return self
  742. def insert(self, i: SupportsIndex, x: _T) -> None:
  743. super().insert(i, x)
  744. self.changed()
  745. def remove(self, i: _T) -> None:
  746. super().remove(i)
  747. self.changed()
  748. def clear(self) -> None:
  749. super().clear()
  750. self.changed()
  751. def sort(self, **kw: Any) -> None:
  752. super().sort(**kw)
  753. self.changed()
  754. def reverse(self) -> None:
  755. super().reverse()
  756. self.changed()
  757. @classmethod
  758. def coerce(
  759. cls, key: str, value: MutableList[_T] | _T
  760. ) -> Optional[MutableList[_T]]:
  761. """Convert plain list to instance of this class."""
  762. if not isinstance(value, cls):
  763. if isinstance(value, list):
  764. return cls(value)
  765. return Mutable.coerce(key, value)
  766. else:
  767. return value
  768. class MutableSet(Mutable, Set[_T]):
  769. """A set type that implements :class:`.Mutable`.
  770. The :class:`.MutableSet` object implements a set that will
  771. emit change events to the underlying mapping when the contents of
  772. the set are altered, including when values are added or removed.
  773. Note that :class:`.MutableSet` does **not** apply mutable tracking to the
  774. *values themselves* inside the set. Therefore it is not a sufficient
  775. solution for the use case of tracking deep changes to a *recursive*
  776. mutable structure. To support this use case,
  777. build a subclass of :class:`.MutableSet` that provides appropriate
  778. coercion to the values placed in the dictionary so that they too are
  779. "mutable", and emit events up to their parent structure.
  780. .. seealso::
  781. :class:`.MutableDict`
  782. :class:`.MutableList`
  783. """
  784. def update(self, *arg: Iterable[_T]) -> None:
  785. super().update(*arg)
  786. self.changed()
  787. def intersection_update(self, *arg: Iterable[Any]) -> None:
  788. super().intersection_update(*arg)
  789. self.changed()
  790. def difference_update(self, *arg: Iterable[Any]) -> None:
  791. super().difference_update(*arg)
  792. self.changed()
  793. def symmetric_difference_update(self, *arg: Iterable[_T]) -> None:
  794. super().symmetric_difference_update(*arg)
  795. self.changed()
  796. def __ior__(self, other: AbstractSet[_T]) -> MutableSet[_T]: # type: ignore[override,misc] # noqa: E501
  797. self.update(other)
  798. return self
  799. def __iand__(self, other: AbstractSet[object]) -> MutableSet[_T]:
  800. self.intersection_update(other)
  801. return self
  802. def __ixor__(self, other: AbstractSet[_T]) -> MutableSet[_T]: # type: ignore[override,misc] # noqa: E501
  803. self.symmetric_difference_update(other)
  804. return self
  805. def __isub__(self, other: AbstractSet[object]) -> MutableSet[_T]: # type: ignore[misc] # noqa: E501
  806. self.difference_update(other)
  807. return self
  808. def add(self, elem: _T) -> None:
  809. super().add(elem)
  810. self.changed()
  811. def remove(self, elem: _T) -> None:
  812. super().remove(elem)
  813. self.changed()
  814. def discard(self, elem: _T) -> None:
  815. super().discard(elem)
  816. self.changed()
  817. def pop(self, *arg: Any) -> _T:
  818. result = super().pop(*arg)
  819. self.changed()
  820. return result
  821. def clear(self) -> None:
  822. super().clear()
  823. self.changed()
  824. @classmethod
  825. def coerce(cls, index: str, value: Any) -> Optional[MutableSet[_T]]:
  826. """Convert plain set to instance of this class."""
  827. if not isinstance(value, cls):
  828. if isinstance(value, set):
  829. return cls(value)
  830. return Mutable.coerce(index, value)
  831. else:
  832. return value
  833. def __getstate__(self) -> Set[_T]:
  834. return set(self)
  835. def __setstate__(self, state: Iterable[_T]) -> None:
  836. self.update(state)
  837. def __reduce_ex__(
  838. self, proto: SupportsIndex
  839. ) -> Tuple[type, Tuple[List[int]]]:
  840. return (self.__class__, (list(self),))