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 _parententityZ_of_typerZ_basesdispatchZ_update_active_history) selfr$r%r&r' parententityof_typemanagerbaser0L/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/attributes.py__init__Ns   zQueryableAttribute.__init__cCs|jjS)N)r&supports_population)r+r0r0r1_supports_populationisz'QueryableAttribute._supports_populationcCs|jjS)N)r& uses_objects)r+r0r0r1_impl_uses_objectsmsz%QueryableAttribute._impl_uses_objectscCs|jt|t||S)N)r& get_historyr r )r+instancepassiver0r0r1r7qszQueryableAttribute.get_historycCs|S)Nr0)r+r0r0r1__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+r0r0r1r;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+r0r0r1parents zQueryableAttribute.parentcCs |jS)N)r'__clause_element__)r+r0r0r1 expressionszQueryableAttribute.expressioncCs |jS)N)r'r>)r+r0r0r1r>sz%QueryableAttribute.__clause_element__cCs |jS)zhlike __clause_element__(), but called specifically by :class:`.Query` to allow special behavior.)r'_query_clause_element)r+r0r0r1r@sz(QueryableAttribute._query_clause_elementcCs |j|S)z'Return setter tuples for a bulk UPDATE.)r'_bulk_update_tuples)r+valuer0r0r1rAsz&QueryableAttribute._bulk_update_tuplescCs"|j|j|j|j|j||dS)N)r&r'r,) __class__entityr%r&r'adapt_to_entity)r+rEr0r0r1rEs  z"QueryableAttribute.adapt_to_entitycCs$t|j|j|j|j||j|dS)N)r-)r#r$r%r&r'r-r()r+clsr0r0r1r-s zQueryableAttribute.of_typecCs||S)N)r@label)r+namer0r0r1rGszQueryableAttribute.labelcOs||jf||S)N)r')r+opotherkwargsr0r0r1operateszQueryableAttribute.operatecKs|||jf|S)N)r')r+rIrJrKr0r0r1reverse_operatesz"QueryableAttribute.reverse_operateFcCs|jj||ddk S)N) optimisticF)r& hasparent)r+staterNr0r0r1rOszQueryableAttribute.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%r0r0r1 __getattr__s  zQueryableAttribute.__getattr__cCsd|jj|jfS)Nz%s.%s)r$rTr%)r+r0r0r1__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+r0r0r1rWs zQueryableAttribute.property)NNNN)F)rT __module__ __qualname____doc__Z is_attributer2r"memoized_propertyr4rWr6rr7r:r;r=r?r>r@rArEr-rGrLrMrOrUrVr0r0r0r1r#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+r8rBr0r0r1__set__ szInstrumentedAttribute.__set__cCs|jt|t|dS)N)r&deleter r )r+r8r0r0r1 __delete__sz InstrumentedAttribute.__delete__cCsD|dkr |St|}|jr.|j|kr.||jS|jt||SdS)N)r r4r%r&getr )r+r8ownerdict_r0r0r1__get__s  zInstrumentedAttribute.__get__N)rTrXrYrZr^r`rdr0r0r0r1r\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_entityrZ)r+r$r%rer'rEdocrfr0r0r1r2.s z0create_proxied_attribute..Proxy.__init__TcSs|jdk ot|j|jjjS)N)rfrQr$r%r&r5)r+r0r0r1r6Bs z:create_proxied_attribute..Proxy._impl_uses_objectscSs|jjS)N)r'rW)r+r0r0r1rWIsz0create_proxied_attribute..Proxy.propertycSs2t|jr||_|jr,|j|j|_|jS)N)r"callablergrhrE)r+r0r0r1r'Ms    z2create_proxied_attribute..Proxy.comparatorcSs||j|j|j|j|S)N)rCrDr%rerg)r+rEr0r0r1rEWs z7create_proxied_attribute..Proxy.adapt_to_entitycSs,|j||}||jkr$|dkr$|S|SdS)N)rerd)r+r8rbretvalr0r0r1rd`sz/create_proxied_attribute..Proxy.__get__cSsd|jj|jfS)Nz%s.%s)r$rTr%)r+r0r0r1rVjsz/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)rQrRr'rSrT)r+ attributer')rer0r1rUms(   z3create_proxied_attribute..Proxy.__getattr__)NNN)rTrXrYrZr2Z_is_internal_proxyrWr6r"r[r'rErdrVrUr0)rer0r1Proxy's      rmre)rHZ from_instance)r#rSrTr"Zmonkeypatch_proxied_specials)rermr0)rer1create_proxied_attributes frnZREMOVEZAPPENDZREPLACEZ 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&rI parent_tokencCs||_||_|jj|_dS)N)r&rIrp)r+Zattribute_implrIr0r0r1r2szEvent.__init__cCs"t|to |j|jko |j|jkS)N) isinstanceror&rI)r+rJr0r0r1__eq__s  z Event.__eq__cCs|jjS)N)r&r%)r+r0r0r1r%sz Event.keycCs |j|S)N)r&rO)r+rPr0r0r1rOszEvent.hasparentN) rTrXrYrZ __slots__r2rrrWr%rOr0r0r0r1ros  roc@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) trackparentrpsend_modified_eventsoperatoreqis_equalaccepts_scalar_loaderdefault_accepts_scalar_loaderrr"Zto_listZ_adapt_listenerr*expire_missingro OP_MODIFIED_modified_token)r+r$r%rur)rv extensioncompare_functionactive_historyrpr}rwr{rKattrZextr0r0r1r2s(F   zAttributeImpl.__init__) r$r%rur)rvrprwrzr}rr{cCsd|jj|jfS)Nz%s.%s)r$rTr%)r+r0r0r1rVCszAttributeImpl.__str__cCs|jjS)z(Backwards compat for impl.active_history)r)r*)r+r0r0r1_get_active_historyFsz!AttributeImpl._get_active_historycCs ||j_dS)N)r)r*)r+rBr0r0r1_set_active_historyKsz!AttributeImpl._set_active_historycCsd}|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)parentsraidrp)r+rPrNmsgr0r0r1rOPszAttributeImpl.hasparentcCsd}t|j}|r||j|<n`||jkrt|j|}|dk rt|j|jkrt|dkrptdt|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.)rrprr%objorm_excZStaleDataErrorr)r+rPZ parent_staterBrZid_Z last_parentr0r0r1 sethasparentgs        zAttributeImpl.sethasparentcCs tdS)N)NotImplementedError)r+rPrcr9r0r0r1r7szAttributeImpl.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+rPrcr9r0r0r1get_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+rPrcrBfnretr0r0r1 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 callablesrurrKeyErrorset_committed_valuer r)r+rPrcr9r%rBrur0r0r1ras:        zAttributeImpl.getcCs|j|||||ddS)N)r9)r])r+rPrcrB initiatorr9r0r0r1appendszAttributeImpl.appendcCs|j||d|||ddS)N)r9 check_old)r])r+rPrcrBrr9r0r0r1removeszAttributeImpl.removec Cs|j||d|||dddS)NT)r9rpop)r])r+rPrcrBrr9r0r0r1rszAttributeImpl.popcCs tdS)N)r)r+rPrcrBrr9rrr0r0r1r]s zAttributeImpl.setcCsB|j|jkr.|j|j}|ttfkr(dS|Sn|j|||dSdS)z,return the unchanged value of this attributeN)r9)r%rrrra)r+rPrcr9rBr0r0r1get_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+rPrcrBr0r0r1r s z!AttributeImpl.set_committed_value)FNNFNTTN)F)rTrXrYrZr2rsrVrrrWrrOrrr7rrrrarrrr]rrr0r0r0r1rts8 X   '   1     rtcsxeZdZdZdZdZdZdZdZdZ 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) superrr2ro OP_REPLACErr OP_REMOVEr)r+argkw)rCr0r1r2szScalarAttributeImpl.__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*rarr%rrfire_remove_eventr_modified_eventrZexpiredrrR)r+rPrcoldexistingr0r0r1r_"s zScalarAttributeImpl.deletecCs\|j|krt||||jS|t@r.|tN}|j|||d}|tkrJtSt|||SdS)N)r9)r%Historyfrom_scalar_attributer rar HISTORY_BLANK)r+rPrcr9currentr0r0r1r75s zScalarAttributeImpl.get_historyNc Cs\|jjr|||t}n||jt}|jjr@||||||}|||||||j<dS)N) r)r*rarr%rr]fire_replace_eventr) r+rPrcrBrr9rrrr0r0r1r]As zScalarAttributeImpl.setcCs*x$|jjD]}|||||p|j}q W|S)N)r)r]r)r+rPrcrBpreviousrrr0r0r1rWsz&ScalarAttributeImpl.fire_replace_eventcCs(x"|jjD]}||||p|jq WdS)N)r)rr)r+rPrcrBrrr0r0r1r^sz%ScalarAttributeImpl.fire_remove_eventcCs|jjdjdS)Nr)rWcolumnsrS)r+r0r0r1rSbszScalarAttributeImpl.type)rTrXrYrZr|r5r3 collectiondynamicrsr2r_rr7r]rrrWrS __classcell__r0r0)rCr1rs    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. FTr0cCs|jjr"|j||ttBtBd}n|j||ttAtBtBd}| ||||j | |j t }|t kr|tk r|j dkrtd|dS)N)r9z%s object does not have a value)r)r*rarrr rr rrrrr%rrrR)r+rPrcrrr0r0r1r_vs z ScalarObjectAttributeImpl.deletecCs\|j|krt||||jS|t@r.|tN}|j|||d}|tkrJtSt|||SdS)N)r9)r%rfrom_object_attributer rarr)r+rPrcr9rr0r0r1r7s 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)r9)NN)r%rrarrr rr)r+rPrcr9rroriginalr0r0r1rs$    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. )r9Nz2Object %s not associated with %s on attribute '%s')r)r*rarrr rr rr ValueErrorr rr%r) r+rPrcrBrr9rrrr0r0r1r]s& zScalarObjectAttributeImpl.setcCsV|jr |dk r |t||dx"|jjD]}||||p<|jq*W||||dS)NF)rvrr r)rrr)r+rPrcrBrrr0r0r1rs z+ScalarObjectAttributeImpl.fire_remove_eventcCs|jr.||k r.|dttfkr.|t||dx$|jjD]}|||||pL|j}q8W|||||jr|dk r|t||d|S)NFT) rvrrrr r)r]rr)r+rPrcrBrrrr0r0r1rs z,ScalarObjectAttributeImpl.fire_replace_event)rTrXrYrZr|r5r3rrsr_rr7rrr]rrr0r0r0r1rgs $ & 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)rvrr _sa_linkerinit_collectioncSs||dS)N)r)targetrcollection_adapterr0r0r1linkNsz.CollectionAttributeImpl.__init__..linkdispose_collectioncSs|ddS)N)r)rrrr0r0r1unlinkRsz0CollectionAttributeImpl.__init__..unlink)rrr2_CollectionAttributeImpl__copyrrro OP_APPENDrrrOP_BULK_REPLACErr"duck_type_collectionrrQr Z listens_for) r+r$r%rur) typecallablervrZ copy_functionrrKrr)rCr0r1r2)s*     z CollectionAttributeImpl.__init__cCsddt|DS)NcSsg|]}|qSr0r0).0yr0r0r1 Wsz2CollectionAttributeImpl.__copy..)rr)r+itemr0r0r1Z__copyVszCollectionAttributeImpl.__copycCs.|j|||d}|tkrtSt|||SdS)N)r9)rarrrfrom_collection)r+rPrcr9rr0r0r1r7Ysz#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 )rcr0r0r1rmsz;CollectionAttributeImpl.get_all_pending..cSs$g|]}|dk rt|pd|fqS)N)r )rrr0r0r1rqscs g|]\}}|kr||fqSr0r0)rso) original_setr0r1rzscs g|]\}}|kr||fqSr0r0)rrr)rr0r1r~scs g|]\}}|kr||fqSr0r0)rrr) current_setr0r1rscSsg|]}t||fqSr0)r )rrr0r0r1rs)r%rQrrrdict)r+rPrcr9rrcurrent_statesoriginal_statesr0)rrr1r`s"       "  z'CollectionAttributeImpl.get_all_pendingcCsXx"|jjD]}||||p|j}q W|||td|jrT|dk rT|t||d|S)NT)r)rrrrrvrr )r+rPrcrBrrr0r0r1fire_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+rPrcrr0r0r1fire_pre_remove_events z-CollectionAttributeImpl.fire_pre_remove_eventcCsX|jr |dk r |t||dx"|jjD]}||||p<|jq*W|||tddS)NFT)rvrr r)rrrr)r+rPrcrBrrr0r0r1rs z)CollectionAttributeImpl.fire_remove_eventcCs@|j|krdS|||td|||j}|||j=dS)NT)r%rrget_collectionrZclear_with_event)r+rPrcrr0r0r1r_s  zCollectionAttributeImpl.deletecCs||\}}|||j<|S)z3Initialize this attribute with an empty collection.)_initialize_collectionr%)r+rPrc_ user_datar0r0r1rs z"CollectionAttributeImpl.initializecCs0|j|j||j\}}|j|||||fS)N)r.Zinitialize_collectionr%rr)r)r+rPadapterrr0r0r1rsz.CollectionAttributeImpl._initialize_collectioncCsL|j|||d}|tkr<|||||}||j|n |||dS)N)r9)rrr_get_pending_mutationr%rZappend_with_event)r+rPrcrBrr9rr0r0r1rs zCollectionAttributeImpl.appendcCsN|j||j|d}|tkr>|||||||j|n |||dS)N)r9)rrrrrr%rZremove_with_event)r+rPrcrBrr9rr0r0r1rs zCollectionAttributeImpl.removec Cs8y|j|||||dWntttfk r2YnXdS)N)r9)rrr IndexError)r+rPrcrBrr9r0r0r1rszCollectionAttributeImpl.popcCsV|}} ||\} } |r| jdk r0| |}nt|} |j} | | k rt|dkrTdpZ|jj}|jj}td||ft|dr| }n2| t krtj r| }qt |d|j }nt|}t|}|j}|j||||j||td}|tkr|||}n|| kr dS||||d|j}| ||j<tj||| |d|`|j|||dS)NNonez/Incompatible collection type: %s is not %s-like _sa_iteratorZ itervalues)r9T)r)rZ _converterr"rrrCrT TypeErrorhasattrrrZpy3kvaluesrQiterlistrr)Z bulk_replacerarrrrrr%rr)r+rPrcrBrr9rZ_adaptiterableZ orig_iterableZnew_collectionrZ setting_typeZreceiving_typeZgivenZwantedZ new_valuesZevtrZold_collectionr0r0r1r]sL          zCollectionAttributeImpl.setcCst|d}d|_dS)NrT)rQZ invalidated)r+rrr0r0r1_invalidate_collection/s z.CollectionAttributeImpl._invalidate_collectionc Cs||\}}|r||||j|j<|||jg|j|jkr||||d|j|j}|j}|j }x|D]} | | qtWx|D]} | | qW|S)z=Set an attribute value on the given instance and 'commit' it.T) rZappend_multiple_without_eventrr%rZ_pending_mutationsrrZ added_itemsZ deleted_itemsZappend_without_eventZremove_without_event) r+rPrcrBrrZpendingaddedZremovedrr0r0r1r3s     z+CollectionAttributeImpl.set_committed_valuecCs.|dkr$|j|||d}|tkr$|St|dS)zRetrieve the CollectionAdapter associated with the given state. Creates a new CollectionAdapter if one does not exist. N)r9r)rarrQ)r+rPrcrr9r0r0r1rNs z&CollectionAttributeImpl.get_collection)NFNNN)rTrXrYrZr|r5r3rrrsr2rrr7rrrrrr_rrrrrr]rrrrr0r0)rCr1rs> #  (      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".)rrrpr&) child_stater child_impl)rlr0r1_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)r9)rrr r r.r&rrrrrrrrrprr) rPchildZoldchildrZ old_stateZold_dictr&Zcheck_recursive_tokenr child_dictrcheck_append_tokencheck_bulk_replace_token)rr% parent_implrpr0r1"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)r9) r r r.r&rprrrrrr)rPrrrrrrr)rr%rpr0r1)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)r9)rrr r r.r&rrrrrr"Z has_dupesrr%rrr) rPrrrrrZcheck_remove_tokenZcheck_replace_tokenZcheck_for_dupes_on_remove)r%ruselistr0r1)emit_backref_from_collection_remove_events2     zDbackref_listeners..emit_backref_from_collection_remove_eventrT)rkrawr]rN)r&rpr Zlisten)rlr%rrrrr0)rrlr%rrprr1backref_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+r0r0r1__bool__CszHistory.__bool__cCst|jp|jp|j S)zhReturn True if this :class:`.History` has no changes and no existing, unchanged state. )boolrrr)r+r0r0r1emptyHsz History.emptycCs|jpg|jpg|jpgS)z3Return a collection of added + unchanged + deleted.)rrr)r+r0r0r1sumPsz History.sumcCs|jpg|jpgS)z)Return a collection of added + unchanged.)rr)r+r0r0r1 non_deletedWszHistory.non_deletedcCs|jpg|jpgS)z+Return a collection of unchanged + deleted.)rr)r+r0r0r1 non_added\szHistory.non_addedcCst|jp |jS)z2Return True if this :class:`.History` has changes.)rrr)r+r0r0r1 has_changesaszHistory.has_changescCs0tdd|jDdd|jDdd|jDS)NcSs g|]}|dk rt|pdqS)N)r )rrr0r0r1risz$History.as_state..cSs g|]}|dk rt|pdqS)N)r )rrr0r0r1rmscSs g|]}|dk rt|pdqS)N)r )rrr0r0r1rqs)rrrr)r+r0r0r1as_statefszHistory.as_statecCs|j|jt}|tkr<|tkr,|dddS|d|gdSnh|||dkrZ|d|gdSt|tkr|d}t|tkrd}n|g}|tkr|dd|S||gd|SdS)Nr0T)rrar% _NO_HISTORYrrzr_NO_STATE_SYMBOLS)rFrlrPrrrr0r0r1rvs    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)Nr0)rrar%rrrrr)rFrlrPrrrr0r0r1rs   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) Nr0rcSs$g|]}|dk rt|pd|fqS)N)r )rrr0r0r1rsz+History.from_collection..cSs$g|]}|dk rt|pd|fqS)N)r )rrr0r0r1rscsg|]\}}|kr|qSr0r0)rrr)rr0r1rscsg|]\}}|kr|qSr0r0)rrr)rr0r1rscsg|]\}}|kr|qSr0r0)rrr)rr0r1rs) rrar%rrrrQrr)rFrlrPrrrrr0)rrr1rs$   zHistory.from_collectionN)rTrXrYrZrZ __nonzero__rrrrrr classmethodrrrr0r0r0r1r*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%r9r0r0r1r7s"r7cCs |||S)N)r7)rPr%r9r0r0r1r srFcCst|}t|}||||S)ZTODO)rr has_parent)rFrr%rNr.rPr0r0r1r srcKsH|dd}|dd}|dd}t|||||d}t||f||S)Nr'r,ri)ri)rregister_descriptorregister_attribute_impl)r$r%rr'r,riZdescr0r0r1register_attributes    rc 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%rruZ useobjectZ impl_classZbackrefrr.factoryrr)r&r0r0r1rs*      rcCs.t|}t||||d}||_||||S)N)r'r,)rr\rZZinstrument_attribute)r$r%r'r,rir.rer0r0r1rIs  rcCst||dS)N)rZuninstrument_attribute)r$r%r0r0r1unregister_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%rPrcr0r0r1r\srcCs&|j|j}|||}||||S)zDInitialize a collection attribute and return the collection adapter.)r.r&rr)rPrcr%rrr0r0r1r 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)r8r%rBrPrcr0r0r1r{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])r8r%rBrrPrcr0r0r1 set_attributesr cCs&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&ra)r8r%rPrcr0r0r1 get_attributes r cCs*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&r_)r8r%rPrcr0r0r1 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)r8r%rPrcr&r0r0r1 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)r8rPrcr0r0r1 flag_dirtysr)F)FNFNN)NNN)N)NrZrxrrrrr/rrrr r r r r rrrrrrrrrrrrrrrrrr r!r"Z_self_inspectsZ_MappedAttributeZInspectionAttrZPropComparatorr#r\rnZsymbolrrrrr~objectrortrrrrr frozensetrr namedtuplerrr7rrrrrr rr rr r rrrr0r0r0r1s                                Jx     2FU(RE +  2    &