o znhA@s*dZddlZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lm Z dd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z d d!lm!Z!d d"lm"Z"d d#lm#Z#e"j$Gd$d%d%ej%ej&ej'Z(Gd&d'd'e(Z)d(d)Z*e#+d*Z,e#+d+Z-e#+d,Z.e#+d-Z/e#+d.Z0Gd/d0d0e1Z2Gd1d2d2e1Z3Gd3d4d4e3Z4Gd5d6d6e4Z5Gd7d8d8e3Z6d9d:Z7e#+d;Z8e9e:ee:ee:egZ;e#d<defd?d@Z?efdAdBZ@d^dDdEZAdFdGZB C  C  d_dHdIZC d`dJdKZDdLdMZEdNdOZFdPdQZGdRdSZHdadTdUZIdVdWZJdXdYZKdZd[ZLd\d]ZMdS)bzDefines instrumentation for class attributes and their interaction with instances. This module is usually not directly visible to user applications, but defines a large part of the ORM's interactivity. N) collections)exc) interfaces) ATTR_EMPTY) ATTR_WAS_SET) CALLABLES_OK)INIT_OK) instance_dictinstance_state) instance_str)LOAD_AGAINST_COMMITTED)manager_of_class) NEVER_SET) NO_AUTOFLUSH) NO_CHANGE)NO_RAISE)NO_VALUE)NON_PERSISTENT_OK)PASSIVE_NO_FETCH)PASSIVE_NO_FETCH_RELATED)PASSIVE_NO_INITIALIZE)PASSIVE_NO_RESULT) PASSIVE_OFF)PASSIVE_ONLY_PERSISTENT)PASSIVE_RETURN_NEVER_SET)RELATED_OBJECT_OK)SQL_OK) state_str)event) inspection)utilc@seZdZdZdZ    d-ddZejddZe dd Z e fd d Z d d Z ejddZejddZe ddZddZddZddZddZddZddZd d!Zd"d#Zd.d%d&Zd'd(Zd)d*Zejd+d,Z dS)/QueryableAttributeaBase class for :term:`descriptor` objects that intercept attribute events on behalf of a :class:`.MapperProperty` object. The actual :class:`.MapperProperty` is accessible via the :attr:`.QueryableAttribute.property` attribute. .. seealso:: :class:`.InstrumentedAttribute` :class:`.MapperProperty` :attr:`.Mapper.all_orm_descriptors` :attr:`.Mapper.attrs` TNc Csr||_||_||_||_||_||_t|}|r5|jD]}||vr4|j ||j||jj r4d|j_ qdSdSNT) class_keyimpl comparator _parententity_of_typer_basesdispatch_update_active_history) selfr&r'r(r) parententityof_typemanagerbaser5D/usr/local/lib/python3.10/dist-packages/sqlalchemy/orm/attributes.py__init__Ns    zQueryableAttribute.__init__cC|jjSN)r(supports_populationr0r5r5r6_supports_populationiz'QueryableAttribute._supports_populationcCr8r9)r( uses_objectsr;r5r5r6_impl_uses_objectsmr=z%QueryableAttribute._impl_uses_objectscCs|jt|t||Sr9)r( get_historyr r )r0instancepassiver5r5r6r@qszQueryableAttribute.get_historycCs|Sr9r5r;r5r5r6__selectable__vsz!QueryableAttribute.__selectable__cCr8)aReturn the 'info' dictionary for the underlying SQL element. The behavior here is as follows: * If the attribute is a column-mapped property, i.e. :class:`.ColumnProperty`, which is mapped directly to a schema-level :class:`.Column` object, this attribute will return the :attr:`.SchemaItem.info` dictionary associated with the core-level :class:`.Column` object. * If the attribute is a :class:`.ColumnProperty` but is mapped to any other kind of SQL expression other than a :class:`.Column`, the attribute will refer to the :attr:`.MapperProperty.info` dictionary associated directly with the :class:`.ColumnProperty`, assuming the SQL expression itself does not have its own ``.info`` attribute (which should be the case, unless a user-defined SQL construct has defined one). * If the attribute refers to any other kind of :class:`.MapperProperty`, including :class:`.RelationshipProperty`, the attribute will refer to the :attr:`.MapperProperty.info` dictionary associated with that :class:`.MapperProperty`. * To access the :attr:`.MapperProperty.info` dictionary of the :class:`.MapperProperty` unconditionally, including for a :class:`.ColumnProperty` that's associated directly with a :class:`.schema.Column`, the attribute can be referred to using :attr:`.QueryableAttribute.property` attribute, as ``MyClass.someattribute.property.info``. .. seealso:: :attr:`.SchemaItem.info` :attr:`.MapperProperty.info` )r)infor;r5r5r6rDzs'zQueryableAttribute.infocCs t|jS)aReturn an inspection instance representing the parent. This will be either an instance of :class:`.Mapper` or :class:`.AliasedInsp`, depending upon the nature of the parent entity which this attribute is associated with. )r"inspectr*r;r5r5r6parents zQueryableAttribute.parentcC |jSr9r)__clause_element__r;r5r5r6 expressions zQueryableAttribute.expressioncCrGr9rHr;r5r5r6rIs z%QueryableAttribute.__clause_element__cCrG)zhlike __clause_element__(), but called specifically by :class:`.Query` to allow special behavior.)r)_query_clause_elementr;r5r5r6rKs z(QueryableAttribute._query_clause_elementcC |j|S)z'Return setter tuples for a bulk UPDATE.)r)_bulk_update_tuplesr0valuer5r5r6rMs z&QueryableAttribute._bulk_update_tuplescCs,|jrJ|j|j|j|j|j||dS)N)r(r)r1)r+ __class__entityr'r(r)adapt_to_entityr0rRr5r5r6rRs  z"QueryableAttribute.adapt_to_entitycCs$t|j|j|j|j||j|dS)N)r2)r$r&r'r(r)r2r*)r0clsr5r5r6r2s zQueryableAttribute.of_typecCs||Sr9)rKlabel)r0namer5r5r6rUszQueryableAttribute.labelcOs||jg|Ri|Sr9r)r0opotherkwargsr5r5r6operatezQueryableAttribute.operatecKs|||jfi|Sr9rWrXr5r5r6reverse_operatez"QueryableAttribute.reverse_operateFcCs|jj||dduS)N) optimisticFr( hasparent)r0stater`r5r5r6rbr_zQueryableAttribute.hasparentc Cs@zt|j|WStytdt|jt|jj||fw)NFNeither %r object nor %r object associated with %s has an attribute %r)getattrr)AttributeErrortype__name__)r0r'r5r5r6 __getattr__s  zQueryableAttribute.__getattr__cCd|jj|jfSNz%s.%sr&rhr'r;r5r5r6__str__zQueryableAttribute.__str__cCr8)zReturn the :class:`.MapperProperty` associated with this :class:`.QueryableAttribute`. Return values here will commonly be instances of :class:`.ColumnProperty` or :class:`.RelationshipProperty`. r)propertyr;r5r5r6rps zQueryableAttribute.property)NNNNF)rh __module__ __qualname____doc__ is_attributer7r#memoized_propertyr<rpr?rr@rCrDrFrJrIrKrMrRr2rUr\r^rbrirmr5r5r5r6r$4sB     (     r$c@s(eZdZdZddZddZddZdS) InstrumentedAttributezClass bound instrumented attribute which adds basic :term:`descriptor` methods. See :class:`.QueryableAttribute` for a description of most features. cCs|jt|t||ddSr9)r(setr r )r0rArOr5r5r6__set__ szInstrumentedAttribute.__set__cCs|jt|t|dSr9)r(deleter r )r0rAr5r5r6 __delete__sz InstrumentedAttribute.__delete__cCs@|dur|St|}|jr|j|vr||jS|jt||Sr9)r r<r'r(getr )r0rAownerdict_r5r5r6__get__s  zInstrumentedAttribute.__get__N)rhrrrsrtryr{rr5r5r5r6rws  rwcs>Gfdddt}tjd|_tj|tdd|S)zCreate an QueryableAttribute / user descriptor hybrid. Returns a new QueryableAttribute type that delegates descriptor behavior and getattr() to the given descriptor. csneZdZdZ   dddZdZeddZedd Zej d d Z d d Z ddZ ddZ fddZdS)z'create_proxied_attribute..ProxyzPresents the :class:`.QueryableAttribute` interface as a proxy on top of a Python descriptor / :class:`.PropComparator` combination. NcSs.||_||_||_||_||_||_||_dSr9)r&r' descriptororiginal_property _comparator_adapt_to_entityrt)r0r&r'rr)rRdocrr5r5r6r7.s  z0create_proxied_attribute..Proxy.__init__TcSs|jduo t|j|jjjSr9)rrer&r'r(r>r;r5r5r6r?Bs z:create_proxied_attribute..Proxy._impl_uses_objectscSr8r9ror;r5r5r6rpIr=z0create_proxied_attribute..Proxy.propertycSs2t|jr ||_|jr|j|j|_|jSr9)r#callablerrrRr;r5r5r6r)Ms  z2create_proxied_attribute..Proxy.comparatorcSs||j|j|j|j|Sr9)rPrQr'rrrSr5r5r6rRWsz7create_proxied_attribute..Proxy.adapt_to_entitycSs(|j||}||jur|dur|S|Sr9)rr)r0rAr}retvalr5r5r6r`sz/create_proxied_attribute..Proxy.__get__cSrjrkrlr;r5r5r6rmjrnz/create_proxied_attribute..Proxy.__str__c szt|WStyN|dkrtdz|j}Wnty-tdtj||fwzt||WYStyMtdtjt|j||fww)zNDelegate __getattr__ to the original descriptor and/or comparator.r)z[Neither %r object nor unconfigured comparator object associated with %s has an attribute %rrd)rerfr)rgrh)r0 attributer)rr5r6rims8     z3create_proxied_attribute..Proxy.__getattr__NNN)rhrrrsrtr7_is_internal_proxyrpr?r#rvr)rRrrmrir5rr5r6Proxy's"        rr)rV from_instance)r$rgrhr#monkeypatch_proxied_specials)rrr5rr6create_proxied_attributes  f rREMOVEAPPENDREPLACE BULK_REPLACEMODIFIEDc@s8eZdZdZdZddZddZeddZd d Z d S) EventaA token propagated throughout the course of a chain of attribute events. Serves as an indicator of the source of the event and also provides a means of controlling propagation across a chain of attribute operations. The :class:`.Event` object is sent as the ``initiator`` argument when dealing with events such as :meth:`.AttributeEvents.append`, :meth:`.AttributeEvents.set`, and :meth:`.AttributeEvents.remove`. The :class:`.Event` object is currently interpreted by the backref event handlers, and is used to control the propagation of operations across two mutually-dependent attributes. .. versionadded:: 0.9.0 :var impl: The :class:`.AttributeImpl` which is the current event initiator. :var op: The symbol :attr:`.OP_APPEND`, :attr:`.OP_REMOVE`, :attr:`.OP_REPLACE`, or :attr:`.OP_BULK_REPLACE`, indicating the source operation. r(rY parent_tokencCs||_||_|jj|_dSr9r)r0attribute_implrYr5r5r6r7szEvent.__init__cCs"t|to|j|juo|j|jkSr9) isinstancerr(rY)r0rZr5r5r6__eq__s   z Event.__eq__cCr8r9)r(r'r;r5r5r6r'r=z Event.keycCrLr9ra)r0rcr5r5r6rb zEvent.hasparentN) rhrrrsrt __slots__r7rrpr'rbr5r5r5r6rs  rc@seZdZdZ        d&ddZdZdd Zd d Zd d Ze eeZ d'ddZ ddZ e fddZefddZddZe fddZe fddZe fddZe fddZe ddfd d!Ze fd"d#Zd$d%ZdS)( AttributeImplz4internal implementation for instrumented attributes.FNTc Ks||_||_||_||_||_| p||_| |_|dur tj|_ n||_ | dur+| |_ n|j |_ t ||}t |p:gD]}|||q<|rKd|j_| |_t|t|_dS)a&Construct an AttributeImpl. :param \class_: associated class :param key: string name of the attribute :param \callable_: optional function which generates a callable based on a parent instance, which produces the "default" values for a scalar or collection attribute when it's first accessed, if not present already. :param trackparent: if True, attempt to track if an instance has a parent attached to it via this attribute. :param extension: a single or list of AttributeExtension object(s) which will receive set/delete/append/remove/etc. events. The event package is now used. .. deprecated:: 1.3 The :paramref:`.AttributeImpl.extension` parameter is deprecated and will be removed in a future release, corresponding to the "extension" parameter on the :class:`.MapperProprty` classes like :func:`.column_property` and :func:`.relationship` The events system is now used. :param compare_function: a function that compares two values which are normally assignable to this attribute. :param active_history: indicates that get_history() should always return the "old" value, even if it means executing a lazy callable upon attribute change. :param parent_token: Usually references the MapperProperty, used as a key for the hasparent() function to identify an "owning" attribute. Allows multiple AttributeImpls to all match a single owner attribute. :param expire_missing: if False, don't add an "expiry" callable to this attribute during state.expire_attributes(None), if no value is present for this key. :param send_modified_events: if False, the InstanceState._modified_event method will have no effect; this means the attribute will never show up as changed in a history entry. NT)r&r' callable_r- trackparentrsend_modified_eventsoperatoreqis_equalaccepts_scalar_loaderdefault_accepts_scalar_loaderrr#to_list_adapt_listenerr/expire_missingr OP_MODIFIED_modified_token)r0r&r'rr-r extensioncompare_functionactive_historyrrrrr[attrextr5r5r6r7s(F   zAttributeImpl.__init__) r&r'rr-rrrrrrrcCrjrkrlr;r5r5r6rmCrnzAttributeImpl.__str__cCr8)z(Backwards compat for impl.active_historyr-r/r;r5r5r6_get_active_historyFsz!AttributeImpl._get_active_historycCs ||j_dSr9rrNr5r5r6_set_active_historyKrz!AttributeImpl._set_active_historycCs*d}|js J||jt|j|duS)a4Return the boolean value of a `hasparent` flag attached to the given state. The `optimistic` flag determines what the default return value should be if no `hasparent` flag can be located. As this function is used to determine if an instance is an *orphan*, instances that were loaded from storage should be assumed to not be orphans, until a True/False value for this flag is set. An instance attribute that is loaded by a callable function will also not have a `hasparent` flag. 6This AttributeImpl is not configured to track parents.F)rparentsr|idr)r0rcr`msgr5r5r6rbPszAttributeImpl.hasparentcCsd}|js J|t|j}|r||j|<dS||jvrB|j|}|durB|j|jkrB|dur@tdt|t||jfdSd|j|<dS)zSet a boolean flag on the given item corresponding to whether or not it is attached to a parent object via the attribute represented by this ``InstrumentedAttribute``. rFNzRemoving state %s from parent state %s along attribute '%s', but the parent record has gone stale, can't be sure this is the most recent parent.) rrrrr'objorm_excStaleDataErrorr)r0rc parent_staterOrid_ last_parentr5r5r6 sethasparentgs(      zAttributeImpl.sethasparentcCtr9NotImplementedErrorr0rcr~rBr5r5r6r@szAttributeImpl.get_historycCr)aReturn a list of tuples of (state, obj) for all objects in this attribute's current state + history. Only applies to object-based attributes. This is an inlining of existing functionality which roughly corresponds to: get_state_history( state, key, passive=PASSIVE_NO_INITIALIZE).sum() rrr5r5r6get_all_pendingszAttributeImpl.get_all_pendingcCs.d}|jjD]}||||}|tur|}q|S)z;Initialize the given state's attribute with an empty value.N)r- init_scalarr)r0rcr~rOfnretr5r5r6 initializes  zAttributeImpl.initializecCs|j|vr ||jS|j}||jvs|j|turs|t@stS||jvr+|||}n||jvr;|j|}|||}n |jrE|||}nt }|tusO|turQ|S|t urhz||WSt ygt d|w|t urs| |||S|t @sytS|||S)zRetrieve a value from the given object. If a callable is assembled on this object's attribute, and passive is False, the callable will be executed and the resulting value will be set as the new value for this attribute. z=Deferred loader for attribute %r failed to populate correctly)r'committed_staterrrexpired_attributes _load_expired callablesrrrKeyErrorset_committed_valuer r)r0rcr~rBr'rOrr5r5r6r|s@          zAttributeImpl.getcCs|j|||||ddSNrBrxr0rcr~rO initiatorrBr5r5r6appendr]zAttributeImpl.appendcCs|j||d|||ddS)N)rB check_oldrrr5r5r6removes  zAttributeImpl.removec Cs|j||d|||dddS)NT)rBrpoprrr5r5r6rs zAttributeImpl.popcCrr9r)r0rcr~rOrrBrrr5r5r6rxs zAttributeImpl.setcCs<|j|jvr|j|j}|ttfvrdS|S|j|||dS)z,return the unchanged value of this attributeNr)r'rrrr|)r0rcr~rBrOr5r5r6get_committed_values   z!AttributeImpl.get_committed_valuecCs|||j<|||jg|S)z=set an attribute value on the given instance and 'commit' it.)r'_commit)r0rcr~rOr5r5r6r s z!AttributeImpl.set_committed_value)FNNFNTTNrq)rhrrrsrtr7rrmrrrprrbrrr@rrrr|rrrrxrrr5r5r5r6rs> d   '  1   rcsxeZdZdZdZdZdZdZdZdZ fddZ ddZ e fd d Z e d dfd d ZddZddZeddZZS)ScalarAttributeImplz8represents a scalar value-holding InstrumentedAttribute.TF)_replace_token _append_token _remove_tokencs8tt|j|i|t|t|_|_t|t|_dSr9) superrr7r OP_REPLACErr OP_REMOVEr)r0argkwrPr5r6r7szScalarAttributeImpl.__init__cCs|jjr |||t}n||jt}|jjr |||||j| |||| |jt}|turE|turG|j sI|j|j vrKt d|dSdSdSdS)N%s object does not have a value)r-r/r|rr'rrfire_remove_eventr_modified_eventrexpiredrrfr0rcr~oldexistingr5r5r6rz"s   zScalarAttributeImpl.deletecCX|j|vrt||||jS|t@r|tN}|j|||d}|tur%tSt|||Sr)r'Historyfrom_scalar_attributer r|r HISTORY_BLANKr0rcr~rBcurrentr5r5r6r@5 zScalarAttributeImpl.get_historyNc Cs\|jjr |||t}n||jt}|jjr ||||||}|||||||j<dSr9) r-r/r|rr'rrxfire_replace_eventr r0rcr~rOrrBrrrr5r5r6rxAs  zScalarAttributeImpl.setcCs&|jjD] }|||||p|j}q|Sr9)r-rxrr0rcr~rOpreviousrrr5r5r6rWs z&ScalarAttributeImpl.fire_replace_eventcCs$|jjD] }||||p |jqdSr9)r-rrr0rcr~rOrrr5r5r6r^s z%ScalarAttributeImpl.fire_remove_eventcCs|jjdjdS)Nr)rpcolumnsrgr;r5r5r6rgbszScalarAttributeImpl.type)rhrrrsrtrr>r: collectiondynamicrr7rzrr@rxrrrprg __classcell__r5r5rr6rs&   rc@sdeZdZdZdZdZdZdZdZddZ e fddZ e fd d Z e d dfd d ZddZddZd S)ScalarObjectAttributeImplzrepresents a scalar-holding InstrumentedAttribute, where the target object is also instrumented. Adds events to delete/set operations. FTr5cCs|jjr|j||ttBtBd}n|j||ttAtBtBd}| ||||j | |j t }|t urB|turD|j durFtd|dSdSdS)Nrr)r-r/r|rrrrr rrrrr'rrrfrr5r5r6rzvs8  z ScalarObjectAttributeImpl.deletecCrr)r'rfrom_object_attributer r|rrrr5r5r6r@rz%ScalarObjectAttributeImpl.get_historycCs|j|vr ||j}n|t@r|j|||d}ngS|dur.|tur.|tur.t||fg}ndg}|j|jvrV|j|j}|durV|turV|turV||urV|t||f|S)Nr)NN)r'rr|rrr rr)r0rcr~rBrroriginalr5r5r6rs$    z)ScalarObjectAttributeImpl.get_all_pendingNc Cs|jjr|j||ttBtBd}n|j||ttAtBtBd}|dur=|t ur=||ur=|r/dSt dt |t ||j f||||||}|||j <dS)z1Set a value on the given InstanceState. rNz2Object %s not associated with %s on attribute '%s')r-r/r|rrrrr rr ValueErrorr rr'rrr5r5r6rxs>  zScalarObjectAttributeImpl.setcCsR|jr|dur|t||d|jjD] }||||p|jq||||dS)NF)rrr r-rrrrr5r5r6rs  z+ScalarObjectAttributeImpl.fire_remove_eventcCs|jr||ur|dttfvr|t||d|jjD] }|||||p%|j}q|||||jr?|dur?|t||d|SNFT) rrrrr r-rxrrrr5r5r6rs   z,ScalarObjectAttributeImpl.fire_replace_event)rhrrrsrtrr>r:rrrzrr@rrrxrrr5r5r5r6rgs  $ . rcseZdZdZdZdZdZdZdZdZ     d(fdd Z dd Z e fd d Z efd d ZddZddZddZddZddZddZe fddZe fddZe fddZde ddfd d!Zd"d#Zd$d%Zde fd&d'ZZS))CollectionAttributeImplaA collection-holding attribute that instruments changes in membership. Only handles collections of instrumented objects. InstrumentedCollectionAttribute holds an arbitrary, user-specified container object (defaulting to a list) and brokers access to the CollectionAdapter, a "view" onto that object that presents consistent bag semantics to the orm layer independent of the user data implementation. FT)copycollection_factoryrr_bulk_replace_token_duck_typed_asNc  stt|j||||f||| d| |dur|j}||_||_t|t|_t|t |_ t|t |_ t ||_t|jddrWt|ddd} t|ddd} dSdS) N)rrr _sa_linkerinit_collectioncSs||dSr9rtargetrcollection_adapterr5r5r6linkNz.CollectionAttributeImpl.__init__..linkdispose_collectioncSs|ddSr9rrr5r5r6unlinkRr z0CollectionAttributeImpl.__init__..unlink)rrr7_CollectionAttributeImpl__copyrrr OP_APPENDrrrOP_BULK_REPLACErr#duck_type_collectionrrer! listens_for) r0r&r'rr- typecallablerr copy_functionrr[rr rr5r6r7)s8        z CollectionAttributeImpl.__init__cCsddt|DS)NcSsg|]}|qSr5r5).0yr5r5r6 Wsz2CollectionAttributeImpl.__copy..)rr)r0itemr5r5r6__copyVr_zCollectionAttributeImpl.__copycCs*|j|||d}|turtSt|||Sr)r|rrrfrom_collectionrr5r5r6r@Ysz#CollectionAttributeImpl.get_historycs|j|vrgS||j}t|d}|j|jvrT|j|j}|ttfvrTdd|D}dd|D}t|t|fdd|Dfdd|Dfdd|DSdd|DS) N _sa_adaptercS$g|]}|dur t|p d|fqSr9r rcr5r5r6rlz;CollectionAttributeImpl.get_all_pending..cSrr9r rr5r5r6rprc g|] \}}|vr||fqSr5r5rso original_setr5r6ry cs g|] \}}|vr||fqSr5r5rr"r5r6r~s crr5r5r current_setr5r6rr$cSsg|]}t||fqSr5r )rr!r5r5r6rs)r'rerrrdict)r0rcr~rBrrcurrent_statesoriginal_statesr5r&r#r6r`s4        z'CollectionAttributeImpl.get_all_pendingcCsT|jjD] }||||p |j}q|||td|jr(|dur(|t||d|Sr%)r-rrrrrrr rr5r5r6fire_append_events z)CollectionAttributeImpl.fire_append_eventcCs|||tddS)afA special event used for pop() operations. The "remove" event needs to have the item to be removed passed to it, which in the case of pop from a set, we don't have a way to access the item before the operation. the event is used for all pop() operations (even though set.pop is the one where it is really needed). TN)rr)r0rcr~rr5r5r6fire_pre_remove_events z-CollectionAttributeImpl.fire_pre_remove_eventcCsT|jr|dur|t||d|jjD] }||||p|jq|||tddSr)rrr r-rrrrrr5r5r6rs  z)CollectionAttributeImpl.fire_remove_eventcCs@|j|vrdS|||td|||j}|||j=dSr%)r'rrget_collectionr'clear_with_event)r0rcr~rr5r5r6rzs  zCollectionAttributeImpl.deletecCs||\}}|||j<|S)z3Initialize this attribute with an empty collection.)_initialize_collectionr')r0rcr~_ user_datar5r5r6rs z"CollectionAttributeImpl.initializecCs0|j|j||j\}}|j|||||fSr9)r3initialize_collectionr'rr-r)r0rcadapterrr5r5r6r/s  z.CollectionAttributeImpl._initialize_collectioncCs`|j|||d}|tur(|||||}|j|vsJd||j|dS|||dSNrz,Collection was loaded during event handling.)r-rr+r'_get_pending_mutationrappend_with_eventr0rcr~rOrrBrr5r5r6rs zCollectionAttributeImpl.appendcCsb|j||j|d}|tur)||||||j|vsJd||j|dS|||dSr4)r-r'rrr'r5rremove_with_eventr7r5r5r6rs zCollectionAttributeImpl.removec Cs6z |j|||||dWdStttfyYdSwr)rrr IndexErrorrr5r5r6rs zCollectionAttributeImpl.popcCsT|}} ||\} } |r]| jdur| |}nEt|} |j} | | ur:|dur*dp-|jj}|jj}td||ft|drD| }n| t urYtj rP| }n t |d|j }nt|}t|}|j}|j||||j||td}|tur|||}n|| urdS||||d|j}| ||j<tj||| |d|`|j|||dS)NNonez/Incompatible collection type: %s is not %s-like _sa_iterator itervaluesrT)r)r/ _converterr#rrrPrh TypeErrorhasattrr;r'py3kvaluesreiterlistrr- bulk_replacer|rrrrrr'rr )r0rcr~rOrrBr_adaptiterable orig_iterablenew_collectionr1 setting_typereceiving_typegivenwanted new_valuesevtrold_collectionr5r5r6rxsX        zCollectionAttributeImpl.setcCst|d}d|_dS)NrT)re invalidated)r0rr3r5r5r6_invalidate_collection/s  z.CollectionAttributeImpl._invalidate_collectionc Cs||\}}|r||||j|j<|||jg|j|jvrK||||d|j|j}|j}|j }|D]} | | q9|D]} | | qC|S)z=Set an attribute value on the given instance and 'commit' it.T) r/append_multiple_without_eventr'r'r_pending_mutationsrr added_items deleted_itemsappend_without_eventremove_without_event) r0rcr~rOrr1pendingaddedremovedrr5r5r6r3s     z+CollectionAttributeImpl.set_committed_valuecCs.|dur|j|||d}|tur|St|dS)zRetrieve the CollectionAdapter associated with the given state. Creates a new CollectionAdapter if one does not exist. Nrr)r|rre)r0rcr~r1rBr5r5r6r-Ns  z&CollectionAttributeImpl.get_collection)NFNNN)rhrrrsrtrr>r:rrrr7r rr@rrr+r,rrzrr/rrrrxrQrr-rr5r5rr6rsF -  (      Krcsjjjfddfdd}fdd}fdd}r3tjd |d d d n tjd |d d d tjd |d d d dS)z6Apply listeners to synchronize a two-way relationship.cs tdt||j|jjjf)NzBidirectional attribute conflict detected: Passing object %s to attribute "%s" triggers a modify event on attribute "%s" via the backref "%s".)rrrr() child_stater child_impl)rr5r6_acceptable_key_errlsz.backref_listeners.._acceptable_key_errc s||ur|S|dur?|tur?|tur?t|t|}}|jj}|js+|js+|j}n|j }||ur?|j ||| j t d|durt|t|}} |jj} |jurc|j| jurc||| | j } | jrl| jnd} || ur|| ur| j|| | |t d|Sr)rrr r r3r(rrrrrrrrrrr) rcchildoldchildr old_stateold_dictr(check_recursive_tokenr[ child_dictr\check_append_tokencheck_bulk_replace_token)r]r' parent_implrr5r6"emit_backref_from_scalar_set_eventzsV      z=backref_listeners..emit_backref_from_scalar_set_eventcs|durdSt|t|}}|jj}|jur&|j|jur&||||j}|jr/|jnd}||urE||urE|j||| |t d|Sr) r r r3r(rrrrrrr)rcr^rr[rcr\rdre)r]r'rr5r6)emit_backref_from_collection_append_events(    zDbackref_listeners..emit_backref_from_collection_append_eventc s|dur]|tur_|turat|t|}}|jj}|js.|js.|j}|j }o,j }n |j}|jr7|j nd}d}||urc||ure|rOt |j j|sg|j||||tddSdSdSdSdSdSdS)NFr)rrr r r3r(rrrrrr# has_dupesr'r'rrr) rcr^rr[rcr\check_remove_tokencheck_replace_tokencheck_for_dupes_on_remove)r'rfuselistr5r6)emit_backref_from_collection_remove_eventsH    zDbackref_listeners..emit_backref_from_collection_remove_eventrT)rrawrxrN)r(rr!listen)rr'rmrgrhrnr5)r]rr'rfrrmr6backref_listeners^s8  A - rq NO_HISTORYrrY unchangeddeletedc@speZdZdZddZeZddZddZdd Zd d Z d d Z ddZ e ddZ e ddZe ddZdS)raA 3-tuple of added, unchanged and deleted values, representing the changes which have occurred on an instrumented attribute. The easiest way to get a :class:`.History` object for a particular attribute on an object is to use the :func:`.inspect` function:: from sqlalchemy import inspect hist = inspect(myobject).attrs.myattribute.history Each tuple member is an iterable sequence: * ``added`` - the collection of items added to the attribute (the first tuple element). * ``unchanged`` - the collection of items that have not changed on the attribute (the second tuple element). * ``deleted`` - the collection of items that have been removed from the attribute (the third tuple element). cCs|tkSr9)rr;r5r5r6__bool__CszHistory.__bool__cCst|jp |jp |j S)zhReturn True if this :class:`.History` has no changes and no existing, unchanged state. )boolrYrurtr;r5r5r6emptyHsz History.emptycCs|jpg|jpg|jp gS)z3Return a collection of added + unchanged + deleted.rsr;r5r5r6sumPsz History.sumcC|jpg|jpgS)z)Return a collection of added + unchanged.)rYrtr;r5r5r6 non_deletedWzHistory.non_deletedcCrz)z+Return a collection of unchanged + deleted.)rtrur;r5r5r6 non_added\r|zHistory.non_addedcCst|jp|jS)z2Return True if this :class:`.History` has changes.)rwrYrur;r5r5r6 has_changesaszHistory.has_changescCs0tdd|jDdd|jDdd|jDS)NcS g|] }|dur t|p dqSr9r rr5r5r6rhz$History.as_state..cSrr9r rr5r5r6rlrcSrr9r rr5r5r6rpr)rrYrtrur;r5r5r6as_statefszHistory.as_statecCs|j|jt}|tur|tur|dddS|d|gdS|||dur,|d|gdSt|tvr=d}t|tvr.cSrr9r rr5r5r6rrcg|] \}}|vr|qSr5r5rr"r5r6rcsg|] \}}|vr|qSr5r5rr"r5r6rrcrr5r5rr%r5r6rr) rr|r'rrrrerCr')rTrrcrrr(r)r5r*r6rs*   zHistory.from_collectionN)rhrrrsrtrv __nonzero__rxryr{r}r~r classmethodrrrr5r5r5r6r*s   cCs>|dur tdt}n |durtdt}tt|||S)a Return a :class:`.History` record for the given object and attribute key. This is the **pre-flush** history for a given attribute, which is reset each time the :class:`.Session` flushes changes to the current database transaction. .. note:: Prefer to use the :attr:`.AttributeState.history` and :meth:`.AttributeState.load_history` accessors to retrieve the :class:`.History` for instance attributes. :param obj: an object whose class is instrumented by the attributes package. :param key: string attribute name. :param passive: indicates loading behavior for the attribute if the value is not already present. This is a bitflag attribute, which defaults to the symbol :attr:`.PASSIVE_OFF` indicating all necessary SQL should be emitted. .. seealso:: :attr:`.AttributeState.history` :meth:`.AttributeState.load_history` - retrieve history using loader callables if the value is not locally present. TzNPassing True for 'passive' is deprecated. Use attributes.PASSIVE_NO_INITIALIZEFzFPassing False for 'passive' is deprecated. Use attributes.PASSIVE_OFF)r#warn_deprecatedrrget_state_historyr )rr'rBr5r5r6r@s"r@cCs |||Sr9)r@)rcr'rBr5r5r6r rrFcCst|}t|}||||S)TODO)rr has_parent)rTrr'r`r3rcr5r5r6r srcKsL|dd}|dd}|dd}t|||||d}t||fi||S)Nr)r1r)r)rregister_descriptorregister_attribute_impl)r&r'rr)r1rdescr5r5r6register_attributes   rc Kst|}|r|dd} ||| pt} n|dd} ||j} |r.|||| | fi|} n)|r>t|||| fd| i|} n|rLt|||| fi|} n t|||| fi|} | ||_|rft ||||| |||S)Nr) rrinstrument_collection_classrCr-rrrr(rqpost_configure_attribute) r&r'rmr useobject impl_classbackrefrr3factoryrr-r(r5r5r6rs<      rcCs.t|}t||||d}||_||||S)N)r)r1)rrwrtinstrument_attribute)r&r'r)r1rr3rr5r5r6rIs rcCst||dSr9)runinstrument_attribute)r&r'r5r5r6unregister_attributeXrnrcCst|}|j}t|||S)a4Initialize a collection attribute and return the collection adapter. This function is used to provide direct access to collection internals for a previously unloaded attribute. e.g.:: collection_adapter = init_collection(someobject, 'elements') for elem in values: collection_adapter.append_without_event(elem) For an easier way to do the above, see :func:`~sqlalchemy.orm.attributes.set_committed_value`. :param obj: a mapped object :param key: string attribute name where the collection is located. )r r'init_state_collection)rr'rcr~r5r5r6r\s rcCs&|j|j}|||}||||S)zDInitialize a collection attribute and return the collection adapter.)r3r(rr-)rcr~r'rr1r5r5r6rss  rcCs,t|t|}}|j|j|||dS)a[Set the value of an attribute with no history events. Cancels any previous history present. The value should be a scalar value for scalar-holding attributes, or an iterable for any collection-holding attribute. This is the same underlying method used when a lazy loader fires off and loads additional data from the database. In particular, this method can be used by application code which has loaded additional attributes or collections through separate queries, which can then be attached to an instance as though it were part of its original loaded state. N)r r r3r(r)rAr'rOrcr~r5r5r6r{srcCs.t|t|}}|j|j||||dS)asSet the value of an attribute, firing history events. This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to establish attribute state as understood by SQLAlchemy. :param instance: the object that will be modified :param key: string name of the attribute :param value: value to assign :param initiator: an instance of :class:`.Event` that would have been propagated from a previous event listener. This argument is used when the :func:`.set_attribute` function is being used within an existing event listening function where an :class:`.Event` object is being supplied; the object may be used to track the origin of the chain of events. .. versionadded:: 1.2.3 N)r r r3r(rx)rAr'rOrrcr~r5r5r6 set_attributesrcCs&t|t|}}|j|j||S)aZGet the value of an attribute, firing any callables required. This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to make usage of attribute state as understood by SQLAlchemy. )r r r3r(r|rAr'rcr~r5r5r6 get_attributes rcCs*t|t|}}|j|j||dS)aQDelete the value of an attribute, firing history events. This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to establish attribute state as understood by SQLAlchemy. N)r r r3r(rzrr5r5r6 del_attributes rcCsDt|t|}}|j|j}|j||j|j||tdddS)aMark an attribute on an instance as 'modified'. This sets the 'modified' flag on the instance and establishes an unconditional change event for the given attribute. The attribute must have a value present, else an :class:`.InvalidRequestError` is raised. To mark an object "dirty" without referring to any specific attribute so that it is considered within a flush, use the :func:`.attributes.flag_dirty` call. .. seealso:: :func:`.attributes.flag_dirty` T is_userlandN) r r r3r(r-modifiedrrr)rAr'rcr~r(r5r5r6 flag_modifieds rcCs(t|t|}}|j|dtdddS)aMark an instance as 'dirty' without any specific attribute mentioned. This is a special operation that will allow the object to travel through the flush process for interception by events such as :meth:`.SessionEvents.before_flush`. Note that no SQL will be emitted in the flush process for an object that has no changes, even if marked dirty via this method. However, a :meth:`.SessionEvents.before_flush` handler will be able to see the object in the :attr:`.Session.dirty` collection and may establish changes on it, which will then be included in the SQL emitted. .. versionadded:: 1.2 .. seealso:: :func:`.attributes.flag_modified` NTr)r r rr)rArcr~r5r5r6 flag_dirtysrrq)FNFNNrr9)Nrtrrrrrr4rrrr r r r rrrrrrrrrrrrrrrrrrr!r"r#_self_inspects_MappedAttributeInspectionAttrPropComparatorr$rwrsymbolrr rrrobjectrrrrrrqr frozensetrr namedtuplerrr@rrrrrrrrrrrrrrr5r5r5r6s                                M x    2FU(R E +  2   -