o znhDy@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@sTeZdZdZdZdZdZejZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZ ddZdZ ejdd 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@edSdTZAedUdVZBedWdXZCdYdZZD ded[d\ZEd]d^ZFddd_d`ZGe,dddadbZHdS)f 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|_ dSN) __class__class_managerweakrefref_cleanupobjcommitted_statesetexpired_attributes)selfrrrr?/usr/local/lib/python3.10/dist-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|fVqdSr)AttributeState).0keyrrr usz&InstanceState.attrs..)rImmutablePropertiesdictrr%rr%r attrshs zInstanceState.attrscCs|jduo|j S)zyReturn true if the object is :term:`transient`. .. seealso:: :ref:`session_object_states` Nr$ _attachedr%rrr transientx zInstanceState.transientcCs|jduo|jS)zxReturn true if the object is :term:`pending`. .. seealso:: :ref:`session_object_states` Nr*r%rrr pendings zInstanceState.pendingcCs|jduo |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` Nr$r+_deletedr%rrr deletedszInstanceState.deletedcC|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` )r0r%rrr was_deletedszInstanceState.was_deletedcCs|jduo |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` Nr/r%rrr persistentszInstanceState.persistentcCs|jduo|j S)zxReturn true if the object is :term:`detached`. .. seealso:: :ref:`session_object_states` Nr*r%rrr detachedr-zInstanceState.detachedzsqlalchemy.orm.sessioncCs|jduo |j|jvSr) session_id _sessionsr sessionlibrrr r+s  zInstanceState._attachedcCs(||jvrt|j|_t|j|<dSdS)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. )_state_sessionr8rrr sessions zInstanceState.sessioncCs|S)zMReturn the mapped object represented by this :class:`.InstanceState`.)rr%rrr object szInstanceState.objectcCs|jdurdS|jdS)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. Nrr$r%rrr identitys  zInstanceState.identitycCr2)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@r%rrr identity_key#s zInstanceState.identity_keycCiSrrr%rrr parents1zInstanceState.parentscCrCrrr%rrr _pending_mutations5rEz InstanceState._pending_mutationscCs|jjS)z8Return the :class:`.Mapper` used for this mapped object.)rmapperr%rrr rG9szInstanceState.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$r%rrr has_identity>s zInstanceState.has_identityc Cs|jjpd}|jjp d}|jjpd}|jjpd}|D]l}|j} |jdu} | o)| } d|_|r4|jr4|`| r\|rJ|durI|} | durI||| n9|dur[|} | dur[||| n'| rp|durp|} | duro||| n| r|dur|} | dur||| d|_ qdSr) dispatchpersistent_to_detacheddeleted_to_detachedpending_to_transientpersistent_to_transientr0r$r6r _strong_obj) rstatesr> to_transientrKrLrMrNstater1r.r4rrrr _detach_statesHsH             zInstanceState._detach_statescCs&|r t|g|dSd|_|_dSr)rrSr6rO)rr>rrr _detachqszInstanceState._detachcCs||`dSr)rTrr%rrr _disposewszInstanceState._disposecCs>tdurdS|}|dur|||`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_dict _fast_discardr6rOr)rr instance_dictrrr r{s  zInstanceState._cleanupcCdSrrr%rrr rzInstanceState.objcCs|}|dur t|SiS)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)rrrX)rorrr r(s  zInstanceState.dictc Os|d|d|dd}}}|j}|j|||z |j|ddi|WSt|j|||WdYdS1sEwYYdS)Nrrr)rrJinit original_initr safe_reraise init_failure)mixedkwargsrinstanceargsrrrr _initialize_instances  &z"InstanceState._initialize_instancecCs|j|j||j|Sr)rimpl get_historyr()rr$passiverrr rfszInstanceState.get_historycCs |j|jSr)rrer;rrr get_impls zInstanceState.get_implcCs ||jvr t|j|<|j|Sr)rFPendingCollectionr;rrr _get_pending_mutations   z#InstanceState._get_pending_mutationcsNdi}|fdddDjrj|d<j||d<|S)Nrbc3s(|]}|jvr|j|fVqdSr)__dict__r#kr%rr r&s z-InstanceState.__getstate__..) rrFmodifiedexpired callablesr$rD load_optionsrrinfo load_pathr)rupdaters serializer _serialize)r state_dictrr%r __getstate__s zInstanceState.__getstate__csd}|durt||j|_|j|_nd|_d|_di|_di|_di|_ dd|_ dd|_ d vrL|j d d vrd |_zd |_Wn4tyt|_t|jD]}|j||ur|j||j|=qlYnwd vrd |_nt|_|j fd d dD|jrz|jd|_Wntyt|jdksJ|jd|_d|_Ynwdvrtd|_d||dS)NrbrrrFrDrnFrorrrprcs g|] }|vr||fqSrrrlrwrr s  z.InstanceState.__setstate__..)r$rqrrrsr)rrrrrrgetrrFrDrnrorrrtrprKeyErrorrlistaddrkr$identity_token IndexErrorlenr deserializers)rrwinstrmrryr __setstate__sZ          zInstanceState.__setstate__cCs\||d}|dur|j|jjr|j|j||j||jr,|j|ddSdS)zKRemove the given attribute and any callables associated with it.N)poprre collection_invalidate_collectionrdiscardrp)rdict_r$oldrrr _resets  zInstanceState._resetcCsd|jvr t|j|_dSdSNrp)rkr(rp)rfrom_rrr _copy_callables%s zInstanceState._copy_callablescs6|jjrfdd}|Sfdd}|S)Ncs<d|jvri|_|d}|dur||j<dSr)rkrprr)rRrrowrfnrer$rr _set_callable.s   zGInstanceState._instance_level_callable_processor.._set_callablecsd|jvri|_|j<dSr)rkrp)rRrr)rr$rr r8s )rer)clsrrr$rrrr "_instance_level_callable_processor)s z0InstanceState._instance_level_callable_processorcsd|_|jr|||jd|_d|_d|jvr|jd=d|jvr(|jd=|jfdd|j j D|j rH|j |j D]}|j |=qA|j j D] }|}d|j_qO|jrl|jfdd|jD|j j D]}|=qs|j j|ddS) NTFrFrDcs"g|] }|js |jvr|jqSr)expire_missingr$)r#rerrr rzPs z)InstanceState._expire..c3s$|] }|vr||fVqdSrrrlrrr r&`sz(InstanceState._expire..)rornrrclearrOrkrrtr_scalar_loader_implsrp intersection_collection_impl_keysr _sa_adapter invalidatedr: _all_key_setrJexpire)rr modified_setrmrr$rrr _expire?s8        zInstanceState._expirec Cs|jdd}|j}|D]V}|j|j}|jr0|r!|js ||vr!q |j||r0||vr0||=| |t }|j rB|t urB| ||j rS||j vrS|t urS||j |<|j |d|rb| |dq |jj||dS)NrF)rkr{rprreaccepts_scalar_loader callable_rr~rr rrr:rrJr) rrattribute_names no_loaderr.rpr$rerrrr _expire_attributesis.        z InstanceState._expire_attributescCs6|t@stS|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 rr unmodifiedrdeferred_scalar_loaderrr)rrRrgtoloadrrr _load_expireds  zInstanceState._load_expiredcCst|j|jS)z8Return the set of keys which have no uncommitted changes)rr differencerr%rrr rszInstanceState.unmodifiedcCst||j|jS)z*Return self.unmodified.intersection(keys).)rrrrr)rkeysrrr unmodified_intersectionsz%InstanceState.unmodified_intersectioncCst|j|j|jS)Return 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. )rrrrr(r%rrr unloadeds zInstanceState.unloadedcjfddjDS)rc3"|] }j|jjr|VqdSr)rrerr#attrr%rr r&  z3InstanceState.unloaded_expirable..rrrr%rr%r unloaded_expirablesz InstanceState.unloaded_expirablecr)Nc3rr)rrerrr%rr r&rz5InstanceState._unloaded_non_object..rr%rr%r _unloaded_non_objectsz"InstanceState._unloaded_non_objectcCrYrrr%rrr rVrZzInstanceState._instance_dictcCs|rL|jsdS|r|j|vrtd|j|j|jvs|r@|r:|tur.|j|vr.||j}|dttfvr:||}||j|j<|j|jvrLt|j|j<|j rT|j dusW|j sd|_ | }|rf|j ||}|j rp||_ |dur|rtd|j|jt|fdSdSdS)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.)send_modified_eventsr$sa_excInvalidRequestErrorrrr copyr:r6rOrnrV _modifiedr~rorm_excObjectDereferencedErrorrrstate_class_str)rrrpreviousr is_userlandrXrrrr _modified_eventsF         zInstanceState._modified_eventcCsf|D] }|j|dqd|_|jt|||jr/t|j||D]}|j|=q(dSdS)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)rrrordifference_updaterrrp)rrrr$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)rrrXrrr _commit_all szInstanceState._commit_allcCsd|D]-\}}|j}|jd|vr|d=|j||r&|jr&|j|d|_|_d|_ qdS)z.Mass / highly inlined version of commit_all().rFFN) rkrrrrrnrrrorO)riter_rXrRrrwrrr r2s      z InstanceState._commit_all_states)Fr)FF)I__name__ __module__ __qualname____doc__r6r$runidr EMPTY_SETrqrs insert_orderrOrnror0 _load_pending_orphaned_outside_of_session is_instancerr:rpr!rmemoized_propertyr)propertyr,r.r1r3r4r5 dependenciesr+r<r>r?rArBrDrFrGrI classmethodrSrTrUrrr(rdrfrhrjrxrrrrrrrrrrrrrVrrrrrrrr r"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||_||_dSr)rRr$)rrRr$rrr r!Vs zAttributeState.__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. )rRr(r{r$r r%rrr 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. )rRrr$__get__rrr%rrr valueds 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 )rRrfr$r r%rrr historyqszAttributeState.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 )rRrfr$r rr%rrr load_historyszAttributeState.load_historyN) rrrrr!rrrrrrrrr r"Gs    r"c@s(eZdZdZddZddZddZdS) riaA 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|_dSr)r IdentitySet deleted_itemsOrderedIdentitySet added_itemsr%rrr r!s zPendingCollection.__init__cC*||jvr |j|dS|j|dSr)rremoverr~rrrrr append zPendingCollection.appendcCrr)rrrr~rrrr rrzPendingCollection.removeN)rrrrr!rrrrrr ris  ri)rrrrrrrrrr r r r r path_registryrrrr_self_inspectsInspectionAttrInforr?r"rirrrr s6               *`