L i_ZdZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lm Z dd lmZddlmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddl"m#Z#dd l"m$Z$erZ?ejxZ@ZAejxZBZC d= d>d9ZDd:ZEd;ZFd<ZGy)?aDefines SQLAlchemy's system of class instrumentation. This module is usually not directly visible to user applications, but defines a large part of the ORM's interactivity. instrumentation.py deals with registration of end-user classes for state tracking. It interacts closely with state.py and attributes.py which establish per-instance and per-class-attribute instrumentation, respectively. The class instrumentation system can be customized on a per-class or global basis using the :mod:`sqlalchemy.ext.instrumentation` module, which provides the means to build and specify alternate instrumentation forms. .. versionchanged: 0.8 The instrumentation extension system was moved out of the ORM and into the external :mod:`sqlalchemy.ext.instrumentation` package. When that package is imported, it installs itself within sqlalchemy.orm so that its more comprehensive resolution mechanics take effect. ) annotations)Any)Callable)cast) Collection)Dict)Generic)Iterable)List)Optional)Set)Tuple)Type) TYPE_CHECKING)TypeVar)UnionN)base) collections)exc) interfaces)state)_O)_is_collection_attribute_impl)util) EventTarget) HasMemoized)Literal)Protocol) _RegistryType) AttributeImpl)QueryableAttribute)_AdaptedCollectionProtocol)_CollectionFactoryType) _MapperConfig)InstanceEvents)Mapper) InstanceState) dispatcher_T)boundDEL_ATTRc$eZdZ ddZy)_ExpiredAttributeLoaderProtocyN)selfrtoloadpassives d/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py__call__z%_ExpiredAttributeLoaderProto.__call__Ss N)rstate.InstanceState[Any]r4zSet[str]r5zbase.PassiveFlagreturnNone__name__ __module__ __qualname__r7r2r8r6r/r/Rs-'"   r8r/ceZdZddZy)_ManagerFactorycyr1r2r3class_s r6r7z_ManagerFactory.__call__\r8NrDType[_O]r:ClassManager[_O]r<r2r8r6rArA[sAr8rAcreZdZUdZded<ej ZejZ e e je Z ded< ded<dZded <d ed <dZd ed <ded<esdZded<ded<ee j&dddZej*e j&dddZdZ dE dFdZdGdZdHdZdIdZedJdZej:dZej:d Zej:d!Z ej:d"Z!e jDdKd#Z#dLd$Z$dLd%Z%dMd&Z&dNd'Z'd(Z(e jDdOd)Z)d*Z*e jVd+Z,e jVd,Z-e jVd-Z. dP dQd.Z/d/Z0d0Z1dPd1Z2dGd2Z3 dRd3Z4dSd4Z5dTd5Z6dSd6Z7 dUd7Z8 dVd8Z9dPdWd9Z:dXd:Z;edYd;Zd\d>Z? d]d?Z@ d^d@ZAd_dAZB dP d`dBZCdJdCZDdadDZEy)b ClassManagerz,Tracks state information at the class level.zdispatcher[ClassManager[_O]]dispatchr/expired_attribute_loaderOptional[Callable[..., None]] init_methodN original_initzOptional[_ManagerFactory]factoryz$Optional[weakref.ref[_MapperConfig]]declarative_scanr!registryrGrDzList[ClassManager[Any]]_basesz1.4zWThe ClassManager.deferred_scalar_loader attribute is now named expired_attribute_loader)messagec|jSr1rLr3s r6deferred_scalar_loaderz#ClassManager.deferred_scalar_loaders,,,r8c||_yr1rV)r3objs r6rXz#ClassManager.deferred_scalar_loaders ),%r8c ||_i|_d|_i|_i|_d|_d|_d|_td|jjDcgc]}t|tr t|c}Dcgc]}||c}|_ |jD]}|j|td|jj j#|||j$D]5}t|}||jj'|j7|j)d|j*vrt-j.d|zyycc}wcc}w)NFz!List[Optional[ClassManager[Any]]]r'__del__z__del__() method on class %s will cause unreachable cycles and memory leaks, as SQLAlchemy instrumentation often creates reference cycles. Please remove this method.)rDinfonew_init local_attrs originals _finalizedrPrNr __bases__ isinstancetypeopt_manager_of_classrSupdaterK_events_new_classmanager_instance__mro___updatemanage__dict__rwarn)r3rDrmgrbase_baseclss r6__init__zClassManager.__init__s\    3!% 5 5!$-).      [[ E KK   dmm33 $ $VT 2~~ 4G&w/C %%cll3 4  ' II@CII  (/  s "E#  E(c|r||_|r|j||rtj||_|r||_|r|j r Jd|z||_|j sY|j2|jjtjur |jn|jj|_ |r|j s|jyyy)Nz>class is already instrumented, init_method %s can't be applied) mapper _add_managerweakrefrefrQrLrarNrDrqobjectrO _finalize)r3finalizersrRrQrLrNs r6 _update_statezClassManager._update_states  DK   ! !$ ' $+KK0@$AD ! #,DD )  24?@ & +D ##/KK((FOO;  [[))   DOO NN ,8r8c|jryd|_|jtjj |j yNT)ra_instrument_init_instrumentation_factoryrKclass_instrumentrDrWs r6rxzClassManager._finalizes7 ??   ))::4;;Gr8ct|Sr1)idrWs r6__hash__zClassManager.__hash__s $xr8c ||uSr1r2)r3others r6__eq__zClassManager.__eq__s }r8cd|jvS)Nrs)rlrWs r6 is_mappedzClassManager.is_mappeds4==((r8ct|Sr1) frozensetrWs r6 _all_key_setzClassManager._all_key_sets r8ct|jDcgc]%}|jjs|j'c}Scc}wr1)rvaluesimpl collectionkeyr3attrs r6_collection_impl_keysz"ClassManager._collection_impl_keyss6"&++- H$4993G3GTXX H  Hs A A ct|jDcgc]$}|jjr |j&c}Scc}wr1)rrraccepts_scalar_loaderrs r6_scalar_loader_implsz!ClassManager._scalar_loader_implssC!KKM 9922     s)Acnt|jDcgc]}|jc}Scc}wr1)rrrrs r6 _loader_implszClassManager._loader_implss% >$))>??>s2c@tj|jr1)rUnmappedClassErrorrDrWs r6rszClassManager.mappers$$T[[11r8c#NKi}|jjddD]}|jd}|jD]c}|j||||jvr$||j|}t |t j sQ|js^||feyw)areturn an iterator of all classbound attributes that are implement :class:`.InspectionAttr`. This includes :class:`.QueryableAttribute` as well as extension types such as :class:`.hybrid_property` and :class:`.AssociationProxy`. rrN)rDrirl setdefaultrcrInspectionAttr is_attribute)r3excludefoundsuperclsinheritsrvals r6_all_sqla_attributesz!ClassManager._all_sqla_attributess!# ++Ab1 #H''*H(( #  h/(+++Cj))#.sJ$=$=>((s(N # #sB B% B% B%cz|jjD]!}||jvs|j|cS|S)z5return an attribute on the class without tripping it.)rDrirl)r3rdefaultrs r6_get_class_attr_mroz ClassManager._get_class_attr_mro8sC ++ Hh'''((-- Nr8c0||vxr||jduS)z\Return True if the given attribute is fully initialized. i.e. has an impl. Nrr3rs r6_attr_has_implzClassManager._attr_has_implAs d{9tCy~~T99r8ct|dS)aCreate a new ClassManager for a subclass of this ClassManager's class. This is called automatically when attributes are instrumented so that the attributes can be propagated to subclasses against their own class-local manager, without the need for mappers etc. to have already pre-configured managers for the full class hierarchy. Mappers can post-configure the auto-generated ClassManager when needed. F)ry)register_class)r3clss r6_subclass_managerzClassManager._subclass_managerIscE22r8ct|j||j|_|j d|jy)Nrq)_generate_initrDrOr^install_memberrWs r6r}zClassManager._instrument_initVs0&t{{D$:L:LM  J 6r8cn|jj||jtjSr1)rK first_initrDrr)rWs r6_state_constructorzClassManager._state_constructorZs&   t{{3"""r8cFt|j|j|y)z0Mark this instance as the manager for its class.N)setattrrD MANAGER_ATTRrWs r6rkzClassManager.manage_s  T..5r8ctSr1)_default_manager_getterrWs r6manager_getterzClassManager.manager_getterds&&r8ctS)zReturn a (instance) -> InstanceState callable. "state getter" callables should raise either KeyError or AttributeError if no InstanceState could be found for the instance. )_default_state_getterrWs r6 state_getterzClassManager.state_getterhs %$r8ctSr1)_default_dict_getterrWs r6 dict_getterzClassManager.dict_getterss##r8c|r||jvr"y||j|<|j|||j|||<|jj D]&}|j |}|j ||d(yr|)r_install_descriptor_reset_memoizationsrD__subclasses__rinstrument_attribute)r3rinst propagatedrmanagers r6rz!ClassManager.instrument_attributews d&&&$(D  S !  # #C .   "S ;;--/ :C,,S1G  ( (dD 9 :r8c#K|jjD]5}t|}|||us||s|jdEd{7y7wr|)rDrresubclass_managers)r3 recursiverrns r6rzClassManager.subclass_managerssX;;--/ ;C&s+C3d? "44T:::  ; ;s +AAAAAAc`tjj|j|||yr1)r~rKattribute_instrumentrDrs r6post_configure_attributez%ClassManager.post_configure_attributes% ))>> KKd3i r8c||vry|r||jvry|j|=|j||j||=|jj D]"}t |}|s|j |d$yr|)r_uninstall_descriptorrrDrreuninstrument_attribute)r3rrrrs r6rz#ClassManager.uninstrument_attributes d?  d&&&  %  % %c *   " I;;--/ :C*3/G..sD9 :r8ct|jD]}|j|d|_d|_d|_|j jt|D]"}||jvs|j|$|j|jjvr!t|j|jyy)z@CD   S$'r8c0t|j|yr1)rrDrs r6rz!ClassManager.uninstall_descriptors S!r8c ||j|jfvrtd|z|jj ||j j j|tt|j ||yr) rrrr`rrDrlgetr-r)r3rimplementations r6rzClassManager.install_membersq 4??D$5$56 6>@CD  !!#t{{';';'?'?X'NO S.1r8c|jj|d}|turt|j||yt |j|yr1)r`popr-rrDr)r3roriginals r6rzClassManager.uninstall_members>>>%%c40 8 # DKKh / DKK %r8c,tj|Sr1)rprepare_instrumentation)r3rcollection_classs r6instrument_collection_classz(ClassManager.instrument_collection_classs223CDDr8c|}|j|}t|sJtj|||}||fSr1)get_implrrCollectionAdapter)r3rrrP user_dataradapters r6initialize_collectionz"ClassManager.initialize_collectionsF I }}S!,T222//eYG !!r8c*|r||vS||jvSr1)r_)r3rsearchs r6is_instrumentedzClassManager.is_instrumenteds $; $*** *r8c ||jSr1rrs r6rzClassManager.get_implsCy~~r8c4t|jSr1)iterrrWs r6 attributeszClassManager.attributessDKKM""r8c|jj|j}||j||}|j|||Sr1)rD__new__r _state_setter)r3rinstances r6 new_instancezClassManager.new_instancesH ;;&&t{{3 =++Hd;E 8U+r8cP||j||}|j||yr1)rrr3rrs r6setup_instancezClassManager.setup_instances+ =++Hd;E 8U+r8c0t||jyr1)rrr3rs r6teardown_instancezClassManager.teardown_instances$//*r8ct||Sr1)_SerializeManager)r3r state_dicts r6 _serializezClassManager._serialize s! 33r8ct||jry|j|jur6|jr*|j |jj |S|j||}|j|||S)zInstall a default InstanceState if none is present. A private convenience method used by the __init__ decorator. F) hasattrrrD __class__rr_new_state_if_nonerrrs r6rzClassManager._new_state_if_nones 8T__ - [[ 2 2 2t~~ ))""  * +++Hd;E   x /Lr8c.t||jSr1)rrrs r6 has_statezClassManager.has_state(sx11r8cF|j|j||S)TODO) optimistic)r hasparent)r3rrr s r6 has_parentzClassManager.has_parent+s#}}S!++Ej+IIr8cy)z=All ClassManagers are non-zero regardless of attribute state.Tr2rWs r6__bool__zClassManager.__bool__1sr8c`d|jj|jt|fzS)Nz<%s of %r at %x>)rr=rDrrWs r6__repr__zClassManager.__repr__5s/! NN # # KK tH%   r8)FNNNNN)ryboolrsOptional[Mapper[_O]]rROptional[_RegistryType]rQOptional[_MapperConfig]rL&Optional[_ExpiredAttributeLoaderProto]rNrMr:r;)r:r;)r:int)rrr:r)r:r)r:z Mapper[_O]r1)rstrr:r)rzType[_T]r:zClassManager[_T])r:zType[state.InstanceState[_O]])F)rrrQueryableAttribute[Any]rrr:r;)rrrrr:r;)rrr:r;)rrrrr:r;)rrrzType[Collection[Any]]r:r%)rrrInstanceState[_O]rPr%r:z@Tuple[collections.CollectionAdapter, _AdaptedCollectionProtocol])rrrrr:r)rrr:r")r:z Iterable[Any])rOptional[InstanceState[_O]]r:r)rrrrr:r;)rrr:r;)rrrDict[str, Any]r:r)rrr:z(Union[Literal[False], InstanceState[_O]])rrr:r)rrrrr rr:r)r:r)Fr=r>r?__doc____annotations__rDEFAULT_MANAGER_ATTRrDEFAULT_STATE_ATTRr staticmethodr attrsetterrrOrQrrRproperty deprecatedrXsetterrqrzrxrrrrmemoized_attributerrrrmemoized_propertyrsrrrrr}rrk hybridmethodrrrrrrrrrrrrrrrrrrrrrrr rrrr2r8r6rJrJ_s 7**,,L((J !<=M::0..37M07 &&=A:A   ## T__ ) -  -""T__ ) , # ,+^'+,048 59$$%$* $ 2 $ # $3$ $LH))##$## $ ## $ ##@$@ 22#B: 37 ##6  '' %% $$! : :&: :  :&; : 4$((5( ("2&EE*?E E "  "! "( " J "+ ## BF,,#>, ,+4&44B4 4  102FKJ&J-0J>BJ J  r8rJrceZdZdZddZdZy)rzProvide serialization of a :class:`.ClassManager`. The :class:`.InstanceState` uses ``__init__()`` on serialize and ``__call__()`` on deserialize. cv|j|_|j}|jj||yr1)rDrrKpickle)r3rdrs r6rqz_SerializeManager.__init__Es,ll --q)r8c^t|jx|_}|#tj|d|jz|j r0|j js|j j||j|||jj||y)NzxCannot deserialize object of type %r - no mapper() has been configured for this class within the current Python process!) rerDrrUnmappedInstanceErrorrrs configured_check_configurerrKunpickle)r3rrrrs r6r7z_SerializeManager.__call__Js"6t{{"CC  ?++"%)KK0   w~~'@'@ NN + + -    " "4 /!!%4r8N)rr9r-r)r=r>r?rrqr7r2r8r6rr=s* 5r8rcPeZdZUdZded<d dZ d dZ d dZd dZy) InstrumentationFactoryz'Factory for new ClassManager instances.z"dispatcher[InstrumentationFactory]rKc|Jt|J|j|\}}|t}t|}n|J|j||||_|Sr1)re_locate_extended_factoryrJ_check_conflictsrP)r3rDrrPs r6create_manager_for_clsz-InstrumentationFactory.create_manager_for_clsdsr!!!#F+333 88@ ?"G"6*G& && fg.!r8cy)z2Overridden by a subclass to do an extended lookup.)NNr2rCs r6r6z/InstrumentationFactory._locate_extended_factoryxsr8cy)z;Overridden by a subclass to test for conflicting factories.Nr2)r3rDrPs r6r7z'InstrumentationFactory._check_conflicts~rEr8cpt|}|j|jj|yr1)manager_of_classrrKclass_uninstrument)r3rDrs r6rz!InstrumentationFactory.unregisters*"6* ((0r8NrF)rDrGr:zr?rrr8r6r7rr2r8r6r4r4_sK100( E JJ)OJ J 1r8r4cxt|}|tj|}|j|||||||S)z_Register class instrumentation. Returns the existing or newly created class manager. )rsrRrQrLrNry)rer~r8rz)rDryrsrRrQrLrNrs r6rrsO#6*G*AA&I )!9  Nr8c.tj|y)z!Unregister class instrumentation.N)r~r)rDs r6unregister_classr@s''/r8cNt|jj|dS)zReturn True if the given attribute on the given instance is instrumented by the attributes package. This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. T)r)r<rr)rrs r6rrs- H.. / ? ? D @ r8cJ| |j}d}tj|d}||z}t|dd}t|dd}t j }t |d<t|||d} |j| _|| _ |r|| _ |r|| _ | S) z>Build an __init__ decorator that triggers ClassManager events.Nzdef __init__(%(apply_pos)s): new_state = class_manager._new_state_if_none(%(self_arg)s) if new_state: return new_state._initialize_instance(%(apply_kw)s) else: return original_init(%(apply_kw)s) F)grouped __defaults____kwdefaults__r=rq) rqrformat_argspec_initgetattrlocalscopyr=execr_sa_original_initrDrE) rD class_managerrO func_body func_vars func_text func_defaultsfunc_kw_defaultsenvrqs r6rrs I((FII%IM>4@M}.>E (--/CC OC:H$,,H!.H -"2 Or8)TNNNNN)rDrGryrrsrrRrrQrrLrrNrMr:rH)Hr __future__rtypingrrrrrr r r r r rrrrrrurrrrr_typingrrrreventrr util.typingrr r!r"r#r$r% decl_baser&eventsr'rsr(r)r*r+symbolr-r/rArrJrr4r~instance_stater instance_dictrr<rre_default_opt_manager_getterrr@rrr2r8r6r_s2# 5!"&).73(&$" T 4;;z "8BhB[ ' '( BK [ |55D'1['1X23 *.)<)<<&'+'9'99 $-1-B-BB*595N5NN2 #'(,04GK15  !&  .  E /<0 )r8