U a@sdZddlZddlmZddlmZddlmZddlmZddlmZdd lm Z dd lm Z dd lm Z dd lm Z dd lm Z ddlmZddlmZddlmZddlmZddlmZdZdZejGdddejZGdddeZGdddeZdS)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@s`eZdZdZdZdZdZejZ e j Z dZ dZdZdZdZdZdZdZdZdZdZddZdZejdd Zed d Zed d ZeddZeddZ eddZ!eddZ"ee#dddZ$ddZ%eddZ&eddZ'edd Z(ed!d"Z)ed#d$Z*ejd%d&Z+ejd'd(Z,ejd)d*Z-ejd+d,Z.ed-d.Z/e0dgd/d0Z1dhd1d2Z2d3d4Z3d5d6Z4d7d8Z5ed9d:Z6d;d<Z7d=d>Z8d?d@Z9dAdBZ:dCdDZ;dEdFZe0dKdLZ?dMdNZ@didOdPZAdQdRZBedSdTZCdUdVZDedWdXZEedYdZZFed[d\ZGd]d^ZHdjd_d`ZIdadbZJdkdcddZKe0dldedfZLdS)m 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:`_sa.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)selfrrrrUC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\state.py__init__`s 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 |sz&InstanceState.attrs..)rZImmutablePropertiesdictrr%rr%r attrsos zInstanceState.attrscCs|jdko|j S)z}Return ``True`` if the object is :term:`transient`. .. seealso:: :ref:`session_object_states` Nr$ _attachedr%rrr transients zInstanceState.transientcCs|jdko|jS)z|Return ``True`` if the object is :term:`pending`. .. seealso:: :ref:`session_object_states` Nr)r%rrr pendings 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` Nr$r*_deletedr%rrr deletedszInstanceState.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.r%rrr 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` Nr-r%rrr persistentszInstanceState.persistentcCs|jdk o|j S)z|Return ``True`` if the object is :term:`detached`. .. seealso:: :ref:`session_object_states` Nr)r%rrr detacheds zInstanceState.detachedzsqlalchemy.orm.sessioncCs|jdk o|jtjjjkSr) session_idrZ preloadedZ orm_session _sessionsr%rrr r*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,|jr(z t|jWStk r&YnXdS)aLReturn 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. .. seealso:: :attr:`_orm.InstanceState.async_session` N)r3r4KeyErrorr%rrr sessions  zInstanceState.sessioncCs*tdkr dS|j}|dk r"t|SdSdS)aGReturn the owning :class:`_asyncio.AsyncSession` for this instance, or ``None`` if none available. This attribute is only non-None when the :mod:`sqlalchemy.ext.asyncio` API is in use for this ORM object. The returned :class:`_asyncio.AsyncSession` object will be a proxy for the :class:`_orm.Session` object that would be returned from the :attr:`_orm.InstanceState.session` attribute for this :class:`_orm.InstanceState`. .. versionadded:: 1.4.18 .. seealso:: :ref:`asyncio_toplevel` N)_async_providerr9)rsessrrr async_sessions zInstanceState.async_sessioncCs|S)zMReturn the mapped object represented by this :class:`.InstanceState`.)rr%rrr object4szInstanceState.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.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 identity:s 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>r%rrr identity_keyNs zInstanceState.identity_keycCsiSrrr%rrr parents\szInstanceState.parentscCsiSrrr%rrr _pending_mutations`sz InstanceState._pending_mutationscCsiSrrr%rrr _empty_collectionsdsz InstanceState._empty_collectionscCs|jjS)ztdkr 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_discardr3rLr)rr instance_dictrrr rs  zInstanceState._cleanupcCsdSrrr%rrr rszInstanceState.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)rrrR)rorrr r's  zInstanceState.dictc Os|d|d|dd}}}|j}|j|||z|j|dd|WSt|j|||W5QRXYnXdS)Nrrr)rrGinitZ original_initrZ safe_reraiseZ init_failure)mixedkwargsrinstanceargsrrrr _initialize_instances  z"InstanceState._initialize_instancecCs|j|j||j|Sr)rimpl get_historyr')rr$passiverrr r[szInstanceState.get_historycCs |j|jSr)rrZr6rrr get_implszInstanceState.get_implcCs ||jkrt|j|<|j|Sr)rBPendingCollectionr6rrr _get_pending_mutations  z#InstanceState._get_pending_mutationcsNdi}|fdddDjr8j|d<j||d<|S)NrWc3s&|]}|jkr|j|fVqdSr)__dict__r#kr%rr r&s z-InstanceState.__getstate__..) rrBmodifiedexpired callablesr$rA load_optionsrrinfo load_pathr)rupdaterh serializer _serialize)r state_dictrr%r __getstate__s zInstanceState.__getstate__csd}|dk r*t||j|_|j|_nd|_d|_di|_di|_di|_ dd|_ dd|_ d kr|j d d krd |_zd |_WnPtk r t|_t|jD]&}|j||kr|j||j|=qYnXnd kr$d |_nt|_|j fd d dD|jrz|jd|_Wn<tk rt|jdkst|jd|_d|_YnXdkrtd|_d||dS)NrWrrrBrArcFrdrgrercs g|]}|kr||fqSrrrarlrr -sz.InstanceState.__setstate__..)r$rfrrrhr)rrrrrrgetrrBrArcrdrgrirerr8rlistaddr`r$identity_token IndexErrorlenAssertionErrorrZ deserializerh)rrlinstrbrrnr __setstate__sR           zInstanceState.__setstate__cCsX||d}|dk r4|j|jjr4|j|j||j||jrT|j|ddS)zHRemove the given attribute and any callables associated with it.N)poprrZ collection_invalidate_collectionrdiscardre)rdict_r$oldrrr _resetAs   zInstanceState._resetcCsd|jkrt|j|_dSNre)r`r're)rfrom_rrr _copy_callablesLs zInstanceState._copy_callablescs4|jjr"fdd}nfdd}|S)Ncs<d|jkri|_|d}|dk r.||j<dSr)r`reryr{)rMr}rowr~fnrZr$rr _set_callableUs    zGInstanceState._instance_level_callable_processor.._set_callablecsd|jkri|_|j<dSr)r`re)rMr}r)rr$rr r_s )rZrz)clsrrr$rrrr "_instance_level_callable_processorPs   z0InstanceState._instance_level_callable_processorcsd|_|jr&|||jd|_d|_d|jkr>|jd=d|jkrP|jd=|jdd|j j D|j r|j |j D] }|j |=q~|j j D]}|}d|j_q|jr|jfdd|jD|j j D] }|=q|j j|ddS) NTFrBrAcSsg|] }|jqSrr>)r#rZrrr rovsz)InstanceState._expire..c3s"|]}|kr||fVqdSrrrar}rr r&sz(InstanceState._expire..)rdrcr|rclearrLr`rrirZ _loader_implsre intersectionZ_collection_impl_keysryZ _sa_adapterZ invalidatedr5Z _all_key_setrGexpire)rr}Z modified_setrbrzr$rrr _expirefs4        zInstanceState._expirec Cs|jdd}|j}|D]}|j|j}|jr`|rB|js||krBq|j||r`||kr`||=| |t }|j r|t k r| ||j r||j kr|t k r||j |<|j |d|r| |dq|jj||dS)NrB)r`rprerrZaccepts_scalar_loaderZ callable_rrrryr rzr{r5rrGr) rr}Zattribute_namesZ no_loaderr,rer$rZr~rrr _expire_attributess0      z InstanceState._expire_attributescsP|t@s tSjj}|fdd|D}j||jt S)z__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable). c3s |]}j|jjs|VqdSr)rrZZload_on_unexpirer#attrr%rr r&sz.InstanceState._load_expired..) r r rr unmodified differencerZexpired_attribute_loaderrr)rrMr\Ztoloadrr%r _load_expireds zInstanceState._load_expiredcCst|j|jS)z8Return the set of keys which have no uncommitted changes)rrrrr%rrr rszInstanceState.unmodifiedcCst||j|jS)z*Return self.unmodified.intersection(keys).)rrrrr)rkeysrrr unmodified_intersections z%InstanceState.unmodified_intersectioncCst|j|j|jSzReturn 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.unloadedcCs|jSr)rr%rrr unloaded_expirablesz InstanceState.unloaded_expirablecsjfddjDS)Nc3s |]}j|jjr|VqdSr)rrZrrr%rr r&sz5InstanceState._unloaded_non_object..)rrrr%rr%r _unloaded_non_objectsz"InstanceState._unloaded_non_objectcCsdSrrr%rrr rQszInstanceState._instance_dictc Csh|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 sdd|_ | }|rt |j}|j|nd}|}|j r4||_ |s4zt|j } Wntk rYnX| jdkr4| |dkrd|rdtd|j|jt|fdS)NzHCan't flag attribute '%s' modified; it's not present in the object stateTFzaCan't emit change event for attribute '%s' - parent object of type %s has been garbage collected.)Zsend_modified_eventsr$sa_excZInvalidRequestErrorrrr copyr5r3rLrcrQrE _modifiedrrrr4r8Z _transactionZ _autobeginorm_excZObjectDereferencedErrorrrZstate_class_str) rr}rpreviousrzZ is_userlandrRZ has_modifiedrwr9rrr _modified_eventsT        zInstanceState._modified_eventcCsb|D]}|j|dqd|_|jt|||jr^t|j||D] }|j|=qPdS)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)rryrdrdifference_updaterrre)rr}rr$rrr _commitBs  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)rr}rRrrr _commit_all_szInstanceState._commit_allcCsd|D]Z\}}|j}|jd|kr*|d=|j||rL|jrL|j|d|_|_d|_ qdS)z.Mass / highly inlined version of commit_all().rBFN) r`rrrrrcrr|rdrL)rZiter_rRrMr}rlrrr rqs      z InstanceState._commit_all_states)F)N)F)FF)N)N)M__name__ __module__ __qualname____doc__r3r$Zrunidr EMPTY_SETrfrrootrhZ insert_orderrLrcrdr.Z _load_pendingZ_orphaned_outside_of_sessionZ is_instancersr5rer!rZmemoized_propertyr(propertyr+r,r/r0r1r2Zpreload_moduler*r7r9r<r=r?r@rArBrCrDrF classmethodrNrOrPrrr'rYr[r]r_rmrxrrrrrrrrrrrrQrrrrrrrr r)s                       :  0       @ 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)rMr$)rrMr$rrr r!szAttributeState.__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. )rMr'rpr$r r%rrr loaded_valueszAttributeState.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. )rMrr$__get__rrr%rrr values zAttributeState.valuecCs|j|jtS)aiReturn 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.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 )rMr[r$r r%rrr historyszAttributeState.historycCs|j|jttAS)a%Return 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.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 )rMr[r$r rr%rrr load_historyszAttributeState.load_historyN) rrrrr!rrrrrrrrr r"s   r"c@s(eZdZdZddZddZddZdS) r^aA 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)rZ IdentitySet deleted_itemsZOrderedIdentitySet added_itemsr%rrr r!s zPendingCollection.__init__cCs(||jkr|j|n |j|dSr)rremoverrrrrrrr appends zPendingCollection.appendcCs(||jkr|j|n |j|dSr)rrrrrrrrr rs zPendingCollection.removeN)rrrrr!rrrrrr r^sr^)rrrrrrrrrr r r r r Z path_registryrrrrr4r:Z_self_inspectsZInspectionAttrInforr=r"r^rrrr s8               bb