zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
U
¸ý°dG–ã@sXdZddlmZddlmZddlmZddlmZddlmZddlm    Z    ddlm
Z
dd    lm Z dd
lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl#m$Z$ddl%m&Z&dd l'm(Z(dd!l)m*Z*dd"l+m,Z,dd#l-m.Z.dd$l/m0Z0dd%l1m2Z2dd&l3m4Z4dd'l3m5Z5ed(ƒZ6ed)ƒZ7Gd*d+„d+ƒZ8Gd,d-„d-e8ƒZ9Gd.d/„d/e8ƒZ:d0d1œd2d3„Z;e;ƒGd4d5„d5e9ee6e7fƒZ<Gd6d7„d7e9e
eƒZ=Gd8d9„d9e9e eƒZ>dS):a3Provide support for tracking of in-place changes to scalar values,
which are propagated into ORM change events on owning parent objects.
 
.. _mutable_scalars:
 
Establishing Mutability on Scalar Column Values
===============================================
 
A typical example of a "mutable" structure is a Python dictionary.
Following the example introduced in :ref:`types_toplevel`, we
begin with a custom type that marshals Python dictionaries into
JSON strings before being persisted::
 
    from sqlalchemy.types import TypeDecorator, VARCHAR
    import json
 
    class JSONEncodedDict(TypeDecorator):
        "Represents an immutable structure as a json-encoded string."
 
        impl = VARCHAR
 
        def process_bind_param(self, value, dialect):
            if value is not None:
                value = json.dumps(value)
            return value
 
        def process_result_value(self, value, dialect):
            if value is not None:
                value = json.loads(value)
            return value
 
The usage of ``json`` is only for the purposes of example. The
:mod:`sqlalchemy.ext.mutable` extension can be used
with any type whose target Python type may be mutable, including
:class:`.PickleType`, :class:`_postgresql.ARRAY`, etc.
 
When using the :mod:`sqlalchemy.ext.mutable` extension, the value itself
tracks all parents which reference it.  Below, we illustrate a simple
version of the :class:`.MutableDict` dictionary object, which applies
the :class:`.Mutable` mixin to a plain Python dictionary::
 
    from sqlalchemy.ext.mutable import Mutable
 
    class MutableDict(Mutable, dict):
        @classmethod
        def coerce(cls, key, value):
            "Convert plain dictionaries to MutableDict."
 
            if not isinstance(value, MutableDict):
                if isinstance(value, dict):
                    return MutableDict(value)
 
                # this call will raise ValueError
                return Mutable.coerce(key, value)
            else:
                return value
 
        def __setitem__(self, key, value):
            "Detect dictionary set events and emit change events."
 
            dict.__setitem__(self, key, value)
            self.changed()
 
        def __delitem__(self, key):
            "Detect dictionary del events and emit change events."
 
            dict.__delitem__(self, key)
            self.changed()
 
The above dictionary class takes the approach of subclassing the Python
built-in ``dict`` to produce a dict
subclass which routes all mutation events through ``__setitem__``.  There are
variants on this approach, such as subclassing ``UserDict.UserDict`` or
``collections.MutableMapping``; the part that's important to this example is
that the :meth:`.Mutable.changed` method is called whenever an in-place
change to the datastructure takes place.
 
We also redefine the :meth:`.Mutable.coerce` method which will be used to
convert any values that are not instances of ``MutableDict``, such
as the plain dictionaries returned by the ``json`` module, into the
appropriate type.  Defining this method is optional; we could just as well
created our ``JSONEncodedDict`` such that it always returns an instance
of ``MutableDict``, and additionally ensured that all calling code
uses ``MutableDict`` explicitly.  When :meth:`.Mutable.coerce` is not
overridden, any values applied to a parent object which are not instances
of the mutable type will raise a ``ValueError``.
 
Our new ``MutableDict`` type offers a class method
:meth:`~.Mutable.as_mutable` which we can use within column metadata
to associate with types. This method grabs the given type object or
class and associates a listener that will detect all future mappings
of this type, applying event listening instrumentation to the mapped
attribute. Such as, with classical table metadata::
 
    from sqlalchemy import Table, Column, Integer
 
    my_data = Table('my_data', metadata,
        Column('id', Integer, primary_key=True),
        Column('data', MutableDict.as_mutable(JSONEncodedDict))
    )
 
Above, :meth:`~.Mutable.as_mutable` returns an instance of ``JSONEncodedDict``
(if the type object was not an instance already), which will intercept any
attributes which are mapped against this type.  Below we establish a simple
mapping against the ``my_data`` table::
 
    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.orm import Mapped
    from sqlalchemy.orm import mapped_column
 
    class Base(DeclarativeBase):
        pass
 
    class MyDataClass(Base):
        __tablename__ = 'my_data'
        id: Mapped[int] = mapped_column(primary_key=True)
        data: Mapped[dict[str, str]] = mapped_column(MutableDict.as_mutable(JSONEncodedDict))
 
The ``MyDataClass.data`` member will now be notified of in place changes
to its value.
 
Any in-place changes to the ``MyDataClass.data`` member
will flag the attribute as "dirty" on the parent object::
 
    >>> from sqlalchemy.orm import Session
 
    >>> sess = Session(some_engine)
    >>> m1 = MyDataClass(data={'value1':'foo'})
    >>> sess.add(m1)
    >>> sess.commit()
 
    >>> m1.data['value1'] = 'bar'
    >>> assert m1 in sess.dirty
    True
 
The ``MutableDict`` can be associated with all future instances
of ``JSONEncodedDict`` in one step, using
:meth:`~.Mutable.associate_with`.  This is similar to
:meth:`~.Mutable.as_mutable` except it will intercept all occurrences
of ``MutableDict`` in all mappings unconditionally, without
the need to declare it individually::
 
    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.orm import Mapped
    from sqlalchemy.orm import mapped_column
 
    MutableDict.associate_with(JSONEncodedDict)
 
    class Base(DeclarativeBase):
        pass
 
    class MyDataClass(Base):
        __tablename__ = 'my_data'
        id: Mapped[int] = mapped_column(primary_key=True)
        data: Mapped[dict[str, str]] = mapped_column(JSONEncodedDict)
 
 
Supporting Pickling
--------------------
 
The key to the :mod:`sqlalchemy.ext.mutable` extension relies upon the
placement of a ``weakref.WeakKeyDictionary`` upon the value object, which
stores a mapping of parent mapped objects keyed to the attribute name under
which they are associated with this value. ``WeakKeyDictionary`` objects are
not picklable, due to the fact that they contain weakrefs and function
callbacks. In our case, this is a good thing, since if this dictionary were
picklable, it could lead to an excessively large pickle size for our value
objects that are pickled by themselves outside of the context of the parent.
The developer responsibility here is only to provide a ``__getstate__`` method
that excludes the :meth:`~MutableBase._parents` collection from the pickle
stream::
 
    class MyMutableType(Mutable):
        def __getstate__(self):
            d = self.__dict__.copy()
            d.pop('_parents', None)
            return d
 
With our dictionary example, we need to return the contents of the dict itself
(and also restore them on __setstate__)::
 
    class MutableDict(Mutable, dict):
        # ....
 
        def __getstate__(self):
            return dict(self)
 
        def __setstate__(self, state):
            self.update(state)
 
In the case that our mutable value object is pickled as it is attached to one
or more parent objects that are also part of the pickle, the :class:`.Mutable`
mixin will re-establish the :attr:`.Mutable._parents` collection on each value
object as the owning parents themselves are unpickled.
 
Receiving Events
----------------
 
The :meth:`.AttributeEvents.modified` event handler may be used to receive
an event when a mutable scalar emits a change event.  This event handler
is called when the :func:`.attributes.flag_modified` function is called
from within the mutable extension::
 
    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.orm import Mapped
    from sqlalchemy.orm import mapped_column
    from sqlalchemy import event
 
    class Base(DeclarativeBase):
        pass
 
    class MyDataClass(Base):
        __tablename__ = 'my_data'
        id: Mapped[int] = mapped_column(primary_key=True)
        data: Mapped[dict[str, str]] = mapped_column(MutableDict.as_mutable(JSONEncodedDict))
 
    @event.listens_for(MyDataClass.data, "modified")
    def modified_json(instance, initiator):
        print("json value modified:", instance.data)
 
.. _mutable_composites:
 
Establishing Mutability on Composites
=====================================
 
Composites are a special ORM feature which allow a single scalar attribute to
be assigned an object value which represents information "composed" from one
or more columns from the underlying mapped table. The usual example is that of
a geometric "point", and is introduced in :ref:`mapper_composite`.
 
As is the case with :class:`.Mutable`, the user-defined composite class
subclasses :class:`.MutableComposite` as a mixin, and detects and delivers
change events to its parents via the :meth:`.MutableComposite.changed` method.
In the case of a composite class, the detection is usually via the usage of the
special Python method ``__setattr__()``. In the example below, we expand upon the ``Point``
class introduced in :ref:`mapper_composite` to include
:class:`.MutableComposite` in its bases and to route attribute set events via
``__setattr__`` to the :meth:`.MutableComposite.changed` method::
 
    import dataclasses
    from sqlalchemy.ext.mutable import MutableComposite
 
    @dataclasses.dataclass
    class Point(MutableComposite):
        x: int
        y: int
 
        def __setattr__(self, key, value):
            "Intercept set events"
 
            # set the attribute
            object.__setattr__(self, key, value)
 
            # alert all parents to the change
            self.changed()
 
 
The :class:`.MutableComposite` class makes use of class mapping events to
automatically establish listeners for any usage of :func:`_orm.composite` that
specifies our ``Point`` type. Below, when ``Point`` is mapped to the ``Vertex``
class, listeners are established which will route change events from ``Point``
objects to each of the ``Vertex.start`` and ``Vertex.end`` attributes::
 
    from sqlalchemy.orm import DeclarativeBase, Mapped
    from sqlalchemy.orm import composite, mapped_column
 
    class Base(DeclarativeBase):
        pass
 
 
    class Vertex(Base):
        __tablename__ = "vertices"
 
        id: Mapped[int] = mapped_column(primary_key=True)
 
        start: Mapped[Point] = composite(mapped_column("x1"), mapped_column("y1"))
        end: Mapped[Point] = composite(mapped_column("x2"), mapped_column("y2"))
 
        def __repr__(self):
            return f"Vertex(start={self.start}, end={self.end})"
 
Any in-place changes to the ``Vertex.start`` or ``Vertex.end`` members
will flag the attribute as "dirty" on the parent object:
 
.. sourcecode:: python+sql
 
    >>> from sqlalchemy.orm import Session
    >>> sess = Session(engine)
    >>> v1 = Vertex(start=Point(3, 4), end=Point(12, 15))
    >>> sess.add(v1)
    {sql}>>> sess.flush()
    BEGIN (implicit)
    INSERT INTO vertices (x1, y1, x2, y2) VALUES (?, ?, ?, ?)
    [...] (3, 4, 12, 15)
 
    {stop}>>> v1.end.x = 8
    >>> assert v1 in sess.dirty
    True
    {sql}>>> sess.commit()
    UPDATE vertices SET x2=? WHERE vertices.id = ?
    [...] (8, 1)
    COMMIT
 
Coercing Mutable Composites
---------------------------
 
The :meth:`.MutableBase.coerce` method is also supported on composite types.
In the case of :class:`.MutableComposite`, the :meth:`.MutableBase.coerce`
method is only called for attribute set operations, not load operations.
Overriding the :meth:`.MutableBase.coerce` method is essentially equivalent
to using a :func:`.validates` validation routine for all attributes which
make use of the custom composite type::
 
    @dataclasses.dataclass
    class Point(MutableComposite):
        # other Point methods
        # ...
 
        def coerce(cls, key, value):
            if isinstance(value, tuple):
                value = Point(*value)
            elif not isinstance(value, Point):
                raise ValueError("tuple or Point expected")
            return value
 
Supporting Pickling
--------------------
 
As is the case with :class:`.Mutable`, the :class:`.MutableComposite` helper
class uses a ``weakref.WeakKeyDictionary`` available via the
:meth:`MutableBase._parents` attribute which isn't picklable. If we need to
pickle instances of ``Point`` or its owning class ``Vertex``, we at least need
to define a ``__getstate__`` that doesn't include the ``_parents`` dictionary.
Below we define both a ``__getstate__`` and a ``__setstate__`` that package up
the minimal form of our ``Point`` class::
 
    @dataclasses.dataclass
    class Point(MutableComposite):
        # ...
 
        def __getstate__(self):
            return self.x, self.y
 
        def __setstate__(self, state):
            self.x, self.y = state
 
As with :class:`.Mutable`, the :class:`.MutableComposite` augments the
pickling process of the parent's object-relational state so that the
:meth:`MutableBase._parents` collection is restored to all ``Point`` objects.
 
é)Ú annotations)Ú defaultdict)Ú AbstractSet)ÚAny)ÚDict)ÚIterable)ÚList)ÚOptional)Úoverload)ÚSet)ÚTuple)Ú TYPE_CHECKING)ÚTypeVar)ÚUnionN)ÚWeakKeyDictionaryé)Úevent)Úinspect)Útypes)ÚMapper)Ú_ExternalEntityType)Ú_O)Ú_T)ÚAttributeEventToken)Ú flag_modified)ÚInstrumentedAttribute)ÚQueryableAttribute)Ú QueryContext)ÚDeclarativeAttributeIntercept)Ú InstanceState)ÚUOWTransaction)ÚSchemaEventTarget)ÚColumn)Ú
TypeEngine)Úmemoized_property)Ú SupportsIndex)Ú    TypeGuardÚ_KTÚ_VTc@sdeZdZdZeddœdd„ƒZedddd    œd
d „ƒZed d dœdd„ƒZed ddddœdd„ƒZ    dS)Ú MutableBasezPCommon base class to :class:`.Mutable`
    and :class:`.MutableComposite`.
 
    zWeakKeyDictionary[Any, Any]©ÚreturncCst ¡S)aåDictionary of parent object's :class:`.InstanceState`->attribute
        name on the parent.
 
        This attribute is a so-called "memoized" property.  It initializes
        itself with a new ``weakref.WeakKeyDictionary`` the first time
        it is accessed, returning the same object upon subsequent access.
 
        .. versionchanged:: 1.4 the :class:`.InstanceState` is now used
           as the key in the weak dictionary rather than the instance
           itself.
 
        )Úweakrefr©Úself©r/úMd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\sqlalchemy/ext/mutable.pyÚ_parentsšszMutableBase._parentsÚstrrz Optional[Any]©ÚkeyÚvaluer+cCs(|dkr dSd}t||t|ƒfƒ‚dS)a Given a value, coerce it into the target type.
 
        Can be overridden by custom subclasses to coerce incoming
        data into a particular type.
 
        By default, raises ``ValueError``.
 
        This method is called in different scenarios depending on if
        the parent class is of type :class:`.Mutable` or of type
        :class:`.MutableComposite`.  In the case of the former, it is called
        for both attribute-set operations as well as during ORM loading
        operations.  For the latter, it is only called during attribute-set
        operations; the mechanics of the :func:`.composite` construct
        handle coercion during load operations.
 
 
        :param key: string name of the ORM-mapped attribute being set.
        :param value: the incoming value.
        :return: the method should return the coerced value, or raise
         ``ValueError`` if the coercion cannot be completed.
 
        Nz1Attribute '%s' does not accept objects of type %s)Ú
ValueErrorÚtype)Úclsr4r5Úmsgr/r/r0Úcoerce«szMutableBase.coercezQueryableAttribute[Any]úSet[str]©Ú    attributer+cCs|jhS)aðGiven a descriptor attribute, return a ``set()`` of the attribute
        keys which indicate a change in the state of this attribute.
 
        This is normally just ``set([attribute.key])``, but can be overridden
        to provide for additional keys.  E.g. a :class:`.MutableComposite`
        augments this set with the attribute keys associated with the columns
        that comprise the composite value.
 
        This collection is consulted in the case of intercepting the
        :meth:`.InstanceEvents.refresh` and
        :meth:`.InstanceEvents.refresh_flush` events, which pass along a list
        of attribute names that have been refreshed; the list is compared
        against this set to determine if action needs to be taken.
 
        ©r4©r8r=r/r/r0Ú_get_listen_keysÈszMutableBase._get_listen_keysÚboolz_ExternalEntityType[Any]ÚNone)r=r:Ú
parent_clsr+cs2|j‰||jk    rdS|j}ˆ |¡‰ddddœ‡‡‡fdd„ ‰ddd    dd
œ‡‡fd d „ }dd d dd dœ‡‡fdd„ }ddddœ‡fdd„ }ddddœ‡fdd„ }tj|dˆdddtj|dˆdddtj|d|dddtj|d|dddtj|d|ddddtj|d |dddtj|d!|ddddS)"ú]Establish this type as a mutation listener for the given
        mapped descriptor.
 
        NzInstanceState[_O]rrB)ÚstateÚargsr+cs>|j ˆd¡}|dk    r:ˆr0ˆ ˆ|¡}||jˆ<ˆ|j|<dS)z„Listen for objects loaded or refreshed.
 
            Wrap the target data member's value with
            ``Mutable``.
 
            N)ÚdictÚgetr:r1)rErFÚval)r8r:r4r/r0Úloadïs  
z.MutableBase._listen_on_attribute.<locals>.loadz+Union[object, QueryContext, UOWTransaction]ú Iterable[Any])rEÚctxÚattrsr+cs|rˆ |¡rˆ|ƒdS©N)Ú intersection)rErLrM)Ú listen_keysrJr/r0Ú
load_attrsýsz4MutableBase._listen_on_attribute.<locals>.load_attrszMutableBase | Noner)Útargetr5ÚoldvalueÚ    initiatorr+csT||kr |St|ˆƒs"ˆ ˆ|¡}|dk    r4ˆ|j|<t|ˆƒrP|j t|ƒd¡|S)zÞListen for set/replace events on the target
            data member.
 
            Establish a weak reference to the parent object
            on the incoming value, remove it for the one
            outgoing.
 
            N)Ú
isinstancer:r1Úpopr)rRr5rSrT)r8r4r/r0Úset_s
 
 
z.MutableBase._listen_on_attribute.<locals>.set_zDict[str, Any])rEÚ
state_dictr+cs@|j ˆd¡}|dk    r<d|kr*ttƒ|d<|dˆ |¡dS©Nzext.mutable.values)rGrHrÚlistÚappend)rErXrIr>r/r0Úpickles
 z0MutableBase._listen_on_attribute.<locals>.picklecsPd|krL|d}t|tƒr0|D]}ˆ|j|<qn|dˆD]}ˆ|j|<q<dSrY)rUrZr1)rErXZ
collectionrIr>r/r0Úunpickle's
z2MutableBase._listen_on_attribute.<locals>.unpickleZ_sa_event_merge_wo_loadT)ÚrawÚ    propagaterJZrefreshZ refresh_flushÚset)r^Úretvalr_r\r])r4Úclass_r@rÚlisten)r8r=r:rCrQrWr\r]r/)r8r:r4rPrJr0Ú_listen_on_attributeÛs` 
 
     ûÿÿÿÿz MutableBase._listen_on_attributeN)
Ú__name__Ú
__module__Ú __qualname__Ú__doc__r$r1Ú classmethodr:r@rdr/r/r/r0r)”sr)c@sZeZdZdZddœdd„Zedddœdd    „ƒZed
dd œd d „ƒZeddd œdd„ƒZdS)ÚMutablezŸMixin that defines transparent propagation of change
    events to a parent object.
 
    See the example in :ref:`mutable_scalars` for usage information.
 
    rBr*cCs&|j ¡D]\}}t| ¡|ƒq
dS©z@Subclasses should call this method whenever change events occur.N)r1ÚitemsrÚobj)r.Úparentr4r/r/r0ÚchangedTszMutable.changedzInstrumentedAttribute[_O]r<cCs| |d|j¡dS)rDTN)rdrbr?r/r/r0Úassociate_with_attributeZsz Mutable.associate_with_attributer7)Úsqltyper+cs*ddddœ‡‡fdd„ }t td|¡dS)    aAssociate this wrapper with all future mapped columns
        of the given type.
 
        This is a convenience method that calls
        ``associate_with_attribute`` automatically.
 
        .. warning::
 
           The listeners established by this method are *global*
           to all mappers, and are *not* garbage collected.   Only use
           :meth:`.associate_with` for types that are permanent to an
           application, not with ad-hoc types else this will cause unbounded
           growth in memory usage.
 
        z
Mapper[_O]r7rB©Úmapperrbr+cs>|jr
dS|jD](}t|jdjˆƒrˆ t||jƒ¡qdS)Nr)Ú non_primaryÚ column_attrsrUÚcolumnsr7rpÚgetattrr4©rsrbÚprop©r8rqr/r0Úlisten_for_typevs
 
z/Mutable.associate_with.<locals>.listen_for_typeÚmapper_configuredN)rrcr)r8rqr{r/rzr0Úassociate_withdszMutable.associate_withzTypeEngine[_T]csht ˆ¡‰tˆtƒr8t ˆd¡ddddœdd„ƒ}d‰nd    ‰d
d dd œ‡‡‡fd d„ }t td|¡ˆS)aAssociate a SQL type with this mutable Python type.
 
        This establishes listeners that will detect ORM mappings against
        the given type, adding mutation event trackers to those mappings.
 
        The type is returned, unconditionally as an instance, so that
        :meth:`.as_mutable` can be used inline::
 
            Table('mytable', metadata,
                Column('id', Integer, primary_key=True),
                Column('data', MyMutableType.as_mutable(PickleType))
            )
 
        Note that the returned type is always an instance, even if a class
        is given, and that only columns which are declared specifically with
        that type instance receive additional instrumentation.
 
        To associate a particular mutable type with all occurrences of a
        particular type, use the :meth:`.Mutable.associate_with` classmethod
        of the particular :class:`.Mutable` subclass to establish a global
        association.
 
        .. warning::
 
           The listeners established by this method are *global*
           to all mappers, and are *not* garbage collected.   Only use
           :meth:`.as_mutable` for types that are permanent to an application,
           not with ad-hoc types else this will cause unbounded growth
           in memory usage.
 
        Zbefore_parent_attachzTypeEngine[Any]z
Column[_T]rB)Úsqltyprnr+cSs||jd<dS)NÚ_ext_mutable_orig_type)Úinfo)r~rnr/r/r0Ú_add_column_memo§sz,Mutable.as_mutable.<locals>._add_column_memoTFú
Mapper[_T]z*Union[DeclarativeAttributeIntercept, type]rrcsz|jr
dSd}|jD]`}t|jtƒrˆr:|jj d¡ˆksF|jjˆkr|jj |d¡sd|jj|<ˆ t    ||j
ƒ¡qdS)NZ_ext_mutable_listener_appliedrFT) rtrurUZ
expressionr"r€rHr7rprwr4)rsrbZ _APPLIED_KEYry©r8Zschema_event_checkrqr/r0r{²s&
 
üùÿýø
ó z+Mutable.as_mutable.<locals>.listen_for_typer|)rZ to_instancerUr!rZ listens_forrcr)r8rqrr{r/rƒr0Ú
as_mutables!
 
 
zMutable.as_mutableN)    rerfrgrhrorirpr}r„r/r/r/r0rjLs    rjc@s2eZdZdZedddœdd„ƒZddœd    d
„Zd S) ÚMutableCompositezÖMixin that defines transparent propagation of change
    events on a SQLAlchemy "composite" object to its
    owning parent or parents.
 
    See the example in :ref:`mutable_composites` for usage information.
 
    zQueryableAttribute[_O]r;r<cCs|jh |jj¡SrN)r4ÚunionÚpropertyÚ_attribute_keysr?r/r/r0r@Ýsz!MutableComposite._get_listen_keysrBr*cCsP|j ¡D]@\}}|j |¡}t| |¡|jƒD]\}}t| ¡||ƒq0q
dSrk)    r1rlrsZ get_propertyÚzipZ_composite_values_from_instancerˆÚsetattrrm)r.rnr4ryr5Ú    attr_namer/r/r0roás þ zMutableComposite.changedN)rerfrgrhrir@ror/r/r/r0r…Ôsr…rBr*cCs2ddddœdd„}t td|¡s.t td|¡dS)Nr‚r7rBrrcSsJ|jD]>}t|dƒrt|jtƒrt|jtƒr|j t||j    ƒd|¡qdS)NÚcomposite_classF)
Ziterate_propertiesÚhasattrrUrŒr7Ú
issubclassr…rdrwr4rxr/r/r0Ú_listen_for_typeîs
ÿ
þ
ý
ÿz3_setup_composite_listener.<locals>._listen_for_typer|)rÚcontainsrrc)rr/r/r0Ú_setup_composite_listenerís r‘csReZdZdZddddœ‡fdd„ Zerled3d    ddd
d œd d „ƒZeddddœdd „ƒZd4ddddœdd „Zn ‡fdd „Zdddœ‡fdd„ Zddddœ‡fdd„ Z    eræedddœdd„ƒZ
eddddœdd„ƒZ
d5ddddœd d„Z
n ‡fd!d„Z
d"d#œ‡fd$d%„ Z dd#œ‡fd&d'„ Z e d(dd)dœd*d+„ƒZd,d#œd-d.„Zd/dd0œd1d2„Z‡ZS)6Ú MutableDictajA dictionary type that implements :class:`.Mutable`.
 
    The :class:`.MutableDict` object implements a dictionary that will
    emit change events to the underlying mapping when the contents of
    the dictionary are altered, including when values are added or removed.
 
    Note that :class:`.MutableDict` does **not** apply mutable tracking to  the
    *values themselves* inside the dictionary. Therefore it is not a sufficient
    solution for the use case of tracking deep changes to a *recursive*
    dictionary structure, such as a JSON structure.  To support this use case,
    build a subclass of  :class:`.MutableDict` that provides appropriate
    coercion to the values placed in the dictionary so that they too are
    "mutable", and emit events up to their parent structure.
 
    .. seealso::
 
        :class:`.MutableList`
 
        :class:`.MutableSet`
 
    r'r(rBr3cstƒ ||¡| ¡dS)z4Detect dictionary set events and emit change events.N)ÚsuperÚ __setitem__ro©r.r4r5©Ú    __class__r/r0r”szMutableDict.__setitem__NzMutableDict[_KT, Optional[_T]]z Optional[_T])r.r4r5r+cCsdSrNr/r•r/r/r0Ú
setdefaultszMutableDict.setdefaultcCsdSrNr/r•r/r/r0r˜%sÚobjectcCsdSrNr/r•r/r/r0r˜)scstƒj|Ž}| ¡|SrN)r“r˜ro©r.ÚargÚresultr–r/r0r˜.s )r4r+cstƒ |¡| ¡dS)z4Detect dictionary del events and emit change events.N©r“Ú __delitem__ro)r.r4r–r/r0rž3s zMutableDict.__delitem__r)ÚaÚkwr+cstƒj||Ž| ¡dSrN©r“Úupdatero)r.rŸr r–r/r0r¢8szMutableDict.update)Ú_MutableDict__keyr+cCsdSrNr/)r.r£r/r/r0rV>szMutableDict.popz_VT | _T)r£Ú_MutableDict__defaultr+cCsdSrNr/©r.r£r¤r/r/r0rVBsz_VT | _T | NonecCsdSrNr/r¥r/r/r0rVFscstƒj|Ž}| ¡|SrN©r“rVroršr–r/r0rVMs zTuple[_KT, _VT]r*cstƒ ¡}| ¡|SrN)r“Úpopitemro)r.rœr–r/r0r§Rs
zMutableDict.popitemcstƒ ¡| ¡dSrN©r“Úclearror-r–r/r0r©Ws
zMutableDict.clearr2zMutableDict[_KT, _VT] | NonecCs0t||ƒs(t|tƒr||ƒSt ||¡S|SdS)z3Convert plain dictionary to instance of this class.N)rUrGrjr:©r8r4r5r/r/r0r:[s
 
 
 zMutableDict.coercezDict[_KT, _VT]cCst|ƒSrN)rGr-r/r/r0Ú __getstate__eszMutableDict.__getstate__z%Union[Dict[str, int], Dict[str, str]]©rEr+cCs| |¡dSrN©r¢©r.rEr/r/r0Ú __setstate__hszMutableDict.__setstate__)N)N)N)rerfrgrhr”r r
r˜ržr¢rVr§r©rir:r«r¯Ú __classcell__r/r/r–r0r’s4ÿ ÿ     r’csBeZdZdZdddœdd„Zddd    œd
d „Zd d dœdd„Zd ddœdd„Zdd ddœ‡fdd„ Zdddœ‡fdd„ Z    dddœ‡fdd„ Z
dddœ‡fd d!„ Z dddœ‡fd"d#„ Z dd$dœd%d&„Z dddd'œ‡fd(d)„ Zddd*œ‡fd+d,„ Zdd-œ‡fd.d/„ Zd0dd1œ‡fd2d3„ Zdd-œ‡fd4d5„ Zed6d7d8d9œd:d;„ƒZ‡ZS)<Ú MutableListaOA list type that implements :class:`.Mutable`.
 
    The :class:`.MutableList` object implements a list that will
    emit change events to the underlying mapping when the contents of
    the list are altered, including when values are added or removed.
 
    Note that :class:`.MutableList` does **not** apply mutable tracking to  the
    *values themselves* inside the list. Therefore it is not a sufficient
    solution for the use case of tracking deep changes to a *recursive*
    mutable structure, such as a JSON structure.  To support this use case,
    build a subclass of  :class:`.MutableList` that provides appropriate
    coercion to the values placed in the dictionary so that they too are
    "mutable", and emit events up to their parent structure.
 
    .. seealso::
 
        :class:`.MutableDict`
 
        :class:`.MutableSet`
 
    r%úTuple[type, Tuple[List[int]]]©Úprotor+cCs|jt|ƒffSrN©r—rZ©r.r´r/r/r0Ú __reduce_ex__…szMutableList.__reduce_ex__ú Iterable[_T]rBr¬cCs||dd…<dSrNr/r®r/r/r0r¯ŒszMutableList.__setstate__z_T | Iterable[_T]z TypeGuard[_T])r5r+cCs t|tƒ SrN©rUr©r.r5r/r/r0Ú    is_scalarszMutableList.is_scalarzTypeGuard[Iterable[_T]]cCs
t|tƒSrNr¹rºr/r/r0Ú is_iterable’szMutableList.is_iterablezSupportsIndex | slice©Úindexr5r+csRt|tƒr$| |¡r$tƒ ||¡n"t|tƒrF| |¡rFtƒ ||¡| ¡dS)z.Detect list set events and emit change events.N)rUr%r»r“r”Úslicer¼ro)r.r¾r5r–r/r0r”•s
zMutableList.__setitem__)r¾r+cstƒ |¡| ¡dS)z.Detect list del events and emit change events.Nr)r.r¾r–r/r0ržŸs zMutableList.__delitem__r©r›r+cstƒj|Ž}| ¡|SrNr¦ršr–r/r0rV¤s zMutableList.pop)Úxr+cstƒ |¡| ¡dSrN)r“r[ro©r.rÁr–r/r0r[©s zMutableList.appendcstƒ |¡| ¡dSrN)r“ÚextendrorÂr–r/r0rís zMutableList.extendzMutableList[_T]cCs| |¡|SrN)rÃrÂr/r/r0Ú__iadd__±s
zMutableList.__iadd__)ÚirÁr+cstƒ ||¡| ¡dSrN)r“Úinsertro)r.rÅrÁr–r/r0rƵszMutableList.insert)rÅr+cstƒ |¡| ¡dSrN©r“Úremovero)r.rÅr–r/r0rȹs zMutableList.remover*cstƒ ¡| ¡dSrNr¨r-r–r/r0r©½s
zMutableList.clearr)r r+c stƒjf|Ž| ¡dSrN)r“Úsortro)r.r r–r/r0rÉÁszMutableList.sortcstƒ ¡| ¡dSrN)r“Úreverseror-r–r/r0rÊÅs
zMutableList.reverser2zMutableList[_T] | _TzOptional[MutableList[_T]]r3cCs0t||ƒs(t|tƒr||ƒSt ||¡S|SdS)z-Convert plain list to instance of this class.N)rUrZrjr:rªr/r/r0r:És
 
 
 zMutableList.coerce)rerfrgrhr·r¯r»r¼r”ržrVr[rÃrÄrÆrÈr©rÉrÊrir:r°r/r/r–r0r±ns$
r±csJeZdZdZdddœ‡fdd„ Zdddœ‡fdd    „ Zdddœ‡fd
d „ Zdddœ‡fd d „ Zdddœdd„Zdddœdd„Z    dddœdd„Z
dddœdd„Z dddœ‡fdd„ Z dddœ‡fdd„ Z dddœ‡fd d!„ Zd"ddœ‡fd#d$„ Zdd%œ‡fd&d'„ Zed(d"d)d*œd+d,„ƒZd-d%œd.d/„Zddd0œd1d2„Zd3d4d5œd6d7„Z‡ZS)8Ú
MutableSeta0A set type that implements :class:`.Mutable`.
 
    The :class:`.MutableSet` object implements a set that will
    emit change events to the underlying mapping when the contents of
    the set are altered, including when values are added or removed.
 
    Note that :class:`.MutableSet` does **not** apply mutable tracking to  the
    *values themselves* inside the set. Therefore it is not a sufficient
    solution for the use case of tracking deep changes to a *recursive*
    mutable structure.  To support this use case,
    build a subclass of  :class:`.MutableSet` that provides appropriate
    coercion to the values placed in the dictionary so that they too are
    "mutable", and emit events up to their parent structure.
 
    .. seealso::
 
        :class:`.MutableDict`
 
        :class:`.MutableList`
 
 
    r¸rBrÀcstƒj|Ž| ¡dSrNr¡©r.r›r–r/r0r¢îs zMutableSet.updaterKcstƒj|Ž| ¡dSrN)r“Úintersection_updaterorÌr–r/r0rÍòs zMutableSet.intersection_updatecstƒj|Ž| ¡dSrN)r“Údifference_updaterorÌr–r/r0rÎös zMutableSet.difference_updatecstƒj|Ž| ¡dSrN)r“Úsymmetric_difference_updaterorÌr–r/r0rÏús z&MutableSet.symmetric_difference_updatezAbstractSet[_T]zMutableSet[_T])Úotherr+cCs| |¡|SrNr­©r.rÐr/r/r0Ú__ior__þs
zMutableSet.__ior__zAbstractSet[object]cCs| |¡|SrN)rÍrÑr/r/r0Ú__iand__s
zMutableSet.__iand__cCs| |¡|SrN)rÏrÑr/r/r0Ú__ixor__s
zMutableSet.__ixor__cCs| |¡|SrN)rÎrÑr/r/r0Ú__isub__
s
zMutableSet.__isub__r)Úelemr+cstƒ |¡| ¡dSrN)r“Úaddro©r.rÖr–r/r0r×s zMutableSet.addcstƒ |¡| ¡dSrNrÇrØr–r/r0rÈs zMutableSet.removecstƒ |¡| ¡dSrN)r“ÚdiscardrorØr–r/r0rÙs zMutableSet.discardrcstƒj|Ž}| ¡|SrNr¦ršr–r/r0rVs zMutableSet.popr*cstƒ ¡| ¡dSrNr¨r-r–r/r0r©s
zMutableSet.clearr2zOptional[MutableSet[_T]]r½cCs0t||ƒs(t|tƒr||ƒSt ||¡S|SdS)z,Convert plain set to instance of this class.N)rUr`rjr:)r8r¾r5r/r/r0r:#s
 
 
 zMutableSet.coercezSet[_T]cCst|ƒSrN)r`r-r/r/r0r«-szMutableSet.__getstate__r¬cCs| |¡dSrNr­r®r/r/r0r¯0szMutableSet.__setstate__r%r²r³cCs|jt|ƒffSrNrµr¶r/r/r0r·3szMutableSet.__reduce_ex__)rerfrgrhr¢rÍrÎrÏrÒrÓrÔrÕr×rÈrÙrVr©rir:r«r¯r·r°r/r/r–r0rËÖs&    rË)?rhÚ
__future__rÚ collectionsrÚtypingrrrrrr    r
r r r rrr,rÚrrrZormrZ orm._typingrrrZorm.attributesrrrrZ orm.contextrZ orm.decl_apirZ    orm.staterZorm.unitofworkr Zsql.baser!Z
sql.schemar"Z sql.type_apir#Úutilr$Z util.typingr%r&r'r(r)rjr…r‘r’r±rËr/r/r/r0Ú<module>sfb                                    9    nh