U kfv @sdZddlmZddlZddlZddlZddlmZddlmZddlmZddlm 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*d'd(lm+Z+d'dlmZ,d'd)lm-Z-d'd*lm.Z.d'd+l/m0Z0d'd,l/m1Z1d'd-l/m2Z2d'd.l3m4Z4d'd/l3m5Z5d'd0l6m7Z7d'd1l8m9Z9d'd2l:m;Z;d'd3lZ>d'd5l?m@Z@d'd6l?mAZAejrdd7lBmCZCdd8lBmDZDdd9lBmEZEdd:lBmFZFdd;lBmGZGddlKmLZLdd?lKmMZMdd@lKmNZNddAlOmPZPddBlQmRZRddClSmTZTddDlUmVZVddElmWZWddFlXmYZYddGlZm[Z[ddHl\m]Z]ddIl^m_Z_ddJl.m`Z`ddKl.maZad'dLlbmcZcd'dMldmeZed'dNldmfZfd'dOldmgZgd'dPldmhZhd'dQl8miZid'dRljmkZkd'dSl?mlZleedTfZmedUedVZnedWedXdYZoedZd[dVZpGd\d]d]e1jqZrGd^d_d_e1jse1jtenZuGd`dadaeuenZvGdbdcdce1jwZxGdddedeeAZyGdfdgdgZzGdhdidieZ{e{e4j|e4j|e4j|e4j|e4j|e4j|Z}e{dje4j|e4j|e4j|e4j|e4j|Z~GdkdldlZGdmdndneeenZe-jGdodpdpe7eeene"e.jZe-jGdqdrdre*eoe eoe9ZGdsdtdteenZGdudvdve5ZGdwdxdxe7eZGdydzdzeZGd{d|d|eZGd}d~d~eZe.jddddGdddeZGdddZdS)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) 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)rT covariant_TLSType[LoaderStrategy]c@seZdZdZdZdS)ORMStatementRolez?Executable SQL or text() construct, including ORM aware objectsN__name__ __module__ __qualname__ __slots__Z _role_namerZrZrZI/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/orm/interfaces.pyrYssrYc@seZdZdZdZdS)ORMColumnsClauseRolerZz7ORM mapped entity, aliased entity, or Column expressionNr[rZrZrZr`razsrac@seZdZdZdZdS)ORMEntityColumnsClauseRolerZzORM mapped or aliased entityNr[rZrZrZr`rbsrbc@seZdZdZdZdS)ORMFromClauseRolerZz5ORM mapped entity, aliased entity, or FROM expressionNr[rZrZrZr`rcsrcc@s6eZdZUded<ded<ded<ded<d ed <d S) ORMColumnDescriptionstrnamez!Union[Type[Any], TypeEngine[Any]]typeboolaliasedz_ColumnsClauseArgument[Any]exprz%Optional[_ColumnsClauseArgument[Any]]entityN)r\r]r^__annotations__rZrZrZr`rds rdc @sbeZdZdZeddddZddddZd d d d dd ddddd ddZdd ddddZdS)_IntrospectsAnnotationsrZrereturncCs|jSN)r\)clsrZrZr`_mapper_property_namesz-_IntrospectsAnnotations._mapper_property_namercCstd|ddS)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.N)NotImplementedErrorrrselfrZrZr`found_in_pep593_annotatedsz1_IntrospectsAnnotations.found_in_pep593_annotatedrAr@z Type[Any] Optional[str]zOptional[Type[Mapped[Any]]]zOptional[_AnnotationScanType]rhNone) decl_scanregistryrqoriginating_modulekeymapped_container annotationextracted_mapped_annotationis_dataclass_fieldroc CsdS)zyPerform class-specific initializaton at early declarative scanning time. .. versionadded:: 2.0 NrZ) ruryrzrqr{r|r}r~rrrZrZr`declarative_scans z(_IntrospectsAnnotations.declarative_scanr )r|rqroc Cs(td|jd|d|ddS)Nz4Python typing annotation is required for attribute ".z " when primary argument(s) for "z#" construct are None or not present)sa_exc ArgumentErrorr\rr)rur|rqrZrZr`_raise_for_requiredsz+_IntrospectsAnnotations._raise_for_requiredN) r\r]r^r_ classmethodrrrvrrrZrZrZr`rms  rmc@sleZdZUdZded<ded<ded<ded<ded <ded <d d d ddZed dddddddZdS)_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_onlyrerr|rocsi}|jtjk r|j|d<|jtjk r0|j|d<|jtjk rF|j|d<|jtjk r\|j|d<|jtjk rr|j|d<|jtjk r|j|d<d|krt|drt d|dd d|kr|dsd|krt|dsd|kr| dfd d |d<t j f|S) zz7_AttributeOptions._as_dataclass_field..) rr-NO_ARGrrrrrcallabler3pop dataclassesfield)rur|kwrZrr`_as_dataclass_fields>               z%_AttributeOptions._as_dataclass_fieldrR Optional[Any]rSz_Union[Tuple[str, _AnnotationScanType], Tuple[str, _AnnotationScanType, dataclasses.Field[Any]]])r|r~r}elemrocCsVt|tr |j|}|||fS|tjk r4|||fS|dk rJdsRtdn||fSdS)zgiven attribute key, annotation, and value from a class, return the argument tuple we would pass to dataclasses.make_dataclass() for this attribute. NFz/Mapped[] received without a mapping declaration) isinstance_DCAttributeOptions_attribute_optionsrr-rAssertionError)rqr|r~r}rZdc_fieldrZrZr`!_get_arguments_for_make_dataclasss      z3_AttributeOptions._get_arguments_for_make_dataclassN)r\r]r^__doc__rlrrrrZrZrZr`rs  /rFc@s&eZdZUdZdZded<ded<dS)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.) rZrrrh_has_dataclass_argumentsN)r\r]r^rr_rlrZrZrZr`r=s  rc@s8eZdZdZdZeddddZedddd Zd S) _MapsColumnszinterface for declarative-capable construct that delivers one or more Column objects to the declarative process to be part of a Table. rZzOptional[MapperProperty[_T]]rncCs tdS)zAreturn a MapperProperty to be assigned to the declarative mappingNrsrtrZrZr`mapper_property_to_assign[sz&_MapsColumns.mapper_property_to_assignzList[Tuple[Column[_T], int]]cCs tdS)zfA list of Column objects that should be declaratively added to the new Table object. NrrtrZrZr`columns_to_assign`sz_MapsColumns.columns_to_assignN)r\r]r^rr_propertyrrrZrZrZr`rTs rc @sreZdZUdZdZdejjfdejjfgZ de d<e s:dZ dZ d e d <d e d<d e d<d Zde d<de d<de d<ddddZdddddddddZdddd d dd!dd"d#d$ZdHd d%d&d'd(d)d*d+d,Zd ddd-d.d/Zd dd0d1d2ZdId3ddd4d5d6Zddd7d8Zed9dd:d;Zdddd?Zd@d%d&d%d&ddAdBddC dDdEZd ddFdGZdS)JMapperPropertyaRepresent 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_finishedrrparentr|infodocrr|rQ_cache_key_traversalNTzPropComparator[_T] comparatorre Mapper[Any]FrhZ_links_to_entityrwrrOrrncCsiS)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` rZrtrZrZr`_memoized_attr_infosz"MapperProperty._memoized_attr_infor>r=rDOptional[ORMAdapter]rrxcontext query_entitypathadapterkwargsrocKsdS)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. NrZ)rurrrrrrZrZr`setupszMapperProperty.setup Result[Any]rBrrrmapperresultr populatorsrocCsdS)zcProduce row processing functions and append to the given set of populators lists. NrZ)rurrrrrrrrZrZr`create_row_processors z#MapperProperty.create_row_processorzInstanceState[Any]r8zSet[InstanceState[Any]]z.Optional[Callable[[InstanceState[Any]], bool]]zGIterator[Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]])type_statedict_visited_stateshalt_onrocCstdS)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. rZ)iter)rurrrrrrZrZr`cascade_iteratorszMapperProperty.cascade_iterator)rrrocCs ||_dS)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)rurrrZrZr` set_parentszMapperProperty.set_parentrrocCsdS)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). NrZrurrZrZr`instrument_classszMapperProperty.instrument_classzOptional[_AttributeOptions])attribute_options_assume_readonly_dc_attributesrocCsDd|_d|_|rt}nt}|r4||kr4d|_||_n d|_||_dS)NFT)rr#_DEFAULT_READONLY_ATTRIBUTE_OPTIONS_DEFAULT_ATTRIBUTE_OPTIONSrr)rurrZ default_attrsrZrZr`__init__,s zMapperProperty.__init__cCsd|_|d|_dS)zCalled after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps. TN)rdo_initrrtrZrZr`r@szMapperProperty.initzInstrumentedAttribute[_T]cCst|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_r|rtrZrZr`class_attributeKszMapperProperty.class_attributecCsdS)zPerform subclass-specific initialization post-mapper-creation steps. This is a template method called by the ``MapperProperty`` object's init() method. NrZrtrZrZr`reszMapperProperty.do_initcCsdS)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. NrZrrZrZr`post_instrument_classnsz$MapperProperty.post_instrument_classrFzDict[Any, object]z#Dict[_IdentityKeyType[Any], object]) session source_state source_dict dest_state dest_dictload _recursive_resolve_conflict_maproc CsdS)zoMerge the attribute represented by this ``MapperProperty`` from source to destination object. NrZ) rurrrrrrrrrZrZr`merge}s zMapperProperty.mergecCsd|jjt|t|ddfS)Nz<%s at 0x%x; %s>r|zno key) __class__r\idrrtrZrZr`__repr__s  zMapperProperty.__repr__)N)NF)r\r]r^rr_r,ZExtendedInternalTraversalZdp_has_cache_keyZ dp_stringrrlrZcascadeZ is_propertyZ_is_relationshiprrrrrrrrrrrrrrrZrZrZr`rrs@       rc@seZdZUdZdZdZded<ded<ded <dKd ddd d dZej ddddZ ddddZ dddddZ dddddZ ejd dd!d"ZdLd#dd$d%d&d'Zejd(dd)d*Zejd+dd,d-Zeddddd.d/d0Zeddddd1d2d3Zedddd4d5d6ZeejeZeejeZeejeZejrnd7ddd$d8d9d:Zd7ddd$d8d;d<Z d=dd>d?d@Z!dAdBdCdDdEZ"dMd#ddFd%dGdHZ#dNd#ddFd%dIdJZ$d S)OPropComparatora 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_entityZorm_prop_comparatorz_InternalEntityType[Any]rzOptional[AliasedInsp[Any]]rz,RODescriptorReference[MapperProperty[_T_co]]rNzMapperProperty[_T])r parentmapperadapt_to_entitycCs||_|p ||_||_dSrpr)rurrrrZrZr`rs zPropComparator.__init__zMapperProperty[_T_co]rncCs|jS)zReturn the :class:`.MapperProperty` associated with this :class:`.PropComparator`. Return values here will commonly be instances of :class:`.ColumnProperty` or :class:`.Relationship`. )rrtrZrZr`rs zPropComparator.propertyzroles.ColumnsClauseRolecCstd|dS)Nz%rrrtrZrZr`__clause_element__sz!PropComparator.__clause_element__rz(Sequence[Tuple[_DMLColumnArgument, Any]])valuerocCstd||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. rN)rr)rurrZrZr`_bulk_update_tuples s z"PropComparator._bulk_update_tupleszAliasedInsp[Any]zPropComparator[_T_co])rrocCs||j|j|S)zReturn a copy of this PropComparator which will use the given :class:`.AliasedInsp` to produce corresponding expressions. )rrr)rurrZrZr`rszPropComparator.adapt_to_entityrcCs|jjS)zZlegacy; this is renamed to _parententity to be compatible with QueryableAttribute.)rrrtrZrZr` _parentmapperszPropComparator._parentmapperz)Optional[_ColumnExpressionArgument[bool]]zColumnElement[Any]) criterionrrocKs|jjj|f|Srp)rr_criterion_existsrurrrZrZr`r%sz PropComparator._criterion_existszOptional[_ORMAdapterProto]cCs|jdkrdS|jjSdS)zrProduce a callable that adapts column expressions to suit an aliased version of this comparator. N)rZ_orm_adapt_elementrtrZrZr`r,s zPropComparator.adapterrOcCs|jjSrp)rrrtrZrZr`r7szPropComparator.info)abrrocKs|j|f|Srp)any)rrrrZrZr`_any_op;szPropComparator._any_op)leftotherrrocKs|j|f|Srp)has)rrrrZrZr`_has_op?szPropComparator._has_op)rrrocCs ||Srp)of_type)rrrZrZr` _of_type_opCszPropComparator._of_type_oprP)oprrrocOsdSrprZrurrrrZrZr`operateMszPropComparator.operatecKsdSrprZrrZrZr`reverse_operateQszPropComparator.reverse_operatez_EntityType[Any])rrocCs|tj|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` )rr of_type_op)rurrZrZr`rUszPropComparator.of_typez_ColumnExpressionArgument[bool]zPropComparator[bool])criteriarocGs|jtjf|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` )rr*and_)rurrZrZr`rpszPropComparator.and_zColumnElement[bool]cKs|jtj|f|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. )rrany_oprrZrZr`rszPropComparator.anycKs|jtj|f|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. )rrhas_oprrZrZr`rszPropComparator.has)N)N)N)N)%r\r]r^rr_Z__visit_name__rlrr)Znon_memoized_propertyrrrrZro_non_memoized_propertyrrrr staticmethodrrrrr*rPrrrtypingrrrrrrrrZrZrZr`rsN Q        rc @seZdZUdZdZdZded<ded<ded <d d d d Zdd ddZddddddZ dddddZ dddddddd d!Z dddd"d#dd$dd%d&d'Z dd d(d)Z d"dd*d+d,ZeeZd-ed.<edd/d0d1d2Zed3dd4d5d6d7Zd8S)9StrategizedPropertyaA 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. ) _strategiesstrategyZ_wildcard_token_default_path_loader_key strategy_keyTz ClassVar[str]strategy_wildcard_key _StrategyKeyr z"Dict[_StrategyKey, LoaderStrategy]r z Tuple[str]rncCs|jdtjfS)N:)r rZ_WILDCARD_TOKENrtrZrZr`_memoized_attr__wildcard_tokensz2StrategizedProperty._memoized_attr__wildcard_tokenzTuple[str, Tuple[str]]cCsd|jdtjffS)Nloaderr)r rZ_DEFAULT_TOKENrtrZrZr`'_memoized_attr__default_path_loader_keysz;StrategizedProperty._memoized_attr__default_path_loader_keyr>rDOptional[_LoadElement])rrrocCs>d}||}|j|j|jfD]}||jkr|j|}q:q|Srp)Z _loader_keyZ_wildcard_path_loader_keyr  attributes)rurrr search_pathZpath_keyrZrZr`_get_context_loaders   z'StrategizedProperty._get_context_loaderLoaderStrategyrcCsJz |j|WStk r YnX|j|f|}||||j|<}|Srp)r KeyError_strategy_lookup)rur|rqr rZrZr` _get_strategys z!StrategizedProperty._get_strategyr=rrrxrcKsD|||}|r$|jr$||j}n|j}|j|||||f|dSrp)rr r setup_query)rurrrrrrstratrZrZr`rs  zStrategizedProperty.setuprrrBrc CsF|||}|r$|jr$||j} n|j} | ||||||||dSrp)rr rr) rurrrrrrrrrrZrZr`r!s  z(StrategizedProperty.create_row_processorcCsi|_||j|_dSrp)r rr r rtrZrZr`r;szStrategizedProperty.do_initrcCs&|jjs"|j|js"|j|dSrp)rZ non_primaryZ class_managerZ_attr_has_implr|r init_class_attributerrZrZr`r?s  z)StrategizedProperty.post_instrument_classz\collections.defaultdict[Type[MapperProperty[Any]], Dict[_StrategyKey, Type[LoaderStrategy]]]_all_strategieszCallable[[_TLS], _TLS])rroc sdddfdd }|S)NrW)dec_clsrocs>d|jkrg|_tt}|j|<|j||S)N_strategy_keys)__dict__r tuplesorteditemsrappend)rr|rqrrZr`decorateLs   z2StrategizedProperty.strategy_for..decoraterZ)rqrr'rZr&r` strategy_forJs z StrategizedProperty.strategy_forMapperProperty[Any]rX)requesting_propertyr|roc Gs|jj|jD]N}||jkrtr.t|ts.t|j|}z||WStk rZYqXq|j D] \}}||krh|}||}qqhd}d}t |||||dSrp) rZ_with_polymorphic_mappers__mro__rr issubclassrrrr$orm_excZLoaderStrategyException) rqr*r|Zprop_clsZ strategiesZ property_typeZstratsZintended_property_typeZactual_strategyrZrZr`rXs0   z$StrategizedProperty._strategy_lookupN)r\r]r^rr_Z inherit_cacherlrrrrrrrr collections defaultdictdictrrr(rrZrZrZr`rs(    rc@sBeZdZdZdZdZdZdZdZdZ dZ dZ ddddddZ dS) 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 rZFr?)r uncached_optrocCs|dk r |S|SdS)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 NrZ)rurr2rZrZr`'_adapt_cached_option_to_uncached_options'z1ORMOption._adapt_cached_option_to_uncached_optionN) r\r]r^rr__is_legacy_optionpropagate_to_loadersZ_is_core_is_user_defined_is_compile_state_is_criteria_optionZ_is_strategy_optionr3rZrZrZr`r1zs r1c@s:eZdZdZdZdZdddddZdd dd d d Zd S)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 rZTr>rx) compile_staterocCsdS)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. NrZ)rur:rZrZr`process_compile_statesz(CompileStateOption.process_compile_stateSequence[_MapperEntity]r:mapper_entitiesrocCsdS)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 NrZrur:r>rZrZr`'process_compile_state_replaced_entitiessz:CompileStateOption.process_compile_state_replaced_entitiesN)r\r]r^rr_r7r;r@rZrZrZr`r9s  r9c@s&eZdZdZdZddddddZd S) LoaderOptionzhDescribe a loader modification to an ORM statement at compilation time. .. versionadded:: 1.4 rZr>r<rxr=cCs||dSrp)r;r?rZrZr`r@ sz4LoaderOption.process_compile_state_replaced_entitiesN)r\r]r^rr_r@rZrZrZr`rAsrAc@s(eZdZdZdZdZdddddZd S) CriteriaOptionztDescribe a WHERE criteria modification to an ORM statement at compilation time. .. versionadded:: 1.4 rZTzDict[str, Any]rx)rrocCsdS)z_update additional entity criteria options in the given attributes dictionary. NrZ)rurrZrZr`get_global_criteriasz"CriteriaOption.get_global_criteriaN)r\r]r^rr_r8rCrZrZrZr`rBsrBc@s0eZdZdZdZdZdZdZd ddddZdS) UserDefinedOptionz~Base class for a user-defined option that can be consumed from the :meth:`.SessionEvents.do_orm_execute` event hook. payloadFTNrcCs ||_dSrprE)rurFrZrZr`r8szUserDefinedOption.__init__)N) r\r]r^rr_r4r6r5rrZrZrZr`rD%s rDz1.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@s<eZdZdZdZdZdZddddd Zdddd d Zd S) MapperOptionz"Describe a modification to a QueryrZTFz Query[Any]rx)queryrocCsdS)z8Apply a modification to the given :class:`_query.Query`.NrZrurIrZrZr` process_queryTszMapperOption.process_querycCs||dS)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)rKrJrZrZr`process_query_conditionallyWs z(MapperOption.process_query_conditionallyN) r\r]r^rr_r4r5rKrLrZrZrZr`rH<s  rHc @seZdZUdZdZded<ddddd Zd d d d dZddddddd dddZddddd dddd d ddZ dddd Z d!S)"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_levelrr|r  strategy_optszClassVar[List[_StrategyKey]]r r)r)rr cCs4||_d|_|jj|_|jj|_||_t||_dS)NF)rMrNrr|r r0rO)rurr rZrZr`rs   zLoaderStrategy.__init__rrxrcCsdSrprZrrZrZr`rsz#LoaderStrategy.init_class_attributer>r=rDrrr)r:rrloadoptrrrocKsdS)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. NrZ)rur:rrrPrrrZrZr`rs zLoaderStrategy.setup_queryrrB) rrrrPrrrrroc CsdS)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. NrZ) rurrrrPrrrrrZrZr`rs z#LoaderStrategy.create_row_processorrerncCs t|jSrp)rerMrtrZrZr`__str__szLoaderStrategy.__str__N) r\r]r^rr_rlrrrrrQrZrZrZr`res   r)r __future__rr.rrrrrrrrr r r r r rrrrrrrrr-rbaserrrrrrrrr r!r"r#r$r%r'rr(r)sqlr*r+r,Zsql.baser-r.Z sql.cache_keyr/Z sql.operatorsr0Z sql.schemar1Z sql.type_apir2r3Z util.typingr4r5Z_typingr6r7r8r9r:rr;r<rr=r>r?Zdecl_apir@Z decl_baserAZloadingrBrrCrDrIrErrFrrGZstrategy_optionsrHrIrJZ engine.resultrKZ sql._typingrLrMrNrOrPZ sql.visitorsrQrRrrSrUrWZ StatementRolerYZColumnsClauseRoleZTypedColumnsClauseRolerarbZStrictFromClauseRolercrdrmrrrrrrZ_self_inspectsZ MemoizedSlotsrrrr1r9rArBrDZdeprecated_clsrHrrZrZrZr`s                                                                                      ,i   $'@P7