U ar@s dZddlmZddlZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZdZGdddejZ Gdddej!Z"Gdd d e"Z#Gd!d"d"ej$Z%ej&Gd#d$d$ee e ej'Z(ej&Gd%d&d&ej)Z*Gd'd(d(e(Z+Gd)d*d*eZ,Gd+d,d,e,Z-Gd-d.d.e,Z.Gd/d0d0e,Z/ej0d1d2dd3Gd4d5d5e,Z1Gd6d7d7e2Z3dS)8z 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. )absolute_importN)exc) path_registry)_MappedAttribute) EXT_CONTINUE)EXT_SKIP)EXT_STOP)InspectionAttr)InspectionAttrInfo) MANYTOMANY) MANYTOONE) NOT_EXTENSION) ONETOMANY)inspect) inspection)util) operators)roles)visitors)ExecutableOption) HasCacheKey) rr rrr r rLoaderStrategy MapperOption LoaderOptionMapperPropertyPropComparatorStrategizedPropertyc@seZdZdZdS)ORMStatementRolez?Executable SQL or text() construct, including ORM aware objectsN__name__ __module__ __qualname__Z _role_namer$r$ZC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\interfaces.pyr>src@seZdZdZdS)ORMColumnsClauseRolez7ORM mapped entity, aliased entity, or Column expressionNr r$r$r$r%r&Dsr&c@seZdZdZdS)ORMEntityColumnsClauseRolezORM mapped or aliased entityNr r$r$r$r%r'Hsr'c@seZdZdZdS)ORMFromClauseRolez5ORM mapped entity, aliased entity, or FROM expressionNr r$r$r$r%r(Lsr(c@seZdZdZdZdejjfdejjfgZ e Z dZ ddZ dd Zd d Zd!d dZddZddZddZddZeddZddZddZddZdd Zd S)"raRepresent 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:`.RelationshipProperty`. )_configure_started_configure_finishedparentkeyinfor+r,TcCsiS)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. .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also available on extension types via the :attr:`.InspectionAttrInfo.info` attribute, so that it can apply to a wider variety of ORM and extension constructs. .. seealso:: :attr:`.QueryableAttribute.info` :attr:`.SchemaItem.info` r$selfr$r$r%_memoized_attr_info{sz"MapperProperty._memoized_attr_infocKsdS)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$)r/context query_entitypathadapterkwargsr$r$r%setupszMapperProperty.setupcCsdS)zcProduce row processing functions and append to the given set of populators lists. Nr$)r/r1r2r3mapperresultr4 populatorsr$r$r%create_row_processorsz#MapperProperty.create_row_processorNcCstdS)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 RelationshipProperty. r$)iter)r/type_stateZdict_Zvisited_statesZhalt_onr$r$r%cascade_iteratorszMapperProperty.cascade_iteratorcCs ||_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+)r/r+initr$r$r% set_parentszMapperProperty.set_parentcCsdS)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$r/r7r$r$r%instrument_classszMapperProperty.instrument_classcCsd|_d|_dSNF)r)r*r.r$r$r%__init__szMapperProperty.__init__cCsd|_|d|_dS)zCalled after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps. TN)r)do_initr*r.r$r$r%r?szMapperProperty.initcCst|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 )getattrr+class_r,r.r$r$r%class_attributeszMapperProperty.class_attributecCsdS)zPerform subclass-specific initialization post-mapper-creation steps. This is a template method called by the ``MapperProperty`` object's init() method. Nr$r.r$r$r%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. Nr$rAr$r$r%post_instrument_classsz$MapperProperty.post_instrument_classc CsdS)zoMerge the attribute represented by this ``MapperProperty`` from source to destination object. Nr$) r/sessionZ source_stateZ source_dictZ dest_stateZ dest_dictload _recursiveZ_resolve_conflict_mapr$r$r%merges zMapperProperty.mergecCsd|jjt|t|ddfS)Nz<%s at 0x%x; %s>r,zno key) __class__r!idrFr.r$r$r%__repr__#s  zMapperProperty.__repr__)N)r!r"r#__doc__ __slots__rZExtendedInternalTraversalZdp_has_cache_keyZ dp_stringZ_cache_key_traversal frozensetZcascadeZ is_propertyr0r6r:r>r@rBrDr?propertyrHrErIrMrPr$r$r$r%rPs,          rc@seZdZdZdZdZd#ddZddZd d Zd d Z e d dZ e ddZ e ddZ e ddZeddZeddZeddZddZddZd$dd Zd%d!d"ZdS)&raU Defines SQL operators for :class:`.MapperProperty` objects. 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:`.RelationshipProperty`, and :class:`.CompositeProperty`. .. note:: With the advent of Hybrid properties introduced in SQLAlchemy 0.7, as well as Core-level operator redefinition in SQLAlchemy 0.8, the use case for user-defined :class:`.PropComparator` instances is extremely rare. See :ref:`hybrids_toplevel` as well as :ref:`types_operators`. 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,\ CompositeProperty,\ RelationshipProperty class MyColumnComparator(ColumnProperty.Comparator): def __eq__(self, other): return self.__clause_element__() == other class MyRelationshipComparator(RelationshipProperty.Comparator): def any(self, expression): "define the 'any' operation" # ... class MyCompositeComparator(CompositeProperty.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:`.RelationshipProperty.Comparator` :class:`.CompositeProperty.Comparator` :class:`.ColumnOperators` :ref:`types_operators` :attr:`.TypeEngine.comparator_factory` proprT _parententity_adapt_to_entityZorm_prop_comparatorNcCs ||_|_|p||_||_dSNrU)r/rVZ parentmapperadapt_to_entityr$r$r%rDs  zPropComparator.__init__cCstd|dS)Nz%r)NotImplementedErrorr.r$r$r%__clause_element__sz!PropComparator.__clause_element__cCs||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. )r\)r/valuer$r$r%_bulk_update_tupless z"PropComparator._bulk_update_tuplescCs||j|j|S)zReturn a copy of this PropComparator which will use the given :class:`.AliasedInsp` to produce corresponding expressions. )rNrVrW)r/rZr$r$r%rZszPropComparator.adapt_to_entitycCs t|jjS)zZlegacy; this is renamed to _parententity to be compatible with QueryableAttribute.)rrWr7r.r$r$r% _parentmapperszPropComparator._parentmappercCstd|jdS)NZorm)Zcompile_state_pluginZplugin_subject)rZ immutabledictr_r.r$r$r%_propagate_attrss zPropComparator._propagate_attrscCs|jdkrdS|jjSdS)zrProduce a callable that adapts column expressions to suit an aliased version of this comparator. N)rXZ_adapt_elementr.r$r$r%r4s zPropComparator.adaptercCs|jjSrY)rTr-r.r$r$r%r-szPropComparator.infocKs|j|f|SrY)anyabr5r$r$r%any_opszPropComparator.any_opcKs|j|f|SrY)hasrbr$r$r%has_opszPropComparator.has_opcCs ||SrY)of_type)rcrGr$r$r% of_type_opszPropComparator.of_type_opcCs|tj|S)aRedefine this object in terms of a polymorphic subclass, :func:`.with_polymorphic` construct, or :func:`.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:`inheritance_of_type` )operaterri)r/rGr$r$r%rhszPropComparator.of_typecGs|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` )rjrand_)r/Zcriteriar$r$r%rkszPropComparator.and_cKs|jtj|f|S)aReturn true if this collection contains any member that meets the given criterion. The usual implementation of ``any()`` is :meth:`.RelationshipProperty.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. )rjrrer/Z criterionr5r$r$r%raszPropComparator.anycKs|jtj|f|S)aReturn true if this element references a member which meets the given criterion. The usual implementation of ``has()`` is :meth:`.RelationshipProperty.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. )rjrrgrlr$r$r%rfszPropComparator.has)N)N)N)r!r"r#rQrRZ__visit_name__rDr\r^rZrTr_r`r4r- staticmethodrergrirhrkrarfr$r$r$r%r+s4W          rc@s~eZdZdZdZdZdZddZddZd d Z d d Z d dZ ddZ ddZ ddZeeZeddZeddZdS)raA 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_keyTNcCsd|jtjffS)N%s:%s)strategy_wildcard_keyrZ_WILDCARD_TOKENr.r$r$r%_memoized_attr__wildcard_tokenEs z2StrategizedProperty._memoized_attr__wildcard_tokencCsdd|jtjfffS)Nloaderrq)rrrZ_DEFAULT_TOKENr.r$r$r%'_memoized_attr__default_path_loader_keyKs  z;StrategizedProperty._memoized_attr__default_path_loader_keycCs>d}||}|j|j|jfD]}||jkr|j|}q:q|SrY)Z _loader_keyZ_wildcard_path_loader_keyrp attributes)r/r1r3rK search_pathZpath_keyr$r$r%_get_context_loaderTs  z'StrategizedProperty._get_context_loadercCsJz |j|WStk r YnX|j|f|}||||j|<}|SrY)rnKeyError_strategy_lookup)r/r,clsror$r$r% _get_strategyfs z!StrategizedProperty._get_strategycKsD|||}|r$|jr$||j}n|j}|j|||||f|dSrY)rxror| setup_query)r/r1r2r3r4r5rtstratr$r$r%r6ts  zStrategizedProperty.setupc CsF|||}|r$|jr$||j} n|j} | ||||||||dSrY)rxror|r:) r/r1r2r3r7r8r4r9rtr~r$r$r%r:~s  z(StrategizedProperty.create_row_processorcCsi|_||j|_dSrY)rnr| strategy_keyror.r$r$r%rEszStrategizedProperty.do_initcCs&|jjs"|j|js"|j|dSrY)r+Z non_primaryZ class_managerZ_attr_has_implr,roinit_class_attributerAr$r$r%rIs  z)StrategizedProperty.post_instrument_classc sfdd}|S)Ncs>d|jkrg|_tt}|j|<|j||S)N_strategy_keys)__dict__rtuplesorteditems_all_strategiesappend)Zdec_clsr,r{kwr$r%decorates   z2StrategizedProperty.strategy_for..decorater$)r{rrr$rr% strategy_fors z StrategizedProperty.strategy_forc Gs|jj|jD]<}||jkr|j|}z||WStk rHYqXq|jD] \}}||krV|}||}qqVd}d}t|||||dSrY)r+Z_with_polymorphic_mappers__mro__rryrorm_excZLoaderStrategyException) r{Zrequesting_propertyr,Zprop_clsZ strategiesZ property_typeZstratsZintended_property_typeZactual_strategyr$r$r%rzs,   z$StrategizedProperty._strategy_lookup)r!r"r#rQrRZ inherit_cacherrrsrurxr|r6r:rErI collections defaultdictdictr classmethodrrzr$r$r$r%r+s"    rc@s$eZdZdZdZdZdZdZdZdS) 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$FN) r!r"r#rQrR_is_legacy_optionpropagate_to_loaders_is_compile_state_is_criteria_optionr$r$r$r%rs  rc@s$eZdZdZdZddZddZdS)rzhDescribe a loader modification to an ORM statement at compilation time. .. versionadded:: 1.4 TcCs||dS)zApply a modification to a given :class:`.CompileState`, given entities that were replaced by with_only_columns() or with_entities(). .. versionadded:: 1.4.19 N)process_compile_state)r/ compile_stateZmapper_entitiesr$r$r%'process_compile_state_replaced_entitiess z4LoaderOption.process_compile_state_replaced_entitiescCsdSz7Apply a modification to a given :class:`.CompileState`.Nr$r/rr$r$r%rsz"LoaderOption.process_compile_stateN)r!r"r#rQrrrr$r$r$r%rs rc@s(eZdZdZdZdZddZddZdS)CriteriaOptionztDescribe a WHERE criteria modification to an ORM statement at compilation time. .. versionadded:: 1.4 TcCsdSrr$rr$r$r%r sz$CriteriaOption.process_compile_statecCsdS)z_update additional entity criteria options in the given attributes dictionary. Nr$)r/rvr$r$r%get_global_criteriasz"CriteriaOption.get_global_criteriaN)r!r"r#rQrrrrr$r$r$r%rs rc@s"eZdZdZdZdZdddZdS)UserDefinedOptionz~Base class for a user-defined option that can be consumed from the :meth:`.SessionEvents.do_orm_execute` event hook. FNcCs ||_dSrY)payload)r/rr$r$r%rD%szUserDefinedOption.__init__)N)r!r"r#rQrrrDr$r$r$r%rsrz1.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(eZdZdZdZdZddZddZdS) rz"Describe a modification to a QueryTFcCsdS)z8Apply a modification to the given :class:`_query.Query`.Nr$r/queryr$r$r% process_query?szMapperOption.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)rrr$r$r%process_query_conditionallyBs z(MapperOption.process_query_conditionallyN)r!r"r#rQrrrrr$r$r$r%r)s  rc@s<eZdZdZdZddZddZddZd d Zd d 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_levelr+r,r strategy_optscCs4||_d|_|jj|_|jj|_||_t||_dSrC)rrr+r,rrr)r/r+rr$r$r%rDqs   zLoaderStrategy.__init__cCsdSrYr$rAr$r$r%rysz#LoaderStrategy.init_class_attributecKsdS)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$)r/rr2r3loadoptr4r5r$r$r%r}|szLoaderStrategy.setup_queryc 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. Nr$) r/r1r2r3rr7r8r4r9r$r$r%r:s z#LoaderStrategy.create_row_processorcCs t|jSrY)strrr.r$r$r%__str__szLoaderStrategy.__str__N) r!r"r#rQrRrDrr}r:rr$r$r$r%rPs  r)4rQ __future__rrrrrbaserrrr r r r r rrrrrZsqlrrrZsql.baserZsql.traversalsr__all__Z StatementRolerZColumnsClauseRoler&r'ZStrictFromClauseRoler(Z_self_inspectsZ MemoizedSlotsrZColumnOperatorsrrrrrrZdeprecated_clsrobjectrr$r$r$r%sh                      [