L i&UdZddlmZddlmZddlmZddlmZddlmZddlmZddlm 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 rZdd#lm(Z(dd$lm)Z)dd%lm*Z*dd&l+m,Z,dd'l+m-Z-dd(lm.Z.dd)l/m0Z0dd*l1m2Z2dd+l3m4Z4dd,lm5Z5dd-l6m7Z7dd.l8m9Z9dd/l:m;Z;dd0ldd1lGd4d5e'ZBGd6d7e'eZCe#jGd8d9ejeeZFGd:d;ZGGd<d=ZHy )>zDefines 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] _sessionsceZdZddZy)_InstanceDictProtocyNselfs Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py__call__z_InstanceDictProto.__call__QN)returnOptional[IdentityMap])__name__ __module__ __qualname__r;r7r=r:r4r4Ps4r=r4c(eZdZdZ ddZy)_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. cyr6r7)r9statedict_rows r:r;z$_InstallLoaderCallableProto.__call__^sr=NrFInstanceState[_O]rGr$rHzRow[Any]r>None)r@rArB__doc__r;r7r=r:rDrDTs,&/<CK r=rDc0eZdZUdZdZded<dZded<dZded <dZded <d Z d ed <e jZ ded<dZ ded<dZded<ded<ded<dZded< dZded< dZded<dZded<dZded<dZded<dZd ed!<dZd"ed#<d$ed%< esd&Zd'ed(< d)ed*< es ej4Zd\d+Zej:d]d,Zed^d-Z ed^d.Z!ed^d/Z"ed^d0Z#ed^d1Z$ed^d2Z%ejLejNd3d^d4Z(d_d5Z)ed`d6Z*edad7Z+edbd8Z,edcd9Z-eddd:Z.ej:ded;Z/ej:dfd<Z0ej:dgd=Z1ej:dhd>Z2ed^d?Z3e4 di djd@Z5dkdldAZ6dmdBZ7dndCZ8edodDZ9dpdEZ:dqdFZ;drdGZdudJZ?dvdKZ@dwdLZAe4 dxdMZB dydNZC di dzdOZD d{dPZEed|dQZFd}dRZGed|dSZHeejdTdUd|dVZJed|dWZK d~ ddXZLddYZM dk ddZZNe4 dk dd[ZOy) 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_attributesClassManager[_O]rRNz Optional[int] session_idOptional[_IdentityKeyType[_O]]keyrunidr7zTuple[ORMOption, ...] load_optionsr load_path insert_orderzOptional[object] _strong_objweakref.ref[_O]rSDict[str, Any]rTFboolmodifiedexpired_deleted _load_pending_orphaned_outside_of_sessionT is_instanceobjectidentity_tokenzOptional[Dict[str, Any]]_last_known_valuesr4_instance_dictcy)z+default 'weak reference' for _instance_dictNr7r8s r:rkzInstanceState._instance_dictsr=Set[str]rUz:Dict[str, Callable[[InstanceState[_O], PassiveFlag], Any]] callablesc|j|_||_tj||j |_i|_t|_ yr6) __class__rQrRweakrefref_cleanuprSrTsetrU)r9rSrRs r:__init__zInstanceState.__init__s<mm  ;;sDMM2!"%%r=c |tj|jDcic]}|t||c}Scc}w)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. )r ReadOnlyPropertiesrRAttributeStater9rYs r:attrszInstanceState.attrss8&&7;|| DS.s+ + D  Ds9c<|jduxr |j S)z}Return ``True`` if the object is :term:`transient`. .. seealso:: :ref:`session_object_states` NrY _attachedr8s r: transientzInstanceState.transientsxx46$66r=c:|jduxr |jS)z{Return ``True`` if the object is :term:`pending`. .. seealso:: :ref:`session_object_states` Nr|r8s r:pendingzInstanceState.pendingsxx42DNN2r=cV|jduxr|jxr |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` NrYr}rdr8s r:deletedzInstanceState.deleteds%8xxt#HH4==Hr=c|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` )rdr8s r: was_deletedzInstanceState.was_deleteds&}}r=cX|jduxr|jxr |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` Nrr8s r: persistentzInstanceState.persistent)s(xxt#LLt}};LLr=c<|jduxr |j S)z|Return ``True`` if the object is :term:`detached`. .. seealso:: :ref:`session_object_states` Nr|r8s r:detachedzInstanceState.detached8sxxt#:DNN(::r=zsqlalchemy.orm.sessionc|jduxr0|jtjjjvSr6)rWr preloaded orm_sessionr2r8s r:r}zInstanceState._attachedCs7 OO4 ' H4>>#=#=#G#GG r=cN|j}| ix|_}||vr t||<yy)z|Track the last known value of a particular key after expiration operations. .. versionadded:: 1.3 N)rjr)r9rYlkvs r:_track_last_known_valuez%InstanceState._track_last_known_valueKs6%% ;,. .D #c c>CH r=cb|jr t|jSy#t$rYywxYw)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)rWr2KeyErrorr8s r:sessionzInstanceState.sessionYs;" ??  11  s " ..cDty|j}| t|Sy)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)r9sesss r:r0zInstanceState.async_sessionqs*&  "||  "4( (r=c"|jS)zReturn the mapped object represented by this :class:`.InstanceState`. Returns None if the object has been garbage collected )rSr8s r:rhzInstanceState.objectsxxzr=c:|jy|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.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. NrrYr8s r:identityzInstanceState.identitys 88 88A; r=c|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. rr8s r: identity_keyzInstanceState.identity_keys xxr=ciSr6r7r8s r:parentszInstanceState.parents r=ciSr6r7r8s r:_pending_mutationsz InstanceState._pending_mutationsrr=ciSr6r7r8s r:_empty_collectionsz InstanceState._empty_collectionsrr=c.|jjS)zs*||C %%11$ 7KKr=c4|j|jSr6)rRrrys r:get_implzInstanceState.get_implAs||C %%%r=cj||jvrt|j|<|j|Sr6)rPendingCollectionrys r:_get_pending_mutationz#InstanceState._get_pending_mutationDs4 d-- -+<+>D # #C (&&s++r=c2jjjjd}|j fddDj rj j |d<jj||d<|S)N)rrQrTrUc3\K|]#}|jvr|j|f%ywr6)rO).0kr9s r: z-InstanceState.__getstate__..Ps5 DMM! a ! s),) rrbrcrnrYrr[rQrUinfor\rR) rSrQrTrUupdater\ serializerR _serialize)r9 state_dicts` r: __getstate__zInstanceState.__getstate__Is kk#33"&"9"9 &     >>&*nn&>&>&@J{ # $ 7 7j I 9r=cF|d}|7tj||j|_|j|_nd|_|d|_|j di|_|j di|_|j di|_ |j dd|_ |j d d|_ d |vr|jj|d d |vr|d |_|d |_nd |vr |d |_nt!|_|j"jd Dcgc] }||vr|||fc}|j$r|j$d|_d|vrt)j*|d|_|d|||ycc}w)Nrcyr6r7r7r=r:z,InstanceState.__setstate__..mr<r=rQrTrrrbFrcrrnrU)rYr[rr\rR)rqrrrsrSrprQgetrTrrrbrcrrrnrUrtrOrYrir deserializer\)r9rinstrs r: __setstate__zInstanceState.__setstate__gs*%  {{47DH..DK#DH$X.DK)~~.?D",..1Er"J!~~i4 "z59 !~~i7 Z  II  Z/ 0 * $' 4DN&01E&FD ##z1*45I*J'*-%' 1  ?JqM"   88"&((1+D  * $)55j6MNDN 9dD*5 s6Fc|j|d}|j|j}|t|r|j ||j j ||jr|jj|dyy)zHRemove the given attribute and any callables associated with it.N)poprRrr_invalidate_collectionrUdiscardrn)r9rGrYold manager_impls r:_resetzInstanceState._resetswiiT"||C(-- ?1,?  / / 4 '', >> NN  sD ) r=cVd|jvrt|j|_yyNrn)rOrrn)r9from_s r:_copy_callableszInstanceState._copy_callabless# %.. (!%//2DN )r=c|j}t|r| dfd }|S dfd }|S)Ncd|jvri|_|jd}|j||j<yr)rOrnrr)rFrGrHr fixed_implfnrYs r: _set_callablezGInstanceState._instance_level_callable_processor.._set_callablesIenn4&(EOiiT*?55c:')$r=cNd|jvri|_|j<yr)rOrn)rFrGrHrrYs r:rzGInstanceState._instance_level_callable_processor.._set_callables&enn4&(EO')$r=rI)rr)clsrRrrYrrrs `` @r:"_instance_level_callable_processorz0InstanceState._instance_level_callable_processors{s|   d #J *( *1> *EM * *& *( *1> *EM * *r=cd|_|jr2|j||jj d|_d|_d|j vr |j d=d|j vr |j d=|jj|jjDcgc]}|jc}|jr7|jj|jD]}|j|=|jjj|D]$}|j|}d|j _&|j$r<|j$j|j$Dcic] }||vs|||c}|jj&j|D]}||=|jj(j+|dycc}wcc}w)NTFrr)rcrbrrTclearr^rOrUrrR _loader_implsrYrn intersection_collection_impl_keysr _sa_adapter invalidatedrj _all_key_setrexpire)r9rG modified_setrr collectionrYs r:_expirezInstanceState._expires ==   &  & & (!DM 4== 0 23  % i( &&"&,,"<"< =$TXX =  >>,,99$..I &NN1% &33@@G 6A1J15J " " . 6  " "  # # * *&*&=&=LeE!HL <<,,99%@ Cc   $$T40= >0Ms0G5 G:G:cz|jjdd}|j}|D]}|j|j}|j r7|r|j s||vr;|jj||r||vr||=|j|t}t|r|tur|j||j} | || vr |tur|| |<|jj|d|s|j|d|jjj!||y)Nr)rOrrnrRraccepts_scalar_loader callable_rUaddrrrrrjrTrr) r9rGattribute_names no_loaderrrnrYrrrs r:_expire_attributesz InstanceState._expire_attributess --##$8$?NN " 'C<<$))D))$..C94D''++C0 !1!#))C*C!$'Cx,?++C0))C3#:#X2EC  $ $S$ / C&' '* $$T?;r=c|tzstSjjj}|j fd|D}j j||jjtS)z__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable). c3hK|])}j|jjs|+ywr6)rRrload_on_unexpirerattrr9s r:rz.InstanceState._load_expired..s1# <<%**;; # /2) rrrUr unmodified differencerRexpired_attribute_loaderrr)r9rFrtoloads` r: _load_expiredzInstanceState._load_expireds|$ $((55dooF""# #   --dFGD %%'r=c^t|jj|jS)z8Return the set of keys which have no uncommitted changes)rtrRr rTr8s r:r zInstanceState.unmodified-s$4<< ++D,@,@AAr=c|t|j|jj|jS)z*Return self.unmodified.intersection(keys).)rtrrRr rT)r9keyss r:unmodified_intersectionz%InstanceState.unmodified_intersection3s. I \$,, ' Z,, - r=ct|jj|jj|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. )rtrRr rTrr8s r:unloadedzInstanceState.unloaded<s3   Z,, - Z " r=z2.0zsThe :attr:`.InstanceState.unloaded_expirable` attribute is deprecated. Please use :attr:`.InstanceState.unloaded`.c|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. )rr8s r:unloaded_expirablez InstanceState.unloaded_expirableJs}}r=c`jjfdjDS)Nc3hK|])}j|jjr|+ywr6)rRrrrs r:rz5InstanceState._unloaded_non_object..[s1* ||D!&&<< * r )rrrRr8s`r:_unloaded_non_objectz"InstanceState._unloaded_non_objectYs+}}))*  *   r=c@|r|jsy|r0|j|vr"tjd|jz|j|jvs|rs|rXt r t |sJ|tur|j|vr||j}|dttfvr|j|}||j|j<|j}|!|j|vrt||j<|jr |j |jsd|_ |j}|r1t|j }|j j#|nd}|j%} |jr:| |_ |s1 t&|j} | j(| j+ | I|rFt/j0d|j2|jdt5j6|dyyy#t,$rYXwxYw)NzHCan't flag attribute '%s' modified; it's not present in the object stateTFz'Can't emit change event for attribute 'z' - parent object of type z has been garbage collected.)send_modified_eventsrYsa_excInvalidRequestErrorrTr rrrcopyrjrWr^rbrkra _modifiedrrSr2 _transaction _autobegin_trorm_excObjectDereferencedErrorrRrstate_class_str) r9rGr previousr is_userlandrr has_modifiedrrs r:_modified_eventzInstanceState._modified_eventas ,,txxu400')-2xxt333{$1$7779,88u,',TXXHh 'BB#'99X#619$$TXX.))C488s? (DHH  OO 0 0 8 DM //1M#M$;$;< ''++D1$ 88:D#' $3"+DOO"<#//7#002|55||DHH-t/C/CD/IK!%|=BO0$sH HHcb|D]}|jj|d d|_|jj t |j ||jrFt |jj |j |D]}|j|=yy)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)rTrrcrUdifference_updatertrrn)r9rGrrYs r:_commitzInstanceState._commits 0C  $ $S$ / 0  11 I " "5 )  >>DNN#006CCEJ (NN3' ( r=c.|j||fg|y)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)r9rGrs r: _commit_allzInstanceState._commit_alls$ $?r=c$|D]\}}|j}|jjd|vr|d=|jj ||r'|j r|j j|dx|_|_d|_ y)z.Mass / highly inlined version of commit_all().rFN) rOrTrrUr+rbr rrcr^)r9iter_rrFrGrs r:r.z InstanceState._commit_all_statess" %LE5J  ! ! ' ' )#z134  $ $ 6 6u =''//6-2 2ENU] $E  %r=)rSrrRrV)r>z'util.ReadOnlyProperties[AttributeState])r>ra)rYstrr>rK)r>Optional[Session])r>zOptional[AsyncSession])r>z Optional[_O])r>zOptional[Tuple[Any, ...]])r>rX)r>z4Dict[int, Union[Literal[False], InstanceState[Any]]])r>zDict[str, PendingCollection])r>z%Dict[str, _AdaptedCollectionProtocol])r>z Mapper[_O])F)rzIterable[InstanceState[_O]]rr.rrar>rKr6)rr3r>rKr>rK)rrr_r>rK)r>r$)rrrrr>rK)rYr2rr(r>r')rYr2r>r&)rYr2r>r)r>r`)rr`r>rK)rGr$rYr2r>rK)rInstanceState[Any]r>rK)rRrVrr%rYrr>z_InstallLoaderCallableProto[_O])rGr$rzSet[InstanceState[Any]]r>rK)rGr$r Iterable[str]rrar>rK)rFrJrr(r>r)r>rm)rr6r>rm)FF) rGr$r zOptional[AttributeImpl]r&rrrar'rar>rK)rGr$rr6r>rK)rGr$rr?r>rK)r1z2Iterable[Tuple[InstanceState[Any], _InstanceDict]]rr?r>rK)Pr@rArBrL __slots____annotations__rWrYrZr[rrootr\r]r^rbrcrdrerfrgrirjr rkr EMPTY_DICTrnrumemoized_propertyrzpropertyr~rrrrrnon_memoized_propertypreload_moduler}rrr0rhrrrrrrr classmethodrrrrsrrrrrrrrrrrrrr rr deprecatedrrr)r,r/r.r7r=r:rNrNcs6I $J $*.C '.E=*,L',*//I|/"&L-&$(K!( ##Hd0GT HdM4). $.K!NF!3707&&  ! JI  OO (     7733II:( M M;; T12 3   .6&      ## # #%+#%#% #%  #%#%J6 2:$ BL&, <'6R *3&,;BE (801"012I01 01l <<'< <  s$.zz%%dhh g0EFFr=N)rFr5rYr2)r>r)r>r') r@rArBrLr7r8rur<rErHrJrLr7r=r:rxrxsb !I  H77    GG6Gr=rxcJeZdZUdZdZded<ded<d dZd dZdd Zdd Z y )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.IdentitySetrNzutil.OrderedIdentitySetrOchtj|_tj|_yr6)r IdentitySetrNOrderedIdentitySetrOr8s r:ruzPendingCollection.__init__fs$!--/224r=cN|j|j|jSr6)_mergerOrN)r9rJs r:merge_with_historyz$PendingCollection.merge_with_historyjs~~d..0B0BCCr=c||jvr|jj|y|jj|yr6)rNremoverOrr9rHs r:appendzPendingCollection.appendms8 D&& &    % %e ,     'r=c||jvr|jj|y|jj|yr6)rOrWrNrrXs r:rWzPendingCollection.removess8 D$$ $    # #E *    " "5 )r=Nr4)rJr'r>r')rHrr>rK) r@rArBrLr7r8rurUrYrWr7r=r:rrXs/1I##((5D( *r=r)IrL __future__rtypingrrrrrr r r r r rqrrr#r_typingrrrrrrrrrrr path_registryrrrr util.typingr!r"r#r$r% attributesr&r'r( collectionsr)rr*instrumentationr+r,rr-rr.enginer/ext.asyncio.sessionr0rr1r8r2r4rD_self_inspectsInspectionAttrInforNrxrr7r=r:rhs# '&'#'!")&()#!7%-% F288IO55 (2,  L%J1172;L%L%^bGbGJ**r=