B 4]Dy@sdZddlZddlmZddlmZddlmZddlmZddlmZdd lm Z dd lm Z dd lm Z dd lm Z dd lm Z ddlmZddlmZddlmZddlmZddlmZejGdddejZGdddeZGdddeZdS)zDefines instrumentation of instances. This module is usually not directly visible to user applications, but defines a large part of the ORM's interactivity. N)base)exc) interfaces) ATTR_WAS_SET)INIT_OK) NEVER_SET)NO_VALUE)PASSIVE_NO_INITIALIZE)PASSIVE_NO_RESULT) PASSIVE_OFF)SQL_OK) PathRegistry) inspection)utilc@sNeZdZdZdZdZdZejZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZddZdZejdd Zed d Zed d ZeddZeddZeddZeddZ ee!dddZ"ddZ#ee!dddZ$eddZ%edd Z&ed!d"Z'ejd#d$Z(ejd%d&Z)ejd'd(Z*ed)d*Z+e,dcd+d,Z-ddd-d.Z.d/d0Z/d1d2Z0d3d4Z1ed5d6Z2d7d8Z3d9d:Z4d;d<Z5d=d>Z6d?d@Z7dAdBZ8dCdDZ9dEdFZ:e,dGdHZ;dIdJZedOdPZ?dQdRZ@edSdTZAedUdVZBedWdXZCdYdZZDdfd[d\ZEd]d^ZFdgd_d`ZGe,dhdadbZHdS)i InstanceStateatracks state information at the instance level. The :class:`.InstanceState` is a key object used by the SQLAlchemy ORM in order to track the state of an object; it is created the moment an object is instantiated, typically as a result of :term:`instrumentation` which SQLAlchemy applies to the ``__init__()`` method of the class. :class:`.InstanceState` is also a semi-public object, available for runtime inspection as to the state of a mapped instance, including information such as its current status within a particular :class:`.Session` and details about data on individual attributes. The public API in order to acquire a :class:`.InstanceState` object is to use the :func:`.inspect` system:: >>> from sqlalchemy import inspect >>> insp = inspect(some_mapped_object) .. seealso:: :ref:`core_inspection_toplevel` NFTcCs0|j|_||_t||j|_i|_t|_ dS)N) __class__class_managerweakrefref_cleanupobjcommitted_statesetexpired_attributes)selfrrrrG/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/state.py__init__Ys zInstanceState.__init__csttfddjDS)aaReturn a namespace representing each attribute on the mapped object, including its current value and history. The returned object is an instance of :class:`.AttributeState`. This object allows inspection of the current data within an attribute as well as attribute history since the last flush. c3s|]}|t|fVqdS)N)AttributeState).0key)rrr usz&InstanceState.attrs..)rZImmutablePropertiesdictr)rr)rrattrshs zInstanceState.attrscCs|jdko|j S)zyReturn true if the object is :term:`transient`. .. seealso:: :ref:`session_object_states` N)r# _attached)rrrr transientxs zInstanceState.transientcCs|jdko|jS)zxReturn true if the object is :term:`pending`. .. seealso:: :ref:`session_object_states` N)r#r')rrrrpendings zInstanceState.pendingcCs|jdk o|jo|jS)aReturn true if the object is :term:`deleted`. An object that is in the deleted state is guaranteed to not be within the :attr:`.Session.identity_map` of its parent :class:`.Session`; however if the session's transaction is rolled back, the object will be restored to the persistent state and the identity map. .. note:: The :attr:`.InstanceState.deleted` attribute refers to a specific state of the object that occurs between the "persistent" and "detached" states; once the object is :term:`detached`, the :attr:`.InstanceState.deleted` attribute **no longer returns True**; in order to detect that a state was deleted, regardless of whether or not the object is associated with a :class:`.Session`, use the :attr:`.InstanceState.was_deleted` accessor. .. versionadded: 1.1 .. seealso:: :ref:`session_object_states` N)r#r'_deleted)rrrrdeletedszInstanceState.deletedcCs|jS)aReturn True if this object is or was previously in the "deleted" state and has not been reverted to persistent. This flag returns True once the object was deleted in flush. When the object is expunged from the session either explicitly or via transaction commit and enters the "detached" state, this flag will continue to report True. .. versionadded:: 1.1 - added a local method form of :func:`.orm.util.was_deleted`. .. seealso:: :attr:`.InstanceState.deleted` - refers to the "deleted" state :func:`.orm.util.was_deleted` - standalone function :ref:`session_object_states` )r*)rrrr was_deletedszInstanceState.was_deletedcCs|jdk o|jo|j S)a{Return true if the object is :term:`persistent`. An object that is in the persistent state is guaranteed to be within the :attr:`.Session.identity_map` of its parent :class:`.Session`. .. versionchanged:: 1.1 The :attr:`.InstanceState.persistent` accessor no longer returns True for an object that was "deleted" within a flush; use the :attr:`.InstanceState.deleted` accessor to detect this state. This allows the "persistent" state to guarantee membership in the identity map. .. seealso:: :ref:`session_object_states` N)r#r'r*)rrrr persistentszInstanceState.persistentcCs|jdk o|j S)zxReturn true if the object is :term:`detached`. .. seealso:: :ref:`session_object_states` N)r#r')rrrrdetacheds zInstanceState.detachedzsqlalchemy.orm.sessioncCs|jdk o|j|jkS)N) session_idZ _sessions)r sessionlibrrrr's zInstanceState._attachedcCs$||jkr t|j|_t|j|<dS)z|Track the last known value of a particular key after expiration operations. .. versionadded:: 1.3 N)_last_known_valuesr%r )rr#rrr_track_last_known_values  z%InstanceState._track_last_known_valuecCs ||S)aReturn the owning :class:`.Session` for this instance, or ``None`` if none available. Note that the result here can in some cases be *different* from that of ``obj in session``; an object that's been deleted will report as not ``in session``, however if the transaction is still in progress, this attribute will still refer to that session. Only when the transaction is completed does the object become fully detached under normal circumstances. )Z_state_session)rr0rrrsessionszInstanceState.sessioncCs|S)zMReturn the mapped object represented by this :class:`.InstanceState`.)r)rrrrobject szInstanceState.objectcCs|jdkrdS|jdSdS)aReturn the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to :meth:`.Query.get`. Returns ``None`` if the object has no primary key identity. .. note:: An object which is :term:`transient` or :term:`pending` does **not** have a mapped identity until it is flushed, even if its attributes include primary key values. Nr)r#)rrrridentitys zInstanceState.identitycCs|jS)zReturn the identity key for the mapped object. This is the key used to locate the object within the :attr:`.Session.identity_map` mapping. It contains the identity as returned by :attr:`.identity` within it. )r#)rrrr identity_key#s zInstanceState.identity_keycCsiS)Nr)rrrrparents1szInstanceState.parentscCsiS)Nr)rrrr_pending_mutations5sz InstanceState._pending_mutationscCs|jjS)z8Return the :class:`.Mapper` used for this mapped object.)rmapper)rrrrr99szInstanceState.mappercCs t|jS)zReturn ``True`` if this object has an identity key. This should always have the same value as the expression ``state.persistent or state.detached``. )boolr#)rrrr has_identity>szInstanceState.has_identityc Cs|jjp d}|jjpd}|jjp"d}|jjp.d}x|D]}|j} |jdk} | oT| } d|_|rj|jrj|`| r|r|dk r|} | dk r||| n"|dk r|} | dk r||| nT| r|dk r|} | dk r||| n,| r|dk r|} | dk r||| d|_ q6WdS)N) dispatchpersistent_to_detacheddeleted_to_detachedpending_to_transientpersistent_to_transientr*r#r/r _strong_obj) rZstatesr3Z to_transientr=r>r?r@stater+r)r-rrrr_detach_statesHs<              zInstanceState._detach_statescCs$|rt|g|n d|_|_dS)N)rrCr/rA)rr3rrr_detachqszInstanceState._detachcCs||`dS)N)rDr)rrrr_disposewszInstanceState._disposecCs>tdkr dS|}|dk r*|||`d|_|_|`dS)zWeakref callback cleanup. This callable cleans out the state when it is being garbage collected. this _cleanup **assumes** that there are no strong refs to us! Will not work otherwise! N)r%_instance_dictZ _fast_discardr/rAr)rr instance_dictrrrr{s  zInstanceState._cleanupcCsdS)Nr)rrrrrszInstanceState.objcCs"|}|dk rt|SiSdS)aReturn the instance dict used by the object. Under normal circumstances, this is always synonymous with the ``__dict__`` attribute of the mapped object, unless an alternative instrumentation system has been configured. In the case that the actual object has been garbage collected, this accessor returns a blank dictionary. N)rrrG)rorrrr%s  zInstanceState.dictc Os|d|d|dd}}}|j}|j|||y|j|dd|St|j|||WdQRXYnXdS)Nrrr)rr<ZinitZ original_initrZ safe_reraiseZ init_failure)Zmixedkwargsrinstanceargsrrrr_initialize_instances  z"InstanceState._initialize_instancecCs|j|j||j|S)N)rimpl get_historyr%)rr#passiverrrrNszInstanceState.get_historycCs |j|jS)N)rrM)rr#rrrget_implszInstanceState.get_implcCs ||jkrt|j|<|j|S)N)r8PendingCollection)rr#rrr_get_pending_mutations  z#InstanceState._get_pending_mutationcsNdi}|fdddDjr8j|d<j||d<|S)NrJc3s&|]}|jkr|j|fVqdS)N)__dict__)r"k)rrrr$s z-InstanceState.__getstate__..) rr8modifiedexpired callablesr#r7 load_optionsrrinfo load_pathr)rupdaterZZ serializerZ _serialize)r state_dictr)rr __getstate__s   zInstanceState.__getstate__csd}|dk r*t||j|_|j|_nd|_d|_di|_di|_di|_ dd|_ dd|_ d kr|j d d krd |_yd |_WnTtk rt|_x4t|jD]&}|j||kr|j||j|=qWYnXnd kr(d |_nt|_|j fd d dD|jry|jd|_Wn(tk r|jd|_d|_YnXdkrtd|_d||dS)NrJrrr8r7rUFrVrYrWrcs g|]}|kr||fqSrr)r"rT)r\rr sz.InstanceState.__setstate__..)r#rXr)NrZr)rrrrrrgetrr8r7rUrVrYr[rWrKeyErrorrlistaddrSr#identity_token IndexErrorrZ deserializerZ)rr\instrTr)r\r __setstate__sL            zInstanceState.__setstate__cCsX||d}|dk r4|j|jjr4|j|j||j||jrT|j|ddS)zKRemove the given attribute and any callables associated with it.N)poprrM collection_invalidate_collectionrdiscardrW)rdict_r#oldrrr_resets   zInstanceState._resetcCsd|jkrt|j|_dS)NrW)rSr%rW)rZfrom_rrr_copy_callables%s zInstanceState._copy_callablescs4|jjr"fdd}nfdd}|S)Ncs<d|jkri|_|d}|dk r.||j<dS)NrW)rSrWrgri)rBrkrowrl)fnrMr#rr _set_callable.s    zGInstanceState._instance_level_callable_processor.._set_callablecsd|jkri|_|j<dS)NrW)rSrW)rBrkro)rpr#rrrq8s )rMrh)clsrrpr#rqr)rprMr#r"_instance_level_callable_processor)s   z0InstanceState._instance_level_callable_processorcsd|_|jr&|||jd|_d|_d|jkr>|jd=d|jkrP|jd=|jfdd|j j D|j rx|j |j D] }|j |=qWx(|j j D]}|}d|j_qW|jr|jfdd|jDx|j j D] }|=qW|j j|ddS) NTFr8r7cs"g|]}|js|jkr|jqSr)expire_missingr#)r"rM)rkrrr^Qsz)InstanceState._expire..c3s"|]}|kr||fVqdS)Nr)r"rT)rkrrr$asz(InstanceState._expire..)rVrUrjrclearrArSrr[rZ_scalar_loader_implsrW intersectionZ_collection_impl_keysrgZ _sa_adapterZ invalidatedr1Z _all_key_setr<expire)rrkZ modified_setrTrhr#r)rkr_expire?s2         zInstanceState._expirec Cs|jdd}|j}x|D]}|j|j}|jrb|rD|js||krDq|j||rb||krb||=| |t }|j r|t k r| ||j r||j kr|t k r||j |<|j |d|r| |dqW|jj||dS)Nr8)rSr_rWrrMaccepts_scalar_loaderZ callable_rrbrgr rhrir1rr<rw) rrkZattribute_namesZ no_loaderr)rWr#rMrlrrr_expire_attributesis*        z InstanceState._expire_attributescCs6|t@s tS|j|j}|j|||jtS)z__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable). ) r r rrv unmodifiedrZdeferred_scalar_loaderrur)rrBrOZtoloadrrr _load_expireds  zInstanceState._load_expiredcCst|j|jS)z8Return the set of keys which have no uncommitted changes)rr differencer)rrrrr{szInstanceState.unmodifiedcCst||j|jS)z*Return self.unmodified.intersection(keys).)rrvrr}r)rkeysrrrunmodified_intersectionsz%InstanceState.unmodified_intersectioncCst|j|j|jS)zReturn the set of keys which do not have a loaded value. This includes expired attributes and any other attribute that was never populated or modified. )rrr}rr%)rrrrunloadeds zInstanceState.unloadedcsjfddjDS)zReturn the set of keys which do not have a loaded value. This includes expired attributes and any other attribute that was never populated or modified. c3s |]}j|jjr|VqdS)N)rrMrt)r"attr)rrrr$sz3InstanceState.unloaded_expirable..)rrvr)rr)rrunloaded_expirables z InstanceState.unloaded_expirablecsjfddjDS)Nc3s |]}j|jjr|VqdS)N)rrMry)r"r)rrrr$sz5InstanceState._unloaded_non_object..)rrvr)rr)rr_unloaded_non_objects z"InstanceState._unloaded_non_objectcCsdS)Nr)rrrrrFszInstanceState._instance_dictcCs|r|jsdS|r,|j|kr,td|j|j|jks<|r|rt|tkr\|j|kr\||j}|dttfkrt||}||j|j<|j|jkrt|j|j<|j r|j dks|j sd|_ | }|r|j ||}|j r||_ |dkr|rtd|j|jt|fdS)NzHCan't flag attribute '%s' modified; it's not present in the object stateTzaCan't emit change event for attribute '%s' - parent object of type %s has been garbage collected.)Zsend_modified_eventsr#sa_excZInvalidRequestErrorrrr copyr1r/rArUrF _modifiedrbrorm_excZObjectDereferencedErrorrrZstate_class_str)rrkrZpreviousrhZ is_userlandrGrerrr_modified_events:        zInstanceState._modified_eventcCsjx|D]}|j|dqWd|_|jt|||jrfx&t|j||D] }|j|=qVWdS)a8Commit attributes. This is used by a partial-attribute load operation to mark committed those attributes which were refreshed from the database. Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict. NF)rrgrVrdifference_updaterrvrW)rrkr~r#rrr_commits zInstanceState._commitcCs|||fg|dS)aScommit all attributes unconditionally. This is used after a flush() or a full load/refresh to remove all pending state from the instance. - all attributes are marked as "committed" - the "strong dirty reference" is removed - the "modified" flag is set to False - any "expired" markers for scalar attributes loaded are removed. - lazy load callables for objects / collections *stay* Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict. N)_commit_all_states)rrkrGrrr _commit_all szInstanceState._commit_allcCshxb|D]Z\}}|j}|jd|kr,|d=|j||rN|jrN|j|d|_|_d|_ qWdS)z.Mass / highly inlined version of commit_all().r8FN) rSrrurrrUrrjrVrA)rZiter_rGrBrkr\rrrr2s     z InstanceState._commit_all_states)F)N)F)FF)N)N)I__name__ __module__ __qualname____doc__r/r#ZrunidrZ EMPTY_SETrXrZZ insert_orderrArUrVr*Z _load_pendingZ_orphaned_outside_of_sessionZ is_instancercr1rWr rZmemoized_propertyr&propertyr(r)r+r,r-r.Z dependenciesr'r2r3r4r5r6r7r8r9r; classmethodrCrDrErrr%rLrNrPrRr]rfrmrnrsrxrzr|r{rrrrrFrrrrrrrrr"s           (   :  *      . rc@sDeZdZdZddZeddZeddZedd Zd d Z d S) r!aProvide an inspection interface corresponding to a particular attribute on a particular mapped object. The :class:`.AttributeState` object is accessed via the :attr:`.InstanceState.attrs` collection of a particular :class:`.InstanceState`:: from sqlalchemy import inspect insp = inspect(some_mapped_object) attr_state = insp.attrs.some_attribute cCs||_||_dS)N)rBr#)rrBr#rrrr VszAttributeState.__init__cCs|jj|jtS)zThe current value of this attribute as loaded from the database. If the value has not been loaded, or is otherwise not present in the object's dictionary, returns NO_VALUE. )rBr%r_r#r )rrrr loaded_valueZszAttributeState.loaded_valuecCs |jj|j|j|jjS)zReturn the value of this attribute. This operation is equivalent to accessing the object's attribute directly or via ``getattr()``, and will fire off any pending loader callables if needed. )rBrr#__get__rr)rrrrvalueds zAttributeState.valuecCs|j|jtS)aXReturn the current **pre-flush** change history for this attribute, via the :class:`.History` interface. This method will **not** emit loader callables if the value of the attribute is unloaded. .. note:: The attribute history system tracks changes on a **per flush basis**. Each time the :class:`.Session` is flushed, the history of each attribute is reset to empty. The :class:`.Session` by default autoflushes each time a :class:`.Query` is invoked. For options on how to control this, see :ref:`session_flushing`. .. seealso:: :meth:`.AttributeState.load_history` - retrieve history using loader callables if the value is not locally present. :func:`.attributes.get_history` - underlying function )rBrNr#r )rrrrhistoryqszAttributeState.historycCs|j|jttAS)aReturn the current **pre-flush** change history for this attribute, via the :class:`.History` interface. This method **will** emit loader callables if the value of the attribute is unloaded. .. note:: The attribute history system tracks changes on a **per flush basis**. Each time the :class:`.Session` is flushed, the history of each attribute is reset to empty. The :class:`.Session` by default autoflushes each time a :class:`.Query` is invoked. For options on how to control this, see :ref:`session_flushing`. .. seealso:: :attr:`.AttributeState.history` :func:`.attributes.get_history` - underlying function .. versionadded:: 0.9.0 )rBrNr#r r)rrrr load_historyszAttributeState.load_historyN) rrrrr rrrrrrrrrr!Gs   r!c@s(eZdZdZddZddZddZdS) rQaA writable placeholder for an unloaded collection. Stores items appended to and removed from a collection that has not yet been loaded. When the collection is loaded, the changes stored in PendingCollection are applied to it to produce the final result. cCst|_t|_dS)N)rZ IdentitySet deleted_itemsZOrderedIdentitySet added_items)rrrrr s zPendingCollection.__init__cCs(||jkr|j|n |j|dS)N)rremoverrb)rrrrrappends zPendingCollection.appendcCs(||jkr|j|n |j|dS)N)rrrrb)rrrrrrs zPendingCollection.removeN)rrrrr rrrrrrrQsrQ)rrrrrrrrrr r r r r Z path_registryrrrrZ_self_inspectsZInspectionAttrInforr4r!rQrrrr s4                *`