B 4]A@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?gZ=Gd@d<defdAdBZ?efdCdDZ@d`dFdGZAdHdIZBdadJdKZCdbdLdMZDdNdOZEdPdQZFdRdSZGdTdUZHdcdVdWZIdXdYZJdZd[ZKd\d]ZLd^d_ZMdS)dzDefines 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_dict)instance_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@seZdZdZdZd-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|}|rnx<|jD]2}||kr8|j ||j||jj r8d|j_ q8WdS)NT) class_keyimpl comparator _parententity_of_typerZ_basesdispatchZ_update_active_history) selfr$r%r&r' parententityof_typemanagerbaser1L/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/attributes.py__init__Ns   zQueryableAttribute.__init__cCs|jjS)N)r&supports_population)r,r1r1r2_supports_populationisz'QueryableAttribute._supports_populationcCs|jjS)N)r& uses_objects)r,r1r1r2_impl_uses_objectsmsz%QueryableAttribute._impl_uses_objectscCs|jt|t||S)N)r& get_historyr r )r,instancepassiver1r1r2r8qszQueryableAttribute.get_historycCs|S)Nr1)r,r1r1r2__selectable__vsz!QueryableAttribute.__selectable__cCs|jjS)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'info)r,r1r1r2r<zs'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,r1r1r2parents zQueryableAttribute.parentcCs |jS)N)r'__clause_element__)r,r1r1r2 expressionszQueryableAttribute.expressioncCs |jS)N)r'r?)r,r1r1r2r?sz%QueryableAttribute.__clause_element__cCs |jS)zhlike __clause_element__(), but called specifically by :class:`.Query` to allow special behavior.)r'_query_clause_element)r,r1r1r2rAsz(QueryableAttribute._query_clause_elementcCs |j|S)z'Return setter tuples for a bulk UPDATE.)r'_bulk_update_tuples)r,valuer1r1r2rBsz&QueryableAttribute._bulk_update_tuplescCs,|jr t|j|j|j|j|j||dS)N)r&r'r-)r)AssertionError __class__entityr%r&r'adapt_to_entity)r,rGr1r1r2rGs  z"QueryableAttribute.adapt_to_entitycCs$t|j|j|j|j||j|dS)N)r.)r#r$r%r&r'r.r()r,clsr1r1r2r.s zQueryableAttribute.of_typecCs||S)N)rAlabel)r,namer1r1r2rIszQueryableAttribute.labelcOs||jf||S)N)r')r,opotherkwargsr1r1r2operateszQueryableAttribute.operatecKs|||jf|S)N)r')r,rKrLrMr1r1r2reverse_operatesz"QueryableAttribute.reverse_operateFcCs|jj||ddk S)N) optimisticF)r& hasparent)r,staterPr1r1r2rQszQueryableAttribute.hasparentc CsHy t|j|Stk rBtdt|jt|jj||fYnXdS)NzFNeither %r object nor %r object associated with %s has an attribute %r)getattrr'AttributeErrortype__name__)r,r%r1r1r2 __getattr__s  zQueryableAttribute.__getattr__cCsd|jj|jfS)Nz%s.%s)r$rVr%)r,r1r1r2__str__szQueryableAttribute.__str__cCs|jjS)zReturn the :class:`.MapperProperty` associated with this :class:`.QueryableAttribute`. Return values here will commonly be instances of :class:`.ColumnProperty` or :class:`.RelationshipProperty`. )r'property)r,r1r1r2rYs zQueryableAttribute.property)NNNN)F)rV __module__ __qualname____doc__Z is_attributer3r"memoized_propertyr5rYr7rr8r;r<r>r@r?rArBrGr.rIrNrOrQrWrXr1r1r1r2r#4s2   )    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||ddS)N)r&setr r )r,r9rCr1r1r2__set__ szInstrumentedAttribute.__set__cCs|jt|t|dS)N)r&deleter r )r,r9r1r1r2 __delete__sz InstrumentedAttribute.__delete__cCsD|dkr |St|}|jr.|j|kr.||jS|jt||SdS)N)r r5r%r&getr )r,r9ownerdict_r1r1r2__get__s  zInstrumentedAttribute.__get__N)rVrZr[r\r`rbrfr1r1r1r2r^sr^cs>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. csheZdZdZdddZdZeddZedd 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.||_||_||_||_||_||_||_dS)N)r$r% descriptororiginal_property _comparator_adapt_to_entityr\)r,r$r%rgr'rGdocrhr1r1r2r3.s z0create_proxied_attribute..Proxy.__init__TcSs|jdk ot|j|jjjS)N)rhrSr$r%r&r6)r,r1r1r2r7Bs z:create_proxied_attribute..Proxy._impl_uses_objectscSs|jjS)N)r'rY)r,r1r1r2rYIsz0create_proxied_attribute..Proxy.propertycSs2t|jr||_|jr,|j|j|_|jS)N)r"callablerirjrG)r,r1r1r2r'Ms    z2create_proxied_attribute..Proxy.comparatorcSs||j|j|j|j|S)N)rErFr%rgri)r,rGr1r1r2rGWs z7create_proxied_attribute..Proxy.adapt_to_entitycSs,|j||}||jkr$|dkr$|S|SdS)N)rgrf)r,r9rdretvalr1r1r2rf`sz/create_proxied_attribute..Proxy.__get__cSsd|jj|jfS)Nz%s.%s)r$rVr%)r,r1r1r2rXjsz/create_proxied_attribute..Proxy.__str__c sy t|Stk r|dkr*tdy |j}Wn,tk r`tdtj||fYnBXy t||Stk rtdtjt|j||fYnXYnXdS)zNDelegate __getattr__ to the original descriptor and/or comparator.r'z[Neither %r object nor unconfigured comparator object associated with %s has an attribute %rzFNeither %r object nor %r object associated with %s has an attribute %rN)rSrTr'rUrV)r, attributer')rgr1r2rWms(   z3create_proxied_attribute..Proxy.__getattr__)NNN)rVrZr[r\r3Z_is_internal_proxyrYr7r"r]r'rGrfrXrWr1)rgr1r2Proxy's      rorg)rJZ from_instance)r#rUrVr"Zmonkeypatch_proxied_specials)rgror1)rgr2create_proxied_attributes frpZREMOVEZAPPENDZREPLACEZ BULK_REPLACEZMODIFIEDc@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&rK parent_tokencCs||_||_|jj|_dS)N)r&rKrr)r,Zattribute_implrKr1r1r2r3szEvent.__init__cCs"t|to |j|jko |j|jkS)N) isinstancerqr&rK)r,rLr1r1r2__eq__s  z Event.__eq__cCs|jjS)N)r&r%)r,r1r1r2r%sz Event.keycCs |j|S)N)r&rQ)r,rRr1r1r2rQszEvent.hasparentN) rVrZr[r\ __slots__r3rtrYr%rQr1r1r1r2rqs  rqc@seZdZdZd&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$||_| |_|dkr@tj|_ n||_ | dk rV| |_ n|j |_ t ||}x"t |pvgD]}|||qzW|rd|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* trackparentrrsend_modified_eventsoperatoreqis_equalaccepts_scalar_loaderdefault_accepts_scalar_loaderrr"Zto_listZ_adapt_listenerr+expire_missingrq OP_MODIFIED_modified_token)r,r$r%rwr*rx extensioncompare_functionactive_historyrrrryr}rMattrZextr1r1r2r3s(F   zAttributeImpl.__init__) r$r%rwr*rxrrryr|rrr}cCsd|jj|jfS)Nz%s.%s)r$rVr%)r,r1r1r2rXCszAttributeImpl.__str__cCs|jjS)z(Backwards compat for impl.active_history)r*r+)r,r1r1r2_get_active_historyFsz!AttributeImpl._get_active_historycCs ||j_dS)N)r*r+)r,rCr1r1r2_set_active_historyKsz!AttributeImpl._set_active_historycCs*d}|jst||jt|j|dk S)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. z6This AttributeImpl is not configured to track parents.F)rxrDparentsrcidrr)r,rRrPmsgr1r1r2rQPszAttributeImpl.hasparentcCsd}|jst|t|j}|r,||j|<n`||jkr|j|}|dk r|j|jkr|dkr~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``. z6This AttributeImpl is not configured to track parents.FNzRemoving 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.) rxrDrrrrr%objorm_excZStaleDataErrorr)r,rRZ parent_staterCrZid_Z last_parentr1r1r2 sethasparentgs"       zAttributeImpl.sethasparentcCs tdS)N)NotImplementedError)r,rRrer:r1r1r2r8szAttributeImpl.get_historycCs tdS)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() N)r)r,rRrer:r1r1r2get_all_pendingszAttributeImpl.get_all_pendingcCs2d}x(|jjD]}||||}|tk r|}qW|S)z;Initialize the given state's attribute with an empty value.N)r*Z init_scalarr)r,rRrerCfnretr1r1r2 initializes  zAttributeImpl.initializecCs |j|kr||jS|j}||jks2|j|tkr|t@s>tS||jkrV|||}n8||jkrv|j|}|||}n|jr|||}nt }|tks|tkr|S|t kry||St k rt d|YqXn|t k r| |||S|t @stS|||SdS)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 correctlyN)r%committed_staterrrexpired_attributesZ _load_expiredZ callablesrwrrKeyErrorset_committed_valuer r)r,rRrer:r%rCrwr1r1r2rcs:        zAttributeImpl.getcCs|j|||||ddS)N)r:)r_)r,rRrerC initiatorr:r1r1r2appendszAttributeImpl.appendcCs|j||d|||ddS)N)r: check_old)r_)r,rRrerCrr:r1r1r2removeszAttributeImpl.removec Cs|j||d|||dddS)NT)r:rpop)r_)r,rRrerCrr:r1r1r2rszAttributeImpl.popcCs tdS)N)r)r,rRrerCrr:rrr1r1r2r_s zAttributeImpl.setcCsB|j|jkr.|j|j}|ttfkr(dS|Sn|j|||dSdS)z,return the unchanged value of this attributeN)r:)r%rrrrc)r,rRrer:rCr1r1r2get_committed_values    z!AttributeImpl.get_committed_valuecCs|||j<|||jg|S)z=set an attribute value on the given instance and 'commit' it.)r%_commit)r,rRrerCr1r1r2r s z!AttributeImpl.set_committed_value)FNNFNTTN)F)rVrZr[r\r3rurXrrrYrrQrrr8rrrrcrrrr_rrr1r1r1r2rvs8 X   '   1     rvcsxeZdZdZdZdZdZdZdZdZ fddZ ddZ e fd d Z e d dfd d ZddZddZeddZZS)ScalarAttributeImplz8represents a scalar value-holding InstrumentedAttribute.TF)_replace_token _append_token _remove_tokencs4tt|j||t|t|_|_t|t|_dS)N) superrr3rq OP_REPLACErr OP_REMOVEr)r,argkw)rEr1r2r3szScalarAttributeImpl.__init__cCs|jjr|||t}n||jt}|jjr@|||||j| |||| |jt}|tkr|tkr|j s|j|j krt d|dS)Nz%s object does not have a value)r*r+rcrr%rrfire_remove_eventr_modified_eventrZexpiredrrT)r,rRreoldexistingr1r1r2ra"s zScalarAttributeImpl.deletecCs\|j|krt||||jS|t@r.|tN}|j|||d}|tkrJtSt|||SdS)N)r:)r%Historyfrom_scalar_attributer rcr HISTORY_BLANK)r,rRrer:currentr1r1r2r85s zScalarAttributeImpl.get_historyNc Cs\|jjr|||t}n||jt}|jjr@||||||}|||||||j<dS)N) r*r+rcrr%rr_fire_replace_eventr) r,rRrerCrr:rrrr1r1r2r_As zScalarAttributeImpl.setcCs*x$|jjD]}|||||p|j}q W|S)N)r*r_r)r,rRrerCpreviousrrr1r1r2rWsz&ScalarAttributeImpl.fire_replace_eventcCs(x"|jjD]}||||p|jq WdS)N)r*rr)r,rRrerCrrr1r1r2r^sz%ScalarAttributeImpl.fire_remove_eventcCs|jjdjdS)Nr)rYcolumnsrU)r,r1r1r2rUbszScalarAttributeImpl.type)rVrZr[r\r~r6r4 collectiondynamicrur3rarr8r_rrrYrU __classcell__r1r1)rEr2rs    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. FTr1cCs|jjr"|j||ttBtBd}n|j||ttAtBtBd}| ||||j | |j t }|t kr|tk r|j dkrtd|dS)N)r:z%s object does not have a value)r*r+rcrrr rr rrrrr%rrrT)r,rRrerrr1r1r2ravs z ScalarObjectAttributeImpl.deletecCs\|j|krt||||jS|t@r.|tN}|j|||d}|tkrJtSt|||SdS)N)r:)r%rfrom_object_attributer rcrr)r,rRrer:rr1r1r2r8s z%ScalarObjectAttributeImpl.get_historycCs|j|kr||j}n|t@r0|j|||d}ngS|dk r\|tk r\|tk r\t||fg}ndg}|j|jkr|j|j}|dk r|tk r|tk r||k r|t||f|S)N)r:)NN)r%rrcrrr rr)r,rRrer:rroriginalr1r1r2rs$    z)ScalarObjectAttributeImpl.get_all_pendingNc Cs|jjr"|j||ttBtBd}n|j||ttAtBtBd}|dk rz|t k rz||k rz|r^dSt dt |t ||j f||||||}|||j <dS)z1Set a value on the given InstanceState. )r:Nz2Object %s not associated with %s on attribute '%s')r*r+rcrrr rr rr ValueErrorr rr%r) r,rRrerCrr:rrrr1r1r2r_s& zScalarObjectAttributeImpl.setcCsV|jr |dk r |t||dx"|jjD]}||||p<|jq*W||||dS)NF)rxrr r*rrr)r,rRrerCrrr1r1r2rs z+ScalarObjectAttributeImpl.fire_remove_eventcCs|jr.||k r.|dttfkr.|t||dx$|jjD]}|||||pL|j}q8W|||||jr|dk r|t||d|S)NFT) rxrrrr r*r_rr)r,rRrerCrrrr1r1r2rs z,ScalarObjectAttributeImpl.fire_replace_event)rVrZr[r\r~r6r4rrurarr8rrr_rrr1r1r1r2rgs $ & 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| |dkr4|j}||_||_t|t|_t|t |_ t|t |_ t ||_t|jddrt|ddd} t|ddd} dS) N)rxrr _sa_linkerinit_collectioncSs||dS)N)r)targetrcollection_adapterr1r1r2linkNsz.CollectionAttributeImpl.__init__..linkdispose_collectioncSs|ddS)N)r)rrrr1r1r2unlinkRsz0CollectionAttributeImpl.__init__..unlink)rrr3_CollectionAttributeImpl__copyrrrq OP_APPENDrrrOP_BULK_REPLACErr"duck_type_collectionrrSr Z listens_for) r,r$r%rwr* typecallablerxrZ copy_functionrrMrr)rEr1r2r3)s*     z CollectionAttributeImpl.__init__cCsddt|DS)NcSsg|]}|qSr1r1).0yr1r1r2 Wsz2CollectionAttributeImpl.__copy..)rr)r,itemr1r1r2Z__copyVszCollectionAttributeImpl.__copycCs.|j|||d}|tkrtSt|||SdS)N)r:)rcrrrfrom_collection)r,rRrer:rr1r1r2r8Ysz#CollectionAttributeImpl.get_historycs|j|krgS||j}t|d}|j|jkr|j|j}|ttfkrdd|D}dd|D}t|t|fdd|Dfdd|Dfdd|DSdd|DS) N _sa_adaptercSs$g|]}|dk rt|pd|fqS)N)r )rcr1r1r2rmsz;CollectionAttributeImpl.get_all_pending..cSs$g|]}|dk rt|pd|fqS)N)r )rrr1r1r2rqscs g|]\}}|kr||fqSr1r1)rso) original_setr1r2rzscs g|]\}}|kr||fqSr1r1)rrr)rr1r2r~scs g|]\}}|kr||fqSr1r1)rrr) current_setr1r2rscSsg|]}t||fqSr1)r )rrr1r1r2rs)r%rSrrrdict)r,rRrer:rrcurrent_statesoriginal_statesr1)rrr2r`s"       "  z'CollectionAttributeImpl.get_all_pendingcCsXx"|jjD]}||||p|j}q W|||td|jrT|dk rT|t||d|S)NT)r*rrrrrxrr )r,rRrerCrrr1r1r2fire_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)r,rRrerr1r1r2fire_pre_remove_events z-CollectionAttributeImpl.fire_pre_remove_eventcCsX|jr |dk r |t||dx"|jjD]}||||p<|jq*W|||tddS)NFT)rxrr r*rrrr)r,rRrerCrrr1r1r2rs z)CollectionAttributeImpl.fire_remove_eventcCs@|j|krdS|||td|||j}|||j=dS)NT)r%rrget_collectionrZclear_with_event)r,rRrerr1r1r2ras  zCollectionAttributeImpl.deletecCs||\}}|||j<|S)z3Initialize this attribute with an empty collection.)_initialize_collectionr%)r,rRre_ user_datar1r1r2rs z"CollectionAttributeImpl.initializecCs0|j|j||j\}}|j|||||fS)N)r/Zinitialize_collectionr%rr*r)r,rRadapterrr1r1r2rsz.CollectionAttributeImpl._initialize_collectioncCs^|j|||d}|tkrN|||||}|j|ks:td||j|n |||dS)N)r:z,Collection was loaded during event handling.)rrrr%rD_get_pending_mutationrZappend_with_event)r,rRrerCrr:rr1r1r2rs zCollectionAttributeImpl.appendcCs`|j||j|d}|tkrP||||||j|ks #  (      Crcsjjjfddfdd}fdd}fdd}rftjd |d d d ntjd |d d d tjd |d d d dS)z6Apply listeners to synchronize a two-way relationship.cs$tdt||j|jjjfdS)NzBidirectional attribute conflict detected: Passing object %s to attribute "%s" triggers a modify event on attribute "%s" via the backref "%s".)rrrrr&) child_stater child_impl)rnr1r2_acceptable_key_errls z.backref_listeners.._acceptable_key_errc s||kr |S|dk r~|tk r~|tk r~t|t|}}|jj}|jsV|jsV|j}n|j }||k r~|j ||| j t d|dk r t|t|}} |jj} |jk r|j| jk rȈ||| | j } | jr| jnd} || k r || k r | j|| | |t d|S)N)r:)rrr r r/r&rrrrrrrrrrrr) rRchildZoldchildrZ old_stateZold_dictr&Zcheck_recursive_tokenr child_dictrcheck_append_tokencheck_bulk_replace_token)rr% parent_implrrr1r2"emit_backref_from_scalar_set_eventzsJ            z=backref_listeners..emit_backref_from_scalar_set_eventcs|dkr dSt|t|}}|jj}|jk rL|j|jk rL||||j}|jr^|jnd}||k r||k r|j||| |t d|S)N)r:) r r r/r&rrrrrrrr)rRrrrrrrr)rr%rrr1r2)emit_backref_from_collection_append_events$    zDbackref_listeners..emit_backref_from_collection_append_eventc s|dk r|tk r|tk rt|t|}}|jj}|js\|js\|j}|j }oXj }n|j}|jrn|j nd}d}||k r||k r|rt |j j|s|j||||tddS)NF)r:)rrr r r/r&rrrrrr"Z has_dupesrr%rrr) rRrrrrrZcheck_remove_tokenZcheck_replace_tokenZcheck_for_dupes_on_remove)r%ruselistr1r2)emit_backref_from_collection_remove_events2     zDbackref_listeners..emit_backref_from_collection_remove_eventrT)rmrawr_rN)r&rrr Zlisten)rnr%rrrrr1)rrnr%rrrrr2backref_listeners^s2  A - rZ NO_HISTORYrr 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|tkS)N)r)r,r1r1r2__bool__CszHistory.__bool__cCst|jp|jp|j S)zhReturn True if this :class:`.History` has no changes and no existing, unchanged state. )boolrrr)r,r1r1r2emptyHsz History.emptycCs|jpg|jpg|jpgS)z3Return a collection of added + unchanged + deleted.)rrr)r,r1r1r2sumPsz History.sumcCs|jpg|jpgS)z)Return a collection of added + unchanged.)rr)r,r1r1r2 non_deletedWszHistory.non_deletedcCs|jpg|jpgS)z+Return a collection of unchanged + deleted.)rr)r,r1r1r2 non_added\szHistory.non_addedcCst|jp |jS)z2Return True if this :class:`.History` has changes.)rrr)r,r1r1r2 has_changesaszHistory.has_changescCs0tdd|jDdd|jDdd|jDS)NcSs g|]}|dk rt|pdqS)N)r )rrr1r1r2risz$History.as_state..cSs g|]}|dk rt|pdqS)N)r )rrr1r1r2rmscSs g|]}|dk rt|pdqS)N)r )rrr1r1r2rqs)rrrr)r,r1r1r2as_statefszHistory.as_statecCs|j|jt}|tkr<|tkr,|dddS|d|gdSnh|||dkrZ|d|gdSt|tkr|d}t|tkrd}n|g}|tkr|dd|S||gd|SdS)Nr1T)rrcr% _NO_HISTORYrr|r_NO_STATE_SYMBOLS)rHrnrRrrrr1r1r2rvs    zHistory.from_scalar_attributecCs|j|jt}|tkrD|tks(|tkr4|dddS|d|gdSnx||krb|tk rb|d|gdSt|tksv|dkrd}t|tkrd}n|g}|tks|tkr|dd|S||gd|SdS)Nr1)rrcr%rrrrr)rHrnrRrrrr1r1r2rs   zHistory.from_object_attributecs|j|jt}|tks |tkr,|dddSt|d}|ttfkrR|t|ddS|tkrj|dt|dSdd|D}dd|D}t|t||fdd|Dfdd|Dfdd|DSdS) Nr1rcSs$g|]}|dk rt|pd|fqS)N)r )rrr1r1r2rsz+History.from_collection..cSs$g|]}|dk rt|pd|fqS)N)r )rrr1r1r2rscsg|]\}}|kr|qSr1r1)rrr)rr1r2rscsg|]\}}|kr|qSr1r1)rrr)rr1r2rscsg|]\}}|kr|qSr1r1)rrr)rr1r2rs) rrcr%rrrrSrr)rHrnrRrrrrr1)rrr2rs$   zHistory.from_collectionN)rVrZr[r\rZ __nonzero__rrrrrr classmethodrrrr1r1r1r2r*s  cCs>|dkrtdt}n|dkr.tdt}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"Zwarn_deprecatedrrget_state_historyr )rr%r:r1r1r2r8s"r8cCs |||S)N)r8)rRr%r:r1r1r2r srFcCst|}t|}||||S)ZTODO)rr has_parent)rHrr%rPr/rRr1r1r2r srcKsH|dd}|dd}|dd}t|||||d}t||f||S)Nr'r-rk)rk)rregister_descriptorregister_attribute_impl)r$r%rr'r-rkZdescr1r1r2register_attributes    r c Kst|}|r*|dd} ||| p$t} n |dd} ||j} |rX|||| | f|} nJ|rxt|||| fd| i|} n*|rt|||| f|} nt|||| f|} | ||_|rt ||||| |||S)Nr) rrZinstrument_collection_classrr*rrrr&rZpost_configure_attribute) r$r%rrwZ useobjectZ impl_classZbackrefrr/factoryrr*r&r1r1r2r s*      r cCs.t|}t||||d}||_||||S)N)r'r-)rr^r\Zinstrument_attribute)r$r%r'r-rkr/rgr1r1r2rIs  rcCst||dS)N)rZuninstrument_attribute)r$r%r1r1r2unregister_attributeXsr cCst|}|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 rinit_state_collection)rr%rRrer1r1r2r\srcCs&|j|j}|||}||||S)zDInitialize a collection attribute and return the collection adapter.)r/r&rr)rRrer%rrr1r1r2r ss  r cCs,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 r/r&r)r9r%rCrRrer1r1r2r{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 r/r&r_)r9r%rCrrRrer1r1r2 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 r/r&rc)r9r%rRrer1r1r2 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 r/r&ra)r9r%rRrer1r1r2 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 r/r&r*Zmodifiedrrr)r9r%rRrer&r1r1r2 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` NT)r)r r rr)r9rRrer1r1r2 flag_dirtysr)F)FNFNN)NNN)N)Nr\rzrrrrr0rrrr r r r r rrrrrrrrrrrrrrrrrr r!r"Z_self_inspectsZ_MappedAttributeZInspectionAttrZPropComparatorr#r^rpZsymbolrrrrrobjectrqrvrrrrr frozensetrr namedtuplerrr8rrr r rr rr rrrrrrr1r1r1r2s                                Jx     2FU(RE +  2    &