U kf&@sUdZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lm Z dd lZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddlmZ"ddlm#Z#dd lm$Z$dd!l%m&Z&dd"l%m'Z'e rdd1lGd4d5d5e'ZBGd6d7d7e'eZCe#jDGd8d9d9ejEeeZFGd:d;d;ZGGdzDefines instrumentation of instances. This module is usually not directly visible to user applications, but defines a large part of the ORM's interactivity. ) annotations)Any)Callable)Dict)Generic)Iterable)Optional)Set)Tuple) TYPE_CHECKING)UnionN)base)exc) interfaces)_O)is_collection_impl) ATTR_WAS_SET)INIT_OK)LoaderCallableStatus) NEVER_SET)NO_VALUE)PASSIVE_NO_INITIALIZE)PASSIVE_NO_RESULT) PASSIVE_OFF)SQL_OK) PathRegistry) inspection)util)Literal)Protocol)_IdentityKeyType) _InstanceDict)_LoaderCallable) AttributeImpl)History) PassiveFlag)_AdaptedCollectionProtocol) IdentityMap) ClassManager) ORMOption)Mapper)Session)Row) async_session) AsyncSessionz)weakref.WeakValueDictionary[int, Session] _sessionsc@seZdZddddZdS)_InstanceDictProtoOptional[IdentityMap]returncCsdSNselfr7r7D/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/orm/state.py__call__Qz_InstanceDictProto.__call__N)__name__ __module__ __qualname__r;r7r7r7r:r2Psr2c@s$eZdZdZdddddddZd S) _InstallLoaderCallableProtoaused at result loading time to install a _LoaderCallable callable upon a specific InstanceState, which will be used to populate an attribute when that attribute is accessed. Concrete examples are per-instance deferred column loaders and relationship lazy loaders. InstanceState[_O]r#Row[Any]Nonestatedict_rowr5cCsdSr6r7)r9rErFrGr7r7r:r;^sz$_InstallLoaderCallableProto.__call__N)r=r>r?__doc__r;r7r7r7r:r@Ts r@c@s|eZdZUdZdZded<dZded<dZded <dZded <d Z d ed <e j Z ded<dZ ded<dZded<ded<ded<dZded<dZded<dZded<dZded<dZded<dZded<dZd ed!<dZd"ed#<d$ed%<esd&d'Zd(ed)<d*ed+<esejZd,dd-d.d/Zejd0d1d2d3Zedd1d4d5Z edd1d6d7Z!edd1d8d9Z"edd1d:d;Z#edd1dd?Z%ej&e'd@dd1dAdBZ(dCdDdEdFdGZ)edHd1dIdJZ*edKd1dLdMZ+edNd1dOdPZ,edQd1dRdSZ-edd1dTdUZ.ejdVd1dWdXZ/ejdYd1dZd[Z0ejd\d1d]d^Z1ejd_d1d`daZ2edd1dbdcZ3e4ddddeddDdfdgdhZ5ddHdDdidjdkZ6dDd1dldmZ7ddDdndodpZ8edqd1drdsZ9dtdtdDdudvdwZ:dCdxdydzd{d|Z;dCd}dEd~dZddDdddZ?dqdCdDdddZ@ddDdddZAe4dddtddddZBdqddDdddZCddqdddDdddZDddxddddZEed(d1ddZFdd(dddZGed(d1ddZHeeIddd(d1ddZJed(d1ddZKddqddtdddDdddZLdqddDdddZMddqddDdddZNe4ddddDdddZOdS) InstanceStatea Tracks 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) >>> insp.attrs.nickname.history History(added=['new nickname'], unchanged=(), deleted=['nickname']) .. seealso:: :ref:`orm_mapper_inspection_instancestate` )__dict__ __weakref__class_managerobjcommitted_stateexpired_attributeszClassManager[_O]rMNz Optional[int] session_idzOptional[_IdentityKeyType[_O]]keyrunidr7zTuple[ORMOption, ...] load_optionsr load_path insert_orderzOptional[object] _strong_objzweakref.ref[_O]rNzDict[str, Any]rOFboolmodifiedexpired_deleted _load_pending_orphaned_outside_of_sessionT is_instanceobjectidentity_tokenzOptional[Dict[str, Any]]_last_known_valuesr2_instance_dictcCsdS)z+default 'weak reference' for _instance_dictNr7r8r7r7r:rbszInstanceState._instance_dictzSet[str]rPz:Dict[str, Callable[[InstanceState[_O], PassiveFlag], Any]] callablesr)rNrMcCs0|j|_||_t||j|_i|_t|_ dSr6) __class__rLrMweakrefref_cleanuprNrOsetrP)r9rNrMr7r7r:__init__s zInstanceState.__init__z'util.ReadOnlyProperties[AttributeState]r4cstfddjDS)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. csi|]}|t|qSr7)AttributeState).0rRr8r7r: sz'InstanceState.attrs..)rZReadOnlyPropertiesrMr8r7r8r:attrss zInstanceState.attrscCs|jdko|j S)z}Return ``True`` if the object is :term:`transient`. .. seealso:: :ref:`session_object_states` NrR _attachedr8r7r7r: transients zInstanceState.transientcCs|jdko|jS)z{Return ``True`` if the object is :term:`pending`. .. seealso:: :ref:`session_object_states` Nrnr8r7r7r: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` NrRror[r8r7r7r:deletedszInstanceState.deletedcCs|jS)aNReturn 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. .. seealso:: :attr:`.InstanceState.deleted` - refers to the "deleted" state :func:`.orm.util.was_deleted` - standalone function :ref:`session_object_states` )r[r8r7r7r: was_deletedszInstanceState.was_deletedcCs|jdk o|jo|j S)aReturn ``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`. .. seealso:: :ref:`session_object_states` Nrrr8r7r7r: persistent)s zInstanceState.persistentcCs|jdk o|j S)z|Return ``True`` if the object is :term:`detached`. .. seealso:: :ref:`session_object_states` Nrnr8r7r7r:detached8s zInstanceState.detachedzsqlalchemy.orm.sessioncCs|jdk o|jtjjjkSr6)rQrZ preloadedZ orm_sessionr1r8r7r7r:roCs zInstanceState._attachedstrrC)rRr5cCs,|j}|dkri|_}||kr(t||<dS)z|Track the last known value of a particular key after expiration operations. .. versionadded:: 1.3 N)rar)r9rRlkvr7r7r:_track_last_known_valueKs  z%InstanceState._track_last_known_valuezOptional[Session]cCs,|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)rQr1KeyErrorr8r7r7r:sessionYs  zInstanceState.sessionzOptional[AsyncSession]cCs*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_providerr{)r9sessr7r7r:r/qs zInstanceState.async_sessionz Optional[_O]cCs|S)zReturn the mapped object represented by this :class:`.InstanceState`. Returns None if the object has been garbage collected )rNr8r7r7r:r_szInstanceState.objectzOptional[Tuple[Any, ...]]cCs|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. Nr rRr8r7r7r:identitys 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~r8r7r7r: identity_keys zInstanceState.identity_keyz4Dict[int, Union[Literal[False], InstanceState[Any]]]cCsiSr6r7r8r7r7r:parentsszInstanceState.parentszDict[str, PendingCollection]cCsiSr6r7r8r7r7r:_pending_mutationssz InstanceState._pending_mutationsz%Dict[str, _AdaptedCollectionProtocol]cCsiSr6r7r8r7r7r:_empty_collectionssz InstanceState._empty_collectionsz Mapper[_O]cCs|jjS)zszInstanceState.get_historyr%cCs |j|jSr6)rMrr9rRr7r7r:get_implAszInstanceState.get_implPendingCollectioncCs ||jkrt|j|<|j|Sr6)rrrr7r7r:_get_pending_mutationDs  z#InstanceState._get_pending_mutationcsZjjjd}|fdddDjrDj|d<j||d<|S)N)rrLrOrPc3s&|]}|jkr|j|fVqdSr6)rJrkkr8r7r: Ps z-InstanceState.__getstate__..) rrYrZrcrRrrTrLrPinforUrM) rNrLrOrPupdaterU serializerMZ _serialize)r9 state_dictr7r8r: __getstate__IszInstanceState.__getstate__)rr5cs2d}|dk r*t||j|_|j|_ndd|_d|_di|_di|_di|_ dd |_ d d |_ d kr|j d d krd |_d |_nd krΈd |_nt|_|j fdddD|jr|jd|_dkrtd|_d||dS)NrcSsdSr6r7r7r7r7r:mr<z,InstanceState.__setstate__..rLrOrrrYFrZrrcrPcs g|]}|kr||fqSr7r7rrr7r: sz.InstanceState.__setstate__..)rRrTrrUrM)rerfrgrNrdrLgetrOrrrYrZrrrcrPrhrJrRr`rZ deserializerU)r9rinstr7rr: __setstate__gs:         zInstanceState.__setstate__)rFrRr5cCsV||d}|j|j}|dk r2t|r2|||j||jrR|j|ddS)zHRemove the given attribute and any callables associated with it.N)poprMrr_invalidate_collectionrPdiscardrc)r9rFrRoldZ manager_implr7r7r:_resets    zInstanceState._resetInstanceState[Any])from_r5cCsd|jkrt|j|_dSNrc)rJrrc)r9rr7r7r:_copy_callabless zInstanceState._copy_callablesr$z_InstallLoaderCallableProto[_O])rMfnrRr5csR|j}t|r4|dddddfdd }ndddddfdd }|S) NrAr#rBrCrDcs<d|jkri|_|d}|dk r.||j<dSr)rJrcrr)rErFrGrZ fixed_implrrRr7r: _set_callables    zGInstanceState._instance_level_callable_processor.._set_callablecsd|jkri|_|j<dSr)rJrc)rErFrG)rrRr7r:rs )rr)clsrMrrRrrr7rr:"_instance_level_callable_processors   z0InstanceState._instance_level_callable_processorzSet[InstanceState[Any]])rF modified_setr5csd|_|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) NTFrrcSsg|] }|jqSr7r~)rkrr7r7r:rsz)InstanceState._expire..csi|]}|kr||qSr7r7rrFr7r:rlsz)InstanceState._expire..)rZrYrrOclearrWrJrPrrMZ _loader_implsrc intersectionZ_collection_impl_keysrZ _sa_adapterZ invalidatedraZ _all_key_setrexpire)r9rFrr collectionrRr7rr:_expires4        zInstanceState._expirez Iterable[str])rFattribute_names no_loaderr5c Cs|jdd}|j}|D]}|j|j}|jr`|rB|js||krBq|j||r`||kr`||=| |t }t |r|t k r| ||j } | dk r|| kr|t k r|| |<|j |d|r| |dq|jj||dS)Nr)rJrrcrMraccepts_scalar_loaderZ callable_rPaddrrrrrarOrr) r9rFrrrqrcrRrrrxr7r7r:_expire_attributess(     z InstanceState._expire_attributesrAr)rErr5csP|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|VqdSr6)rMrZload_on_unexpirerkattrr8r7r:rsz.InstanceState._load_expired..) rrrPr unmodified differencerMZexpired_attribute_loaderrr)r9rErZtoloadr7r8r: _load_expireds  zInstanceState._load_expiredcCst|j|jS)z8Return the set of keys which have no uncommitted changes)rhrMrrOr8r7r7r:r-szInstanceState.unmodified)keysr5cCst||j|jS)z*Return self.unmodified.intersection(keys).)rhrrMrrO)r9rr7r7r:unmodified_intersection3s z%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. )rhrMrrOrr8r7r7r:unloaded<s zInstanceState.unloadedz2.0zsThe :attr:`.InstanceState.unloaded_expirable` attribute is deprecated. Please use :attr:`.InstanceState.unloaded`.cCs|jS)zSynonymous with :attr:`.InstanceState.unloaded`. This attribute was added as an implementation-specific detail at some point and should be considered to be private. )rr8r7r7r:unloaded_expirableJs z InstanceState.unloaded_expirablecsjfddjDS)Nc3s |]}j|jjr|VqdSr6)rMrrrr8r7r:r[sz5InstanceState._unloaded_non_object..)rrrMr8r7r8r:_unloaded_non_objectYsz"InstanceState._unloaded_non_objectzOptional[AttributeImpl])rFrpreviousr is_userlandr5c Cs|r|jsdS|r,|j|kr,td|j|j|jks<|r|rtrPt|sPt|tkrl|j|krl||j}|dt tfkr| |}||j|j<|j }|dk r|j|krt ||j<|j r|j dks|js~d|_|}|rt|j}|j|nd}|} |j rN| |_ |sNzt|j } Wntk r8YnX| jdkrN| | dkr~|r~td|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_eventsrRsa_excZInvalidRequestErrorrOr rAssertionErrorrrcopyrarQrWrYrbrX _modifiedrrNr1rzZ _transactionZ _autobegin_torm_excZObjectDereferencedErrorrMrZstate_class_str) r9rFrrrrrxrZ has_modifiedrr{r7r7r:_modified_eventasZ        zInstanceState._modified_event)rFrr5cCsb|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)rOrrZrPdifference_updaterhrrc)r9rFrrRr7r7r:_commits  zInstanceState._commitr3)rFrr5cCs|||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)r9rFrr7r7r: _commit_allszInstanceState._commit_allz2Iterable[Tuple[InstanceState[Any], _InstanceDict]])iter_rr5cCsd|D]Z\}}|j}|jd|kr*|d=|j||rL|jrL|j|d|_|_d|_ qdS)z.Mass / highly inlined version of commit_all().rFN) rJrOrrPrrYrrrZrW)r9rrrErFrr7r7r:rs      z InstanceState._commit_all_states)F)N)F)FF)N)N)Pr=r>r?rH __slots____annotations__rQrRrSrTrrootrUrVrWrYrZr[r\r]r^r`rar rbr EMPTY_DICTrcriZmemoized_propertyrmpropertyrprqrsrtrurvZnon_memoized_propertyZpreload_moduleroryr{r/r_rrrrrrr classmethodrrrrgrrrrrrrrrrrrrrrr deprecatedrrrrrrr7r7r7r:rIcs                        % ) 6!    HrIc@szeZdZUdZdZded<ded<dddddZed d d d Zed d d dZ edd ddZ dd ddZ dS)rjaProvide 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 rErRrrErwrRcCs||_||_dSr6r)r9rErRr7r7r:riszAttributeState.__init__rr4cCs|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. )rErrrRrr8r7r7r: loaded_value szAttributeState.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. )rErMrR__get__rNrLr8r7r7r:values zAttributeState.valuer&cCs|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 )rErrRrr8r7r7r:history"szAttributeState.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.Query` is invoked. For options on how to control this, see :ref:`session_flushing`. .. seealso:: :attr:`.AttributeState.history` :func:`.attributes.get_history` - underlying function )rErrRrrr8r7r7r: load_history>szAttributeState.load_historyN) r=r>r?rHrrrirrrrrr7r7r7r:rjs   rjc@sdeZdZUdZdZded<ded<ddd d Zd d d d dZdddddZdddddZ dS)raA 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. ) deleted_items added_itemszutil.IdentitySetrzutil.OrderedIdentitySetrrCr4cCst|_t|_dSr6)rZ IdentitySetrZOrderedIdentitySetrr8r7r7r:rifs zPendingCollection.__init__r&)rr5cCs||j|jSr6)_mergerr)r9rr7r7r:merge_with_historyjsz$PendingCollection.merge_with_historyr)rr5cCs(||jkr|j|n |j|dSr6)rremoverrr9rr7r7r:appendms zPendingCollection.appendcCs(||jkr|j|n |j|dSr6)rrrrrr7r7r:rss zPendingCollection.removeN) r=r>r?rHrrrirrrr7r7r7r:rXs r)IrH __future__rtypingrrrrrrr r r r rerrrrZ_typingrrrrrrrrrrrZ path_registryrrrrZ util.typingr r!r"r#r$ attributesr%r&r' collectionsr(rr)Zinstrumentationr*r+rr,r{r-Zenginer.Zext.asyncio.sessionr/r|r0rr1r2r@Z_self_inspectsZInspectionAttrInforIrjrr7r7r7r:s                                               e