L i hdZddlmZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#dd lm$Z$dd!lm%Z%dd"lm&Z&dd#lm'Z'dd$lm(Z(dd%lm)Z)dd&lm*Z*dd'lm+Z+d(d)lm,Z,d(dlmZ-d(d*lm.Z.d(d+lm/Z/d(d,l0m1Z1d(d-l0m2Z2d(d.l0m3Z3d(d/l4m5Z5d(d0l4m6Z6d(d1l7m8Z8d(d2l9m:Z:d(d3l;mZ>d(d5l/m?Z?d(d6l@mAZAd(d7l@mBZBej,rdd8lCmDZDdd9lCmEZEdd:lCmFZFdd;lCmGZGddlmKZKdd?lLmMZMdd@lLmNZNddAlLmOZOddBlPmQZQddClRmSZSddDlTmUZUddElVmWZWddFlmXZXddGlYmZZZddHl[m\Z\ddIl]m^Z^ddJl_m`Z`ddKl/maZaddLl/mbZbd(dMlcmdZdd(dNlemfZfd(dOlemgZgd(dPlemhZhd(dQlemiZid(dRl9mjZjd(dSlkmlZld(dTl@mmZmeedUfZnedVeWZoedXedYZZped[d\WZqGd]d^e2jZsGd_d`e2je2jeoZvGdadbeveoZwGdcdde2jZyGdedfeBZzGdgdhZ{GdidjeZ|e|e5je5je5je5je5je5je5je5jZ~e|dke5je5je5je5je5je5je5jZGdldmZGdndoeeeoZe.jGdpdqe8eeeoe#e/jZe.jGdrdse+epe epe:ZGdtdueeoZGdvdwe6ZGdxdye8eZGdzd{eZGd|d}eZGd~deZe/jdddGddeZGddZy)z Contains various base classes used throughout the ORM. Defines some key base classes prominent within the internals. This module and the classes within are mostly private, though some attributes are exposed when inspecting mappings. ) annotationsN)Any)Callable)cast)ClassVar)Dict)Generic)Iterator)List)Mapping) NamedTuple)NoReturn)Optional)Sequence)Set)Tuple)Type) TYPE_CHECKING)TypeVar)Union)exc) path_registry)_MappedAttribute) EXT_CONTINUE)EXT_SKIP)EXT_STOP)InspectionAttr)InspectionAttrInfo) MANYTOMANY) MANYTOONE)NO_KEY)NO_VALUE) NotExtension) ONETOMANY)RelationshipDirection)SQLORMOperations) ColumnElement) inspection)util) operators)roles)visitors)_NoArg)ExecutableOption) HasCacheKey)ColumnOperators)Column) TypeEngine)warn_deprecated)RODescriptorReference) TypedDict) _EntityType)_IdentityKeyType) _InstanceDict)_InternalEntityType)_ORMAdapterProto)InstrumentedAttribute)Mapped) _MapperEntity)ORMCompileState) QueryContext) RegistryType)_ClassScanMapperConfig)_PopulatorDict)Mapper)AbstractEntityRegistry)Query)Session) InstanceState) _LoadElement) AliasedInsp) ORMAdapter)Result)_ColumnExpressionArgument)_ColumnsClauseArgument)_DMLColumnArgument) _InfoType) OperatorType)_TraverseInternalsType)_AnnotationScanType._T)bound_T_coT)rV covariant_TLSType[LoaderStrategy]ceZdZdZdZy)ORMStatementRolez?Executable SQL or text() construct, including ORM aware objectsN__name__ __module__ __qualname__ __slots__ _role_namer]_/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.pyr\r\tsIIrdr\ceZdZdZdZy)ORMColumnsClauseRoler]z7ORM mapped entity, aliased entity, or Column expressionNr^r]rdrergrg{sIJJrdrgceZdZdZdZy)ORMEntityColumnsClauseRoler]zORM mapped or aliased entityNr^r]rdreriris I/JrdriceZdZdZdZy)ORMFromClauseRoler]z5ORM mapped entity, aliased entity, or FROM expressionNr^r]rdrerkrks IHJrdrkc@eZdZUded<ded<ded<ded<d ed <y ) ORMColumnDescriptionstrnamez!Union[Type[Any], TypeEngine[Any]]typeboolaliasedz_ColumnsClauseArgument[Any]exprz%Optional[_ColumnsClauseArgument[Any]]entityN)r_r`ra__annotations__r]rdrermrms I ,+ M %% 11rdrmcbeZdZdZeddZddZ d dZd dZy) _IntrospectsAnnotationsr]c|jSN)r_)clss re_mapper_property_namez-_IntrospectsAnnotations._mapper_property_names ||rdc<td|jd)zrreturn a copy of this object to use in declarative when the object is found inside of an Annotated object.z Use of the z> construct inside of an Annotated object is not yet supported.)NotImplementedErrorr{selfs refound_in_pep593_annotatedz1_IntrospectsAnnotations.found_in_pep593_annotateds."$4469:L L  rdc y)zyPerform class-specific initializaton at early declarative scanning time. .. versionadded:: 2.0 Nr]) r decl_scanregistryrzoriginating_modulekeymapped_container annotationextracted_mapped_annotationis_dataclass_fields redeclarative_scanz(_IntrospectsAnnotations.declarative_scanrdc ptjd|jd|d|jd)Nz4Python typing annotation is required for attribute ".z " when primary argument(s) for "z#" construct are None or not present)sa_exc ArgumentErrorr_r{)rrrzs re_raise_for_requiredz+_IntrospectsAnnotations._raise_for_requiredsG"" ~Qse$**,-.0 0  rdNreturnrn)rr)rrCrrBrz Type[Any]r Optional[str]rrnrzOptional[Type[Mapped[Any]]]rOptional[_AnnotationScanType]rrrrqrNone)rrnrzrrr) r_r`rarb classmethodr{rrrr]rdrerwrwsI  )    *    6 2 &C !   & rdrwceZdZUdZded<ded<ded<ded<ded <ded <d ed <d ed<ddZe ddZy)_AttributeOptionszdefine Python-local attribute behavior options common to all :class:`.MapperProperty` objects. Currently this includes dataclass-generation arguments. .. versionadded:: 2.0 zUnion[_NoArg, bool]dataclasses_initdataclasses_reprzUnion[_NoArg, Any]dataclasses_defaultz Union[_NoArg, Callable[[], Any]]dataclasses_default_factorydataclasses_comparedataclasses_kw_onlyzUnion[_NoArg, bool, None]dataclasses_hashz&Union[_NoArg, Mapping[Any, Any], None]dataclasses_dataclass_metadataci}|jtjur|j|d<|jtjur|j|d<|jtjur|j|d<|j tjur|j |d<|j tjur|j |d<|jtjur|j|d<|jtjur|j|d<|jtjur|j|d<d|vrt|drtd |d d d|vr4|ds/d|vr+t|dsd|vr|jdfd |d<tjd i|S)zz7_AttributeOptions._as_dataclass_field..sGrdr])rr/NO_ARGrrrrrrrcallabler5pop dataclassesfield)rrkwrs @re_as_dataclass_fieldz%_AttributeOptions._as_dataclass_fields   + +6== @$($D$DB !  # #6== 8 44ByM   5..BvJ   5..BvJ  # #6== 8 44ByM  # #6== 8 44ByM   5..BvJ  . .fmm C!@@BzN ?x9 6  G$= =  bLvJRR ]+!+ffY'G$3B !  &2&&rdct|tr |jj|}|||fS|tj ur|||fS|Jd||fS)zgiven attribute key, annotation, and value from a class, return the argument tuple we would pass to dataclasses.make_dataclass() for this attribute. z/Mapped[] received without a mapping declaration) isinstance_DCAttributeOptions_attribute_optionsrr/r)rzrrrelemdc_fields re!_get_arguments_for_make_dataclassz3_AttributeOptions._get_arguments_for_make_dataclasssl d/ 0..BB3GHX. .  &T* *  ) LK K5 $ $rdN)rrnrr) rrnrrTr Optional[Any]rrrz_Union[Tuple[str, _AnnotationScanType], Tuple[str, _AnnotationScanType, dataclasses.Field[Any]]])r_r`ra__doc__rurrrr]rdrerrs*)))++!AA,,,,//$JJ1'f%% %%(%%( %%  %%   %%%%rdrFc,eZdZUdZdZded< ded<y)rawmixin for descriptors or configurational objects that include dataclass field options. This includes :class:`.MapperProperty`, :class:`._MapsColumn` within the ORM, but also includes :class:`.AssociationProxy` within ext. Can in theory be used for other descriptors that serve a similar role as association proxy. (*maybe* hybrids, not sure yet.) r]rrrq_has_dataclass_argumentsN)r_r`rarrbrur]rdrerrHs!I)) #"rdrc8eZdZdZdZeddZeddZy) _MapsColumnszinterface for declarative-capable construct that delivers one or more Column objects to the declarative process to be part of a Table. r]ct)zAreturn a MapperProperty to be assigned to the declarative mappingr}r~s remapper_property_to_assignz&_MapsColumns.mapper_property_to_assignfs "##rdct)zfA list of Column objects that should be declaratively added to the new Table object. rr~s recolumns_to_assignz_MapsColumns.columns_to_assignks "##rdN)rzOptional[MapperProperty[_T]])rzList[Tuple[Column[_T], int]])r_r`rarrbpropertyrrr]rdrerr_s4I $$$$rdrceZdZUdZdZdej jfdej jfgZ de d<e sdZ dZ d e d < d e d< d e d< d Zde d< de d< de d< d!dZ d"dZ d#dZ d$ d%dZd&dZd'dZ d( d)dZd*dZed+dZd*dZd'dZ d,dZd-d Zy).MapperPropertyaRepresent a particular class attribute mapped by :class:`_orm.Mapper`. The most common occurrences of :class:`.MapperProperty` are the mapped :class:`_schema.Column`, which is represented in a mapping as an instance of :class:`.ColumnProperty`, and a reference to another class produced by :func:`_orm.relationship`, represented in the mapping as an instance of :class:`.Relationship`. )_configure_started_configure_finishedrrparentrinfodocrrrS_cache_key_traversalNTzPropComparator[_T] comparatorrn Mapper[Any]Frq_links_to_entityrrrQrciS)aInfo dictionary associated with the object, allowing user-defined data to be associated with this :class:`.InspectionAttr`. The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the :func:`.column_property`, :func:`_orm.relationship`, or :func:`.composite` functions. .. seealso:: :attr:`.QueryableAttribute.info` :attr:`.SchemaItem.info` r]r~s re_memoized_attr_infoz"MapperProperty._memoized_attr_infos " rdc y)aCalled by Query for the purposes of constructing a SQL statement. Each MapperProperty associated with the target mapper processes the statement referenced by the query context, adding columns and/or criterion as appropriate. Nr])rcontext query_entitypathadapterkwargss resetupzMapperProperty.setuprrdcy)zcProduce row processing functions and append to the given set of populators lists. Nr])rrrrmapperresultr populatorss recreate_row_processorz#MapperProperty.create_row_processorrrdctdS)aIterate through instances related to the given instance for a particular 'cascade', starting with this MapperProperty. Return an iterator3-tuples (instance, mapper, state). Note that the 'cascade' collection on this MapperProperty is checked first for the given type before cascade_iterator is called. This method typically only applies to Relationship. r])iter)rtype_statedict_visited_stateshalt_ons recascade_iteratorzMapperProperty.cascade_iterators ,Bxrdc||_y)zSet the parent mapper that references this MapperProperty. This method is overridden by some subclasses to perform extra setup when the mapper is first known. N)r)rrrs re set_parentzMapperProperty.set_parents  rdcy)aIHook called by the Mapper to the property to initiate instrumentation of the class attribute managed by this MapperProperty. The MapperProperty here will typically call out to the attributes module to set up an InstrumentedAttribute. This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mapper setup process. The second step is typically the init_class_attribute step, called from StrategizedProperty via the post_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute (specifically the "impl") which has been determined after the MapperProperty has determined what kind of persistence management it needs to do (e.g. scalar, object, collection, etc). Nr]rrs reinstrument_classzMapperProperty.instrument_class#rrdcd|_d|_|rt}nt}|r||k7rd|_||_yd|_||_y)NFT)rr#_DEFAULT_READONLY_ATTRIBUTE_OPTIONS_DEFAULT_ATTRIBUTE_OPTIONSrr)rattribute_options_assume_readonly_dc_attributes default_attrss re__init__zMapperProperty.__init__7sL #(#( )?M6M !2m!C,0D )&7D #,1D )&3D #rdc@d|_|jd|_y)zCalled after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps. TN)rdo_initrr~s rerzMapperProperty.initKs#' #' rdcVt|jj|jS)aReturn the class-bound descriptor corresponding to this :class:`.MapperProperty`. This is basically a ``getattr()`` call:: return getattr(self.parent.class_, self.key) I.e. if this :class:`.MapperProperty` were named ``addresses``, and the class to which it is mapped is ``User``, this sequence is possible:: >>> from sqlalchemy import inspect >>> mapper = inspect(User) >>> addresses_property = mapper.attrs.addresses >>> addresses_property.class_attribute is User.addresses True >>> User.addresses.property is addresses_property True )getattrrclass_rr~s reclass_attributezMapperProperty.class_attributeVs0t{{))48844rdcy)zPerform subclass-specific initialization post-mapper-creation steps. This is a template method called by the ``MapperProperty`` object's init() method. Nr]r~s rerzMapperProperty.do_initprrdcy)aPerform instrumentation adjustments that need to occur after init() has completed. The given Mapper is the Mapper invoking the operation, which may not be the same Mapper as self.parent in an inheritance scenario; however, Mapper will always at least be a sub-mapper of self.parent. This method is typically used by StrategizedProperty, which delegates it to LoaderStrategy.init_class_attribute() to perform final setup on the class-bound InstrumentedAttribute. Nr]rs repost_instrument_classz$MapperProperty.post_instrument_classyrrdc y)zoMerge the attribute represented by this ``MapperProperty`` from source to destination object. Nr]) rsession source_state source_dict dest_state dest_dictload _recursive_resolve_conflict_maps remergezMapperProperty.mergerrdcbd|jjt|t|ddfzS)Nz<%s at 0x%x; %s>rzno key) __class__r_idrr~s re__repr__zMapperProperty.__repr__s4! NN # # tH D% *%   rdrrQ rr@rr?rrFrOptional[ORMAdapter]rrrrrr@rr?rrFrrr Result[Any]rr rrDrrry) rrnrInstanceState[Any]rr:rzSet[InstanceState[Any]]rz.Optional[Callable[[InstanceState[Any]], bool]]rzGIterator[Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]])rrrrqrrrrrrNF)rzOptional[_AttributeOptions]rrqrrrr)rzInstrumentedAttribute[_T])rrHrrrr:rrrr:rrqrzDict[Any, object]rz#Dict[_IdentityKeyType[Any], object]rrr)r_r`rarrbr.ExtendedInternalTraversaldp_has_cache_key dp_stringrrurcascade is_property_is_relationshiprrrrrrrrrrrrrr r]rdrerr}s:  I 855FFG 22<<=40 K #"C H! 6 ' O &   $ %  &          $  %      &  #     *CG "  0  @  0 ,:>/4464)-4  4( (552     ) #  '  !   &  C    rdrcXeZdZUdZdZdZded<ded<ded < d dd Zejdd Z d d Z d!dZ d"dZ ejd#dZ d d$dZejd%dZejd&dZed'dZed(dZed)dZeej2eZeej2eZeej2eZej<r d*dZ d*dZ d+dZ! d,dZ" d d-dZ# d d-dZ$y ).PropComparatora& Defines SQL operations for ORM mapped attributes. SQLAlchemy allows for operators to be redefined at both the Core and ORM level. :class:`.PropComparator` is the base class of operator redefinition for ORM-level operations, including those of :class:`.ColumnProperty`, :class:`.Relationship`, and :class:`.Composite`. User-defined subclasses of :class:`.PropComparator` may be created. The built-in Python comparison and math operator methods, such as :meth:`.operators.ColumnOperators.__eq__`, :meth:`.operators.ColumnOperators.__lt__`, and :meth:`.operators.ColumnOperators.__add__`, can be overridden to provide new operator behavior. The custom :class:`.PropComparator` is passed to the :class:`.MapperProperty` instance via the ``comparator_factory`` argument. In each case, the appropriate subclass of :class:`.PropComparator` should be used:: # definition of custom PropComparator subclasses from sqlalchemy.orm.properties import ( ColumnProperty, Composite, Relationship, ) class MyColumnComparator(ColumnProperty.Comparator): def __eq__(self, other): return self.__clause_element__() == other class MyRelationshipComparator(Relationship.Comparator): def any(self, expression): "define the 'any' operation" # ... class MyCompositeComparator(Composite.Comparator): def __gt__(self, other): "redefine the 'greater than' operation" return sql.and_( *[ a > b for a, b in zip( self.__clause_element__().clauses, other.__composite_values__(), ) ] ) # application of custom PropComparator subclasses from sqlalchemy.orm import column_property, relationship, composite from sqlalchemy import Column, String class SomeMappedClass(Base): some_column = column_property( Column("some_column", String), comparator_factory=MyColumnComparator, ) some_relationship = relationship( SomeOtherClass, comparator_factory=MyRelationshipComparator ) some_composite = composite( Column("a", String), Column("b", String), comparator_factory=MyCompositeComparator, ) Note that for column-level operator redefinition, it's usually simpler to define the operators at the Core level, using the :attr:`.TypeEngine.comparator_factory` attribute. See :ref:`types_operators` for more detail. .. seealso:: :class:`.ColumnProperty.Comparator` :class:`.Relationship.Comparator` :class:`.Composite.Comparator` :class:`.ColumnOperators` :ref:`types_operators` :attr:`.TypeEngine.comparator_factory` prop _parententity_adapt_to_entityorm_prop_comparator_InternalEntityType[Any]rOptional[AliasedInsp[Any]]rz,RODescriptorReference[MapperProperty[_T_co]]rNc6||_|xs||_||_yryr)rr parentmapperadapt_to_entitys rerzPropComparator.__init__ s  ,<  /rdc|jS)zReturn the :class:`.MapperProperty` associated with this :class:`.PropComparator`. Return values here will commonly be instances of :class:`.ColumnProperty` or :class:`.Relationship`. )rr~s rerzPropComparator.propertysyyrdctd|z)Nz%rrr~s re__clause_element__z!PropComparator.__clause_element__!s!$+..rdc<td|j|fgS)zReceive a SQL expression that represents a value in the SET clause of an UPDATE statement. Return a tuple that can be passed to a :class:`_expression.Update` construct. rP)rr()rvalues re_bulk_update_tuplesz"PropComparator._bulk_update_tuples$s#*D,C,C,EFNOOrdcP|j|j|j|S)zReturn a copy of this PropComparator which will use the given :class:`.AliasedInsp` to produce corresponding expressions. )rrr)rr%s rer%zPropComparator.adapt_to_entity1s! ~~dii););_MMrdc.|jjS)zZlegacy; this is renamed to _parententity to be compatible with QueryableAttribute.)rrr~s re _parentmapperzPropComparator._parentmapper9s!!(((rdc P|jjj|fi|Sry)rr_criterion_existsr criterionrs rer0z PropComparator._criterion_exists?s& 6tyy##55iJ6JJrdcH|jy|jjS)zrProduce a callable that adapts column expressions to suit an aliased version of this comparator. N)r_orm_adapt_elementr~s rerzPropComparator.adapterFs%  (((;; ;rdc.|jjSry)rrr~s rerzPropComparator.infoQsyy~~rdc (|j|fi|Sry)any)abrs re_any_opzPropComparator._any_opUsquuQ!&!!rdc (|j|fi|Sry)has)leftotherrs re_has_opzPropComparator._has_opYstxx(((rdc$|j|Sry)of_type)r8rs re _of_type_opzPropComparator._of_type_op]syy  rdcyryr]ropr>rs reoperatezPropComparator.operateg!$rdc yryr]rDs rereverse_operatezPropComparator.reverse_operatekrGrdcB|jtj|S)aRedefine this object in terms of a polymorphic subclass, :func:`_orm.with_polymorphic` construct, or :func:`_orm.aliased` construct. Returns a new PropComparator from which further criterion can be evaluated. e.g.:: query.join(Company.employees.of_type(Engineer)).filter( Engineer.name == "foo" ) :param \class_: a class or mapper indicating that criterion will be against this specific subclass. .. seealso:: :ref:`orm_queryguide_joining_relationships_aliased` - in the :ref:`queryguide_toplevel` :ref:`inheritance_of_type` )rFr of_type_op)rrs rerAzPropComparator.of_typeos4||N55v>>rdcD|jtjg|S)a?Add additional criteria to the ON clause that's represented by this relationship attribute. E.g.:: stmt = select(User).join( User.addresses.and_(Address.email_address != "foo") ) stmt = select(User).options( joinedload(User.addresses.and_(Address.email_address != "foo")) ) .. versionadded:: 1.4 .. seealso:: :ref:`orm_queryguide_join_on_augmented` :ref:`loader_option_criteria` :func:`.with_loader_criteria` )rFr,and_)rcriterias rerMzPropComparator.and_s8t||INN6X66rdc F|jtj|fi|S)aReturn a SQL expression representing true if this element references a member which meets the given criterion. The usual implementation of ``any()`` is :meth:`.Relationship.Comparator.any`. :param criterion: an optional ClauseElement formulated against the member class' table or attributes. :param \**kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values. )rFrany_opr1s rer7zPropComparator.any"(t||N119GGGrdc F|jtj|fi|S)aReturn a SQL expression representing true if this element references a member which meets the given criterion. The usual implementation of ``has()`` is :meth:`.Relationship.Comparator.has`. :param criterion: an optional ClauseElement formulated against the member class' table or attributes. :param \**kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values. )rFrhas_opr1s rer<zPropComparator.hasrQrdry)rzMapperProperty[_T]r$r!r%r")rzMapperProperty[_T_co])rzroles.ColumnsClauseRole)r*rrz(Sequence[Tuple[_DMLColumnArgument, Any]])r%zAliasedInsp[Any]rPropComparator[_T_co])rr)r2)Optional[_ColumnExpressionArgument[bool]]rrrColumnElement[Any])rzOptional[_ORMAdapterProto]r )r8rr9rrrrr)r=rr>rrrrr)r8rrrrr)rErRr>rrrrrV)rz_EntityType[Any]rrT)rNz_ColumnExpressionArgument[bool]rzPropComparator[bool])r2rUrrrzColumnElement[bool])%r_r`rarrb__visit_name__rurr+non_memoized_propertyrr(r+r%ro_non_memoized_propertyr.r0rr staticmethodr:r?rBrr,rRrPrSrKtypingrrFrIrArMr7r<r]rdrerrsP^@ %  % %" %+. %:= %  %?8787 7@@DH<HH  H0@DH<HH  HrdrceZdZUdZdZdZded<ded<ded <dd Z dd Z dd Z dd Z ddZ ddZ ddZ ddZej eZded<eddZe d dZy)!StrategizedPropertyaA MapperProperty which uses selectable strategies to affect loading behavior. There is a single strategy selected by default. Alternate strategies can be selected at Query time through the usage of ``StrategizedOption`` objects via the Query.options() method. The mechanics of StrategizedProperty are used for every Query invocation for every mapped attribute participating in that Query, to determine first how the attribute will be rendered in SQL and secondly how the attribute will retrieve a value from a result row and apply it to a mapped object. The routines here are very performance-critical. ) _strategiesstrategy_wildcard_token_default_path_loader_key strategy_keyTz ClassVar[str]strategy_wildcard_key _StrategyKeyrbz"Dict[_StrategyKey, LoaderStrategy]r^cB|jdtjfS)N:)rcr_WILDCARD_TOKENr~s re_memoized_attr__wildcard_tokenz2StrategizedProperty._memoized_attr__wildcard_tokens())*!M,I,I+J K  rdcFd|jdtjffS)Nloaderrf)rcr_DEFAULT_TOKENr~s re'_memoized_attr__default_path_loader_keyz;StrategizedProperty._memoized_attr__default_path_loader_keys0 **+1]-I-I,J K M  rdcd}||}|j|j|jfD]"}||jvs|j|}|S|Sry) _loader_key_wildcard_path_loader_keyra attributes)rrrr search_pathpath_keys re_get_context_loaderz'StrategizedProperty._get_context_loadersq(,4j  # #  1 1  0 0  H 7---))(3 !   rdc |j|S#t$rYnwxYw|j|g|}|||x|j|<}|Sry)r^KeyError_strategy_lookup)rrrzr_s re _get_strategyz!StrategizedProperty._get_strategyse ##C( (   $d##D/3/,/tS>9s  c |j||}|r(|jr|j|j}n |j}|j|||||fi|yry)rsr_rw setup_query)rrrrrrrjstrats rerzStrategizedProperty.setup+s_))'48 foo&&v7EMME \4 .decorategs^ w'7'77)+&rxxz*+C,3C   $S )  " " ) )# .Nrd)rrYrrYr])rzrrs`` re strategy_forz StrategizedProperty.strategy_fores rdc|jj|jD]?}||jvstrt |t sJ|j|} ||cS|jjD]\}}||vs |}||}nd}d}tj|||||#t$rYwxYwry) r_with_polymorphic_mappers__mro__rr issubclassrrurorm_excLoaderStrategyException) rzrequesting_propertyrprop_cls strategies property_typestratsintended_property_typeactual_strategys rervz$StrategizedProperty._strategy_lookupss ""<<  H3... %h??? 00: %c?*  &)%8%8%>%>%@ # !M6f})6&"(+  # &* ""O--   "      sB11 B=<B=N)rz Tuple[str])rzTuple[str, Tuple[str]])rr@rrFrOptional[_LoadElement])rrdrLoaderStrategyr rrr)rrrzCallable[[_TLS], _TLS])rMapperProperty[Any]rrrrZ)r_r`rarrb inherit_cacherurhrlrsrwrrrr collections defaultdictdictrrrrvr]rdrer]r]sX IM((33   &.D 6    $ %  &      "   $ %      & #   4>7 %&   "5 =@   rdr]cFeZdZdZdZdZdZ dZdZdZ dZ dZ ddZ y) ORMOptionaBase class for option objects that are passed to ORM queries. These options may be consumed by :meth:`.Query.options`, :meth:`.Select.options`, or in a more general sense by any :meth:`.Executable.options` method. They are interpreted at statement compile time or execution time in modern use. The deprecated :class:`.MapperOption` is consumed at ORM query construction time. .. versionadded:: 1.4 r]Fc||S|S)aadapt this option to the "uncached" version of itself in a loader strategy context. given "self" which is an option from a cached query, as well as the corresponding option from the uncached version of the same query, return the option we should use in a new query, in the context of a loader strategy being asked to load related rows on behalf of that cached query, which is assumed to be building a new query based on entities passed to us from the cached query. Currently this routine chooses between "self" and "uncached" without manufacturing anything new. If the option is itself a loader strategy option which has a path, that path needs to match to the entities being passed to us by the cached query, so the :class:`_orm.Load` subclass overrides this to return "self". For all other options, we return the uncached form which may have changing state, such as a with_loader_criteria() option which will very often have new state. This routine could in the future involve generating a new option based on both inputs if use cases arise, such as if with_loader_criteria() needed to match up to ``AliasedClass`` instances given in the parent query. However, longer term it might be better to restructure things such that ``AliasedClass`` entities are always matched up on their cache key, instead of identity, in things like paths and such, so that this whole issue of "the uncached option does not match the entities" goes away. However this would make ``PathRegistry`` more complicated and difficult to debug as well as potentially less performant in that it would be hashing enormous cache keys rather than a simple AliasedInsp. UNLESS, we could get cache keys overall to be reliably hashed into something like an md5 key. .. versionadded:: 1.4.41 r])rr uncached_opts re'_adapt_cached_option_to_uncached_optionz1ORMOption._adapt_cached_option_to_uncached_optionsN  # KrdN)rrArrrr) r_r`rarrb_is_legacy_optionpropagate_to_loaders_is_core_is_user_defined_is_compile_state_is_criteria_option_is_strategy_optionrr]rdrerrs[ I  H*#*3<* *rdrc4eZdZdZdZdZddZ ddZy) CompileStateOptionabase for :class:`.ORMOption` classes that affect the compilation of a SQL query and therefore need to be part of the cache key. .. note:: :class:`.CompileStateOption` is generally non-public and should not be used as a base class for user-defined options; instead, use :class:`.UserDefinedOption`, which is easier to use as it does not interact with ORM compilation internals or caching. :class:`.CompileStateOption` defines an internal attribute ``_is_compile_state=True`` which has the effect of the ORM compilation routines for SELECT and other statements will call upon these options when a SQL string is being compiled. As such, these classes implement :class:`.HasCacheKey` and need to provide robust ``_cache_key_traversal`` structures. The :class:`.CompileStateOption` class is used to implement the ORM :class:`.LoaderOption` and :class:`.CriteriaOption` classes. .. versionadded:: 1.4.28 r]Tcy)zApply a modification to a given :class:`.ORMCompileState`. This method is part of the implementation of a particular :class:`.CompileStateOption` and is only invoked internally when an ORM query is compiled. Nr])r compile_states reprocess_compile_statez(CompileStateOption.process_compile_staterrdcy)aqApply a modification to a given :class:`.ORMCompileState`, given entities that were replaced by with_only_columns() or with_entities(). This method is part of the implementation of a particular :class:`.CompileStateOption` and is only invoked internally when an ORM query is compiled. .. versionadded:: 1.4.19 Nr]rrmapper_entitiess re'process_compile_state_replaced_entitiesz:CompileStateOption.process_compile_state_replaced_entities rrdN)rr@rrrr@rzSequence[_MapperEntity]rr)r_r`rarrbrrrr]rdrerrs:.I  & 1    rdrc(eZdZdZdZ ddZy) LoaderOptionzhDescribe a loader modification to an ORM statement at compilation time. .. versionadded:: 1.4 r]c&|j|yry)rrs rerz4LoaderOption.process_compile_state_replaced_entities%s ""=1rdNr)r_r`rarrbrr]rdrerrs/ I2&212  2rdrc eZdZdZdZdZddZy)CriteriaOptionztDescribe a WHERE criteria modification to an ORM statement at compilation time. .. versionadded:: 1.4 r]Tcy)z_update additional entity criteria options in the given attributes dictionary. Nr])rrps reget_global_criteriaz"CriteriaOption.get_global_criteria9rrdN)rpzDict[str, Any]rr)r_r`rarrbrrr]rdrerr-sI rdrc,eZdZdZdZdZdZdZ dddZy) UserDefinedOptionz~Base class for a user-defined option that can be consumed from the :meth:`.SessionEvents.do_orm_execute` event hook. payloadFTNc||_yryr)rrs rerzUserDefinedOption.__init__Ss  rdry)rr) r_r`rarrbrrrrr]rdrerr@s* I  rdrz1.4aKThe :class:`.MapperOption class is deprecated and will be removed in a future release. For modifications to queries on a per-execution basis, use the :class:`.UserDefinedOption` class to establish state within a :class:`.Query` or other Core statement, then use the :meth:`.SessionEvents.before_orm_execute` hook to consume them.) constructorc.eZdZdZdZdZdZ ddZddZy) MapperOptionz"Describe a modification to a Queryr]TFcy)z8Apply a modification to the given :class:`_query.Query`.Nr]rquerys re process_queryzMapperOption.process_queryorrdc&|j|y)aosame as process_query(), except that this option may not apply to the given query. This is typically applied during a lazy load or scalar refresh operation to propagate options stated in the original Query to the new Query being used for the load. It occurs for those options that specify propagate_to_loaders=True. N)rrs reprocess_query_conditionallyz(MapperOption.process_query_conditionallyrs 5!rdN)rz Query[Any]rr) r_r`rarrbrrrrr]rdrerrWs(-I  G "rdrceZdZUdZdZded< d dZd dZ d dZ ddZ dd Z y )raDescribe the loading behavior of a StrategizedProperty object. The ``LoaderStrategy`` interacts with the querying process in three ways: * it controls the configuration of the ``InstrumentedAttribute`` placed on a class to handle the behavior of the attribute. this may involve setting up class-level callable functions to fire off a select operation when the attribute is first accessed (i.e. a lazy load) * it processes the ``QueryContext`` at statement construction time, where it can modify the SQL statement that is being produced. For example, simple column attributes will add their represented column to the list of selected columns, a joined eager loader may establish join clauses to add to the statement. * It produces "row processor" functions at result fetching time. These "row processor" functions populate a particular attribute on a particular mapped instance. )parent_propertyis_class_levelrrrb strategy_optszClassVar[List[_StrategyKey]]rc||_d|_|jj|_|jj|_||_t ||_yr)rrrrrbrr)rrrbs rerzLoaderStrategy.__init__sO &#**11 ''++(!,/rdcyryr]rs rerz#LoaderStrategy.init_class_attributes rdc y)zEstablish column and other state for a given QueryContext. This method fulfills the contract specified by MapperProperty.setup(). StrategizedProperty delegates its setup() method directly to this method. Nr])rrrrloadoptrrs reryzLoaderStrategy.setup_queryrrdc y)aEstablish row processing functions for a given QueryContext. This method fulfills the contract specified by MapperProperty.create_row_processor(). StrategizedProperty delegates its create_row_processor() method directly to this method. Nr]) rrrrrrrrrs rerz#LoaderStrategy.create_row_processorrrdc,t|jSry)rnrr~s re__str__zLoaderStrategy.__str__s4''((rdN)rrrbrdr)rr@rr?rrFrrrr rrrr)rr@rr?rrFrrrrrrrr rrDrrr) r_r`rarrbrurrryrrr]rdrerrs.I100)09E0  & $ %  (  &     $   $ %  (     & #   *)rdr)r __future__rrrr[rrrrrr r r r r rrrrrrrrrrrrbaserrrrrrr r!r"r#r$r%r&r'r)rr*r+sqlr,r-r.sql.baser/r0 sql.cache_keyr1 sql.operatorsr2 sql.schemar3 sql.type_apir4r5 util.typingr6r7_typingr8r9r:r;r<rpr=r>rr?r@rAdecl_apirB decl_baserCloadingrDrrErFrrGrrHrrIstrategy_optionsrJrKrL engine.resultrM sql._typingrNrOrPrQrR sql.visitorsrSrTrdrUrWrY StatementRoler\ColumnsClauseRoleTypedColumnsClauseRolergriStrictFromClauseRolerkrmrwrrrrrr_self_inspects MemoizedSlotsrrr]rrrrrdeprecated_clsrrr]rdrersx #  6.&&2:*("&.(@"''+%"/# $)&,)1&(%&1'5 $.! &740',51S#X  Tsd3v34u**K U99"=K0!5b!90 I22I 292) ) Xl% l%^/ MM MM MM MM MM MM MM MM '8  MM MM MM MM MM MM MM '###.$&(8(<$< _ R _ _ D  rH%e,genorHrHj | .,| ~M M`4 i4 n2%2" ' & . F  "9" ">X)X)rd