iddZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd l m Z dd l m Z dd l mZdd l mZddl mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlmZddl!m"Z"ddl!mZ#ddl!m$Z$dd l%m&Z&dd!l'm(Z(dd"l)m*Z*gd#Z+ej,Z-ej.e j/Gd$d%e0Z1Gd&d'e*Z2Gd(d)e0Z3Gd*d+e3Z4ej.Gd,d-eZ5Gd.d/e3Z6Gd0d1e3Z7Gd2d3e0Z8Gd4d5ej9Z:d6S)7aThe Query class and support. Defines the :class:`_query.Query` class, the central construct used by the ORM to construct database queries. The :class:`_query.Query` class should not be confused with the :class:`_expression.Select` class, which defines database SELECT operations at the SQL (non-ORM) level. ``Query`` differs from ``Select`` in that it returns ORM-mapped objects and interacts with an ORM session, whereas the ``Select`` construct interacts directly with the database to return iterable result sets. )chain) attributes)exc) interfaces)loading) persistence) properties_entity_descriptor) _generative)_is_aliased_class)_is_mapped_class _orm_columns)InspectionAttr) PathRegistry)_entity_corresponds_to)aliased) AliasedClass)join) object_mapper) ORMAdapter) with_parent)inspect) inspection)log)sql)util) expression)visitors)ColumnCollection)_interpret_as_from) ForUpdateArg)Query QueryContextrc eZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZeZdZdZdZdZdZdZdZdZdZdZiZ dZ!dZ"e#j$xZ%Z&e#j$Z'e#j$Z(e#j$Z)dZ*dZ+dZ,dZ-dZ.e/Z0dZ1dZ2dZ3 ddZ4ddZ5dZ6d Z7d Z8d Z9d Z:d Z;e<dZ=e<dZ>dZ?dZ@dZAdZBeCdZDdZEdZFdZGddZHdZIdZJdZKddZLddZMdZNdZOd ZP dd!ZQd"ZReCd#ZSdd$ZTdd%ZUd&ZVd'ZWeCd(ZXd)ZYe<d*ZZeCd+Z[e<d,Z\d-Z]e<d.Z^e<d/Z_eCd0Z`e<d1ZaeZpe<d?Zqe<d@ZrdAZsesZtdBZue<dCZve<dDZwe#jxdEdFddGZydHZzdIZ{e<dJZ|dKZ}e<ddMZ~ddNZdOZe<dPZe<e#jdQdRdSZe< ddTZe<dUZe>|H-- * *tS))))  ( ( 8 8 8 8 8 >r2c |jx|_}|D]}|jD]}||vrt|}|js_|jjrS|jj|jvr=| |jtj |j |jj d}n|jr|j}nd}||f||<|j||dSN)_mapper_adapter_mapcopyr/ris_aliased_classmapperwith_polymorphicpersist_selectabler,"_mapper_loads_polymorphically_withsql_util ColumnAdapter selectable_equivalent_columns_adapter setup_entity)r.r/dr;entityext_infoaliased_adapters r0r9zQuery._set_entity_selectabless'+'?'D'D'F'FF 1 - -C, - -??&vH$5/$O</ %O>#'#=>>!CC ( ( 6$,$7$,O$G!"!"+/!2/*2*;*.!)? ;AfI  !F),,,3 - - -r2c|jp|gD]2}||j|<|D]}||j|j<3dSr=)_with_polymorphic_mappersr,iterate_to_root local_table)r.rAadapterm2ms r0rDz(Query._mapper_loads_polymorphically_withsk2>vh D DB-4D &r *'')) D D>0'~~//H!1(0% (####r  1DN##q((,j.>??)&&((F#+#9q!6$$D   1DN##q((h'')%)$(=D  1 1((((((r2c|jD]T}|j|d|D]"}|j|jd#UdSr=)rPr,poprQrR)r.rArTrUs r0_reset_polymorphic_adapterz Query._reset_polymorphic_adapter7s|2 D DB  & * *2t 4 4 4'')) D D*..q}dCCCC D D Dr2chd|jvr?|jd}|j|d}|r||St |t jr|}nt|dr|j}ndS|j|d}|r||SdS)N parententitytable) _annotationsr,get adapt_clauser^r! FromClauserWrt)r.elementsearchr`s r0_adapt_polymorphic_elementz Query._adapt_polymorphic_element=s W1 1 1).9F.2264@@E 3))'222 gz4 5 5 FF Wg & & ]FF4*..vt<<  /%%g.. . / /r2c fd|DS)Ncbg|]+}tj|dd,ST) _adapt_clauser!_literal_as_label_reference).0or.s r0 z)Query._adapt_col_list..PsM      6q994     r2r))r.colss` r0_adapt_col_listzQuery._adapt_col_listOs0         r2c||_dSr=)lazy_loaded_from)r.states r0_set_lazyload_fromzQuery._set_lazyload_fromWs %r2cd|_dSNF)_orm_only_adaptr.s r0_adapt_all_clauseszQuery._adapt_all_clauses[s$r2c^g|jsd}|r-|jr&|jD]}||jf|jr*|jr|nd|jjf|jr||jfs|Sfd}tj |i|S)z\Adapt incoming clauses to transformations which have been applied within this query.Fcfd|jvpd|jv}D]\}}|r|r||}||cSdS)N _orm_adaptrsru)elem is_orm_adapt _orm_onlyrSeadapterss r0replacez$Query._adapt_clause..replacesn 117!T%66 '/ ! !" 7 !L! A}   ! !r2) r_filter_aliasesr\rrf_orm_only_from_obj_aliasr,r{r"replacement_traverse)r.clause as_filterorm_onlyrirrs @r0rzQuery._adapt_clause_s# H  8- 8* 8 82: 67777    OO $ =HHH5(0     % I OOXt'FG H H H M ! ! ! ! !,VRAAAr2c|jdS)zReturn the first QueryEntity.rr5rs r0_query_entity_zerozQuery._query_entity_zeros~a  r2c&|jdjS)z8Return the Mapper associated with the first QueryEntity.r)r5rArs r0 _mapper_zerozQuery._mapper_zeros~a ''r2cP|j|jn|jS)zReturn the 'entity' (mapper or AliasedClass) associated with the first QueryEntity, or alternatively the 'select from' entity if specified.)rYr entity_zerors r0 _entity_zerozQuery._entity_zeros/'3  $ $((**6 r2c#PK|jD]}t|tr|VdSr=)r5r^ _MapperEntity)r.r;s r0_mapper_entitieszQuery._mapper_entitiess=>  C#}--    r2c\|jd|S)N_joinpoint_entity) _joinpointrvrrs r0_joinpoint_zerozQuery._joinpoint_zeros'""#68I8I8K8KLLLr2cl|}|t|}|js|jSdSr=)rris_clause_elementrA)r.ezeroinsps r0 _bind_mapperzQuery._bind_mappers<!!##  5>>D) #{"tr2cj|j|jgkrtjd|z|jjS)Nz4%s() can only be used against a single mapped class.)r5r6rZInvalidRequestErrorr)r.methnames r0_only_full_mapper_zerozQuery._only_full_mapper_zerosE >d23 3 3,)+34 #//r2ct|jdkrtj|pd|S)Nrz8This operation requires a Query against a single mapper.)rcr5rZrr)r. rationales r0_only_entity_zerozQuery._only_entity_zerosM t~   " ",++    """r2c\i}|jD]!}||jj"|Sr=)rupdaterArH)r.rmr;s r0 __all_equivszQuery.__all_equivss8( : :C MM#*8 9 9 9 9 r2c2|dddSNrvF)order_bydistinct)_no_criterion_conditionrs r0_get_conditionzQuery._get_conditions&++ EE,   r2c6|ddddSr)_no_criterion_assertionrs r0_get_existing_conditionzQuery._get_existing_conditions# $$UUU$KKKKKr2c|jsdS|j5|j.|js'|j |j|js|r|js |r|jrtj d|zdSdSNz>>,00$/;@@@$...r2c~|jsdS|jrtjd|z||dSr)rrrZrrr.rs r0_no_clauseelement_conditionz!Query._no_clauseelement_conditionsZ&  F > ,2489  $$T*****r2cT|jsdS|jtjd|zdS)Nz[Query.%s() being called on a Query with an existing full statement - can't apply criterion.)rrrZrrs r0_no_statement_conditionzQuery._no_statement_conditionsF&  F ? &,9   ' &r2cj|jsdS|j|jtjd|d|ddS)NzQuery.z() being called on a Query which already has LIMIT or OFFSET applied. To modify the row-limited results of a Query, call from_self() first. Otherwise, call z*() before limit() or offset() are applied.)rrrrZrrs r0_no_limit_offsetzQuery._no_limit_offsetsU&  F ; "dl&>,, #'$$ . '?&>r2cz|r||_|r||_|r||_|rt||_|r||_|Sr=)_populate_existing_version_check_refresh_stateset_only_load_props_refresh_identity_token)r.populate_existing version_checkonly_load_props refresh_stateidentity_tokens r0 _get_optionszQuery._get_options sa  8&7D #  0"/D   0"/D   9$'$8$8D !  :+9D ( r2cz|j}||}|j|_|Sr= __class____new____dict__r?)r.clsqs r0_clonez Query._clones4n KK  ]'')) r2c||jj}|jr||j}|S)zThe full SELECT statement represented by this Query. The statement by default will not have disambiguating labels applied to the construct unless with_labels(True) is called first. )labels)_compile_context _with_labels statement_paramsparams)r.stmts r0rzQuery.statement%sB$$D,=$>>H < -;;t|,,D r2c|d}|r|}|j}|r|}||S)aReturn the full SELECT statement represented by this :class:`_query.Query`, embedded within an :class:`_expression.Alias`. Eager JOIN generation within the query is disabled. :param name: string name to be assigned as the alias; this is passed through to :meth:`_expression.FromClause.alias`. If ``None``, a name will be deterministically generated at compile time. :param with_labels: if True, :meth:`.with_labels` will be called on the :class:`_query.Query` first to apply table-qualified labels to all columns. :param reduce_columns: if True, :meth:`_expression.Select.reduce_columns` will be called on the resulting :func:`_expression.select` construct, to remove same-named columns where one also refers to the other via foreign key or WHERE clause equivalence. F)name)enable_eagerloads with_labelsrreduce_columnsr`)r.rrrrs r0subqueryzQuery.subquery5s`.  " "5 ) )   A K  #  ""AwwDw!!!r2c`|dj||S)aFReturn the full SELECT statement represented by this :class:`_query.Query` represented as a common table expression (CTE). Parameters and usage are the same as those of the :meth:`_expression.SelectBase.cte` method; see that method for further details. Here is the `PostgreSQL WITH RECURSIVE example `_. Note that, in this example, the ``included_parts`` cte and the ``incl_alias`` alias of it are Core selectables, which means the columns are accessed via the ``.c.`` attribute. The ``parts_alias`` object is an :func:`_orm.aliased` instance of the ``Part`` entity, so column-mapped attributes are available directly:: from sqlalchemy.orm import aliased class Part(Base): __tablename__ = 'part' part = Column(String, primary_key=True) sub_part = Column(String, primary_key=True) quantity = Column(Integer) included_parts = session.query( Part.sub_part, Part.part, Part.quantity).\ filter(Part.part=="our part").\ cte(name="included_parts", recursive=True) incl_alias = aliased(included_parts, name="pr") parts_alias = aliased(Part, name="p") included_parts = included_parts.union_all( session.query( parts_alias.sub_part, parts_alias.part, parts_alias.quantity).\ filter(parts_alias.part==incl_alias.c.sub_part) ) q = session.query( included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ).\ group_by(included_parts.c.sub_part) .. seealso:: :meth:`_expression.HasCTE.cte` F)r recursive)rrcte)r.rrs r0rz Query.cteUs8n%%e,,6::;   r2c\|dj|S)zReturn the full SELECT statement represented by this :class:`_query.Query`, converted to a scalar subquery with a label of the given name. Analogous to :meth:`_expression.SelectBase.label`. F)rrlabel)r.rs r0rz Query.labels)%%e,,6<_; this is commonly used to disambiguate columns from multiple tables which have the same name. When the `Query` actually issues SQL to load rows, it always uses column labeling. .. note:: The :meth:`_query.Query.with_labels` method *only* applies the output of :attr:`_query.Query.statement`, and *not* to any of the result-row invoking systems of :class:`_query.Query` itself, e.g. :meth:`_query.Query.first`, :meth:`_query.Query.all`, etc. To execute a query using :meth:`_query.Query.with_labels`, invoke the :attr:`_query.Query.statement` using :meth:`.Session.execute`:: result = session.execute(query.with_labels().statement) TN)rrs r0rzQuery.with_labelss2!r2c||_dS)aControl whether assertions are generated. When set to False, the returned Query will not assert its state before certain operations, including that LIMIT/OFFSET has not been applied when filter() is called, no criterion exists when get() is called, and no "from_statement()" exists when filter()/order_by()/group_by() etc. is called. This more permissive mode is used by custom Query subclasses to specify criterion or other modifiers outside of the usual usage patterns. Care should be taken to ensure that the usage pattern is even possible. A statement applied by from_statement() will override any criterion set by filter() or order_by(), for example. N)rr s r0enable_assertionszQuery.enable_assertionss(#(r2c|jS)zA readonly attribute which returns the current WHERE criterion for this Query. This returned value is a SQL expression construct, or ``None`` if no criterion has been established. )rrs r0 whereclausezQuery.whereclause%s r2c||_dS)aIndicate that this query applies to objects loaded within a certain path. Used by deferred loaders (see strategies.py) which transfer query options from an originating query to a newly generated query intended for the deferred load. N) _current_path)r.paths r0_with_current_pathzQuery._with_current_path0s"r2c|jstjd|jd}|g|jddz|_|||||dS)aLoad columns for inheriting classes. :meth:`_query.Query.with_polymorphic` applies transformations to the "main" mapped class represented by this :class:`_query.Query`. The "main" mapped class here means the :class:`_query.Query` object's first argument is a full class, i.e. ``session.query(SomeClass)``. These transformations allow additional tables to be present in the FROM clause so that columns for a joined-inheritance subclass are available in the query, both for the purposes of load-time efficiency as well as the ability to use these columns at query time. See the documentation section :ref:`with_polymorphic` for details on how this method is used. z(No primary mapper set up for this Query.rrN)rGpolymorphic_on)r6rZrr5rset_with_polymorphic)r.cls_or_mappersrGrrLs r0rBzQuery.with_polymorphic<s*# ,: "))++ DN122$66##  !) $     r2cX||_|jd|d|_dS)a Yield only ``count`` rows at a time. The purpose of this method is when fetching very large result sets (> 10K rows), to batch results in sub-collections and yield them out partially, so that the Python interpreter doesn't need to declare very large areas of memory which is both time consuming and leads to excessive memory use. The performance from fetching hundreds of thousands of rows can often double when a suitable yield-per setting (e.g. approximately 1000) is used, even with DBAPIs that buffer rows (which are most). The :meth:`_query.Query.yield_per` method **is not compatible subqueryload eager loading or joinedload eager loading when using collections**. It is potentially compatible with "select in" eager loading, **provided the database driver supports multiple, independent cursors** (pysqlite and psycopg2 are known to work, MySQL and SQL Server ODBC drivers do not). Therefore in some cases, it may be helpful to disable eager loads, either unconditionally with :meth:`_query.Query.enable_eagerloads`:: q = sess.query(Object).yield_per(100).enable_eagerloads(False) Or more selectively using :func:`.lazyload`; such as with an asterisk to specify the default loader scheme:: q = sess.query(Object).yield_per(100).\ options(lazyload('*'), joinedload(Object.some_related)) .. warning:: Use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten. In particular, it's usually impossible to use this setting with eagerly loaded collections (i.e. any lazy='joined' or 'subquery') since those collections will be cleared for a new load when encountered in a subsequent result batch. In the case of 'subquery' loading, the full result for all rows is fetched which generally defeats the purpose of :meth:`~sqlalchemy.orm.query.Query.yield_per`. Also note that while :meth:`~sqlalchemy.orm.query.Query.yield_per` will set the ``stream_results`` execution option to True, currently this is only understood by :mod:`~sqlalchemy.dialects.postgresql.psycopg2`, :mod:`~sqlalchemy.dialects.mysql.mysqldb` and :mod:`~sqlalchemy.dialects.mysql.pymysql` dialects which will stream results using server side cursors instead of pre-buffer all rows for this query. Other DBAPIs **pre-buffer all rows** before making them available. The memory use of raw database rows is much less than that of an ORM-mapped object, but should still be taken into consideration when benchmarking. .. seealso:: :meth:`_query.Query.enable_eagerloads` T)stream_resultsmax_row_bufferN) _yield_per_execution_optionsunion)r.counts r0 yield_perzQuery.yield_per^s8B "&"9"?"?#u = =# # r2cB||tjS)aaReturn an instance based on the given primary key identifier, or ``None`` if not found. E.g.:: my_user = session.query(User).get(5) some_object = session.query(VersionedFoo).get((5, 10)) some_object = session.query(VersionedFoo).get( {"id": 5, "version_id": 10}) :meth:`_query.Query.get` is special in that it provides direct access to the identity map of the owning :class:`.Session`. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object. :meth:`_query.Query.get` also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. :meth:`_query.Query.get` is only used to return a single mapped instance, not multiple instances or individual column constructs, and strictly on a single primary key value. The originating :class:`_query.Query` must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading options via :meth:`_query.Query.options` may be applied however, and will be used if the object is not yet locally present. A lazy-loading, many-to-one attribute configured by :func:`_orm.relationship`, using a simple foreign-key-to-primary-key criterion, will also use an operation equivalent to :meth:`_query.Query.get` in order to retrieve the target value from the local identity map before querying the database. See :doc:`/orm/loading_relationships` for further details on relationship loading. :param ident: A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed. For a single-column primary key, the scalar calling form is typically the most expedient. If the primary key of a row is the value "5", the call looks like:: my_object = query.get(5) The tuple form contains primary key values typically in the order in which they correspond to the mapped :class:`_schema.Table` object's primary key columns, or if the :paramref:`_orm.Mapper.primary_key` configuration parameter were used, in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits "5, 10" the call would look like:: my_object = query.get((5, 10)) The dictionary form should include as keys the mapped attribute names corresponding to each element of the primary key. If the mapped class has the attributes ``id``, ``version_id`` as the attributes which store the object's primary key value, the call would look like:: my_object = query.get({"id": 5, "version_id": 10}) .. versionadded:: 1.3 the :meth:`_query.Query.get` method now optionally accepts a dictionary of attribute names to values in order to indicate a primary key identifier. :return: The object instance, or ``None``. ) _get_implrload_on_pk_identity)r.idents r0rvz Query.getsl~~eW%@AAAr2ch|||}tj|j|||S)aqLocate an object in the identity map. Given a primary key identity, constructs an identity key and then looks in the session's identity map. If present, the object may be run through unexpiration rules (e.g. load unloaded attributes, check if was deleted). For performance reasons, while the :class:`_query.Query` must be instantiated, it may be instantiated with no entities, and the mapper is passed:: obj = session.query()._identity_lookup(inspect(SomeClass), (1, )) :param mapper: mapper in use :param primary_key_identity: the primary key we are searching for, as a tuple. :param identity_token: identity token that should be used to create the identity key. Used as is, however overriding subclasses can repurpose this in order to interpret the value in a special way, such as if None then look among multiple target tokens. :param passive: passive load flag passed to :func:`.loading.get_from_identity`, which impacts the behavior if the object is found; the object may be validated and/or unexpired if the flag allows for SQL to be emitted. :param lazy_loaded_from: an :class:`.InstanceState` that is specifically asking for this identity as a related identity. Used for sharding schemes where there is a correspondence between an object and a related object being lazy-loaded (or otherwise relationship-loaded). .. versionadded:: 1.2.9 :return: None if the object is not found in the identity map, *or* if the object was unexpired and found to have been deleted. if passive flags disallow SQL and the object is expired, returns PASSIVE_NO_RESULT. In all other cases the instance is returned. .. versionadded:: 1.2.7 r)identity_key_from_primary_keyrget_from_identityr+)r.rAprimary_key_identityrpassiverkeys r0_identity_lookupzQuery._identity_lookups?b22 3  (vsGLLLr2c tdr|d}tt}|st jdtt|jkr9tj dd d|jDz|r tfd|j Dnd#t$rW}t jtj d d d |j Dz| Yd}~nd}~wwxYw|jsj|jsc|j\||| }|2|t+|j|jsdS|S|t0jurdS||S) N__composite_values__rvr=)defaultzmIncorrect number of values in identifier to formulate primary key for query.get(); primary key columns are %s,c3 K|] }d|zV dSz'%s'Nr)rcs r0 z"Query._get_impl..Cs&BB!6A:BBBBBBr2c32K|]}|jVdSr=r3)rpropr1s r0r=z"Query._get_impl..Hs>,,)2,,,,,,r2ztIncorrect names of values in identifier to formulate primary key for query.get(); primary key attribute names are %sc3*K|]}d|jzVdSr:r?)rr@s r0r=z"Query._get_impl..Ss=## $#TX-######r2replace_contextr.)rWr6rr^dictr r8rc primary_keyrZrrlist_identity_key_propsKeyErrorraise_ralways_refresh_for_update_argr4r issubclassrclass_rPASSIVE_CLASS_MISMATCH)r.r1 db_load_fnrrAis_dicterrinstances ` r0r*zQuery._get_impl2sm ')? @ @ O#7#L#L#N#N ,,U331488 #'<$g$$$  # $ $F,>(?(? ? ?,J((BBv/ABBBBBC    '+,,,, & :,,,(($$     .'((##(.(B###%(          ' ) $,,,,^-H#,,..."("4fmDD 4Z>>>tz$ 4555s C** E 4A EE c|D]c}|!|jdg|_%|jtjt ||_ddS)a@Return a :class:`.Query` construct which will correlate the given FROM clauses to that of an enclosing :class:`.Query` or :func:`~.expression.select`. The method here accepts mapped classes, :func:`.aliased` constructs, and :func:`.mapper` constructs as arguments, which are resolved into expression constructs, in addition to appropriate expression constructs. The correlation arguments are ultimately passed to :meth:`_expression.Select.correlate` after coercion to expression constructs. The correlation arguments take effect in such cases as when :meth:`_query.Query.from_self` is used, or when a subquery as returned by :meth:`_query.Query.subquery` is embedded in another :func:`_expression.select` construct. N) _correlater&rEsurface_selectablesr$)r.argsss r0 correlatezQuery.correlateqso,  Ay"&/"7"7"?"?"&/"7"701CA1F1FGG##   r2c||_dS)a%Return a Query with a specific 'autoflush' setting. Note that a Session with autoflush=False will not autoflush, even if this flag is set to True at the Query level. Therefore this flag is usually used only to disable autoflush for a specific Query. N) _autoflush)r.settings r0 autoflushzQuery.autoflushs"r2cd|_dS)ajReturn a :class:`_query.Query` that will expire and refresh all instances as they are loaded, or reused from the current :class:`.Session`. :meth:`.populate_existing` does not improve behavior when the ORM is used normally - the :class:`.Session` object's usual behavior of maintaining a transaction and expiring all attributes after rollback or commit handles object state automatically. This method is not intended for general use. .. seealso:: :ref:`session_expire` - in the ORM :class:`_orm.Session` documentation TN)rrs r0rzQuery.populate_existings$#'r2c||_dS)zSet the 'invoke all eagers' flag which causes joined- and subquery loaders to traverse into already-loaded related objects and collections. Default is that of :attr:`_query.Query._invoke_all_eagers`. N)_invoke_all_eagersr s r0_with_invoke_all_eagerszQuery._with_invoke_all_eagerss#(r2c|rt|}n|}|yt|}|jD].}t |t jr|j|jur|}n5/tj d|jj j d|j j d| t|||jS)a4Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established :func:`_orm.relationship()` configuration. The method uses the :func:`.with_parent` function to generate the clause, the result of which is passed to :meth:`_query.Query.filter`. Parameters are the same as :func:`.with_parent`, with the exception that the given property can be None, in which case a search is performed against this :class:`_query.Query` object's target mapper. :param instance: An instance which has some :func:`_orm.relationship`. :param property: String property name, or class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship. :param from_entity: Entity in which to consider as the left side. This defaults to the "zero" entity of the :class:`_query.Query` itself. Nz>Could not locate a property which relates instances of class 'z' to instances of class '')rrriterate_propertiesr^r RelationshipPropertyrArZrrM__name__rfilterrrL)r.rRproperty from_entityrrAr@s r0rzQuery.with_parents8  .!+..KK++--K  "8,,F1  tZ%DEE {'999#HE00$*1::: *333 {{;x;;MNNOOOr2c|t||}t|j|_t||}||gdS)zIadd a mapped entity to the list of result columns to be returned.N)rrFr5rr9)r.rLr`rUs r0 add_entityzQuery.add_entitysU  VU++Fdn-- $ ' ' $$aS)))))r2c||_dS)aReturn a :class:`_query.Query` that will use the given :class:`.Session`. While the :class:`_query.Query` object is normally instantiated using the :meth:`.Session.query` method, it is legal to build the :class:`_query.Query` directly without necessarily using a :class:`.Session`. Such a :class:`_query.Query` object, or any :class:`_query.Query` already associated with a different :class:`.Session`, can produce a new :class:`_query.Query` object associated with a target session using this method:: from sqlalchemy.orm import Query query = Query([MyClass]).filter(MyClass.id == 5) result = query.with_session(my_session).one() N)r+)r.r+s r0 with_sessionzQuery.with_sessions0 r2c|djd}||}d|_||_|r|||S)aSreturn a Query that selects from this Query's SELECT statement. :meth:`_query.Query.from_self` essentially turns the SELECT statement into a SELECT of itself. Given a query such as:: q = session.query(User).filter(User.name.like('e%')) Given the :meth:`_query.Query.from_self` version:: q = session.query(User).filter(User.name.like('e%')).from_self() This query renders as: .. sourcecode:: sql SELECT anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1) AS anon_1 There are lots of cases where :meth:`_query.Query.from_self` may be useful. A simple one is where above, we may want to apply a row LIMIT to the set of user objects we query against, and then apply additional joins against that row-limited set:: q = session.query(User).filter(User.name.like('e%')).\ limit(5).from_self().\ join(User.addresses).filter(Address.email.like('q%')) The above query joins to the ``Address`` entity but only against the first five results of the ``User`` query: .. sourcecode:: sql SELECT anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1 LIMIT :param_1) AS anon_1 JOIN address ON anon_1.user_id = address.user_id WHERE address.email LIKE :email_1 **Automatic Aliasing** Another key behavior of :meth:`_query.Query.from_self` is that it applies **automatic aliasing** to the entities inside the subquery, when they are referenced on the outside. Above, if we continue to refer to the ``User`` entity without any additional aliasing applied to it, those references wil be in terms of the subquery:: q = session.query(User).filter(User.name.like('e%')).\ limit(5).from_self().\ join(User.addresses).filter(Address.email.like('q%')).\ order_by(User.name) The ORDER BY against ``User.name`` is aliased to be in terms of the inner subquery: .. sourcecode:: sql SELECT anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1 LIMIT :param_1) AS anon_1 JOIN address ON anon_1.user_id = address.user_id WHERE address.email LIKE :email_1 ORDER BY anon_1.user_name The automatic aliasing feature only works in a **limited** way, for simple filters and orderings. More ambitious constructions such as referring to the entity in joins should prefer to use explicit subquery objects, typically making use of the :meth:`_query.Query.subquery` method to produce an explicit subquery object. Always test the structure of queries by viewing the SQL to ensure a particular structure does what's expected! **Changing the Entities** :meth:`_query.Query.from_self` also includes the ability to modify what columns are being queried. In our example, we want ``User.id`` to be queried by the inner query, so that we can join to the ``Address`` entity on the outside, but we only wanted the outer query to return the ``Address.email`` column:: q = session.query(User).filter(User.name.like('e%')).\ limit(5).from_self(Address.email).\ join(User.addresses).filter(Address.email.like('q%')) yielding: .. sourcecode:: sql SELECT address.email AS address_email FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1 LIMIT :param_1) AS anon_1 JOIN address ON anon_1.user_id = address.user_id WHERE address.email LIKE :email_1 **Looking out for Inner / Outer Columns** Keep in mind that when referring to columns that originate from inside the subquery, we need to ensure they are present in the columns clause of the subquery itself; this is an ordinary aspect of SQL. For example, if we wanted to load from a joined entity inside the subquery using :func:`.contains_eager`, we need to add those columns. Below illustrates a join of ``Address`` to ``User``, then a subquery, and then we'd like :func:`.contains_eager` to access the ``User`` columns:: q = session.query(Address).join(Address.user).\ filter(User.name.like('e%')) q = q.add_entity(User).from_self().\ options(contains_eager(Address.user)) We use :meth:`_query.Query.add_entity` above **before** we call :meth:`_query.Query.from_self` so that the ``User`` columns are present in the inner subquery, so that they are available to the :func:`.contains_eager` modifier we are using on the outside, producing: .. sourcecode:: sql SELECT anon_1.address_id AS anon_1_address_id, anon_1.address_email AS anon_1_address_email, anon_1.address_user_id AS anon_1_address_user_id, anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM ( SELECT address.id AS address_id, address.email AS address_email, address.user_id AS address_user_id, "user".id AS user_id, "user".name AS user_name FROM address JOIN "user" ON "user".id = address.user_id WHERE "user".name LIKE :name_1) AS anon_1 If we didn't call ``add_entity(User)``, but still asked :func:`.contains_eager` to load the ``User`` entity, it would be forced to add the table on the outside without the correct join criteria - note the ``anon1, "user"`` phrase at the end: .. sourcecode:: sql -- incorrect query SELECT anon_1.address_id AS anon_1_address_id, anon_1.address_email AS anon_1_address_email, anon_1.address_user_id AS anon_1_address_user_id, "user".id AS user_id, "user".name AS user_name FROM ( SELECT address.id AS address_id, address.email AS address_email, address.user_id AS address_user_id FROM address JOIN "user" ON "user".id = address.user_id WHERE "user".name LIKE :name_1) AS anon_1, "user" :param \*entities: optional list of entities which will replace those being selected. FN) rrrrX_from_selectable_enable_single_critrrYr-)r.r/ fromclausers r0 from_selfzQuery.from_selfs`       u % % yy   ! !* - - % $ 1 1 3 3  & OOH % % %r2c||_dSr=)ro)r.vals r0_set_enable_single_critzQuery._set_enable_single_crits#&   r2cdD]}|j|d||gdd|_|j}g|_|D]#}|||jd$dS)N) rrrrrr _joinpathrr_having _prefixes _suffixesTFr)rrprnrr5adapt_to_selectablerb)r.rpattr old_entitiesrs r0rnzQuery._from_selectables   * *D M  dD ) ) ) ) zlD111).%~  ; ;A ! !$q(9 : : : : ; ;r2c|stdS|}||t|jsd|_t|S)zgReturn an iterator yielding result tuples corresponding to the given list of columns. r))r: )iterrr- _ColumnEntityr$)r.columnsrs r0valuesz Query.valuessV  88O KKMM  >>>| ALAwwr2cv t||dS#t$rYdSwxYw)zVReturn a scalar result corresponding to the given column expression. rN)nextr StopIterationr.columns r0r z Query.valuesH   F++,,Q/ /   44 s '* 88c0||dS)a7Return a new :class:`_query.Query` replacing the SELECT list with the given entities. e.g.:: # Users, filtered on some arbitrary criterion # and then ordered by related email address q = session.query(User).\ join(User.address).\ filter(User.name.like('%ed%')).\ order_by(Address.email) # given *only* User.id==5, Address.email, and 'q', what # would the *next* User in the result be ? subq = q.with_entities(Address.email).\ order_by(None).\ filter(User.id==5).\ subquery() q = q.join((subq, subq.c.email < Address.email)).\ limit(1) N)r-)r.r/s r0 with_entitieszQuery.with_entities s2 8$$$$$r2ct|j|_t|j}|D]}t||||j|ddS)zXAdd one or more column expressions to the list of result columns to be returned.N)rFr5rcrr9)r.rlr<s r0 add_columnszQuery.add_columns'sm dn--    # #A $ " " " " $$T^ABB%788888r2z0.7z9:meth:`.add_column` is superseded by :meth:`.add_columns`c,||S)zAdd a column expression to the list of result columns to be returned. Pending deprecation: :meth:`.add_column` will be superseded by :meth:`.add_columns`. )rrs r0 add_columnzQuery.add_column4s'''r2c|jdg|RS)aLReturn a new :class:`_query.Query` object, applying the given list of mapper options. Most supplied options regard changing how column- and relationship-mapped attributes are loaded. .. seealso:: :ref:`deferred_options` :ref:`relationship_loader_options` F_optionsr.rVs r0optionsz Query.optionsCs t}U*T****r2c|jdg|RSNTrrs r0_conditional_optionszQuery._conditional_optionsUst}T)D))))r2cP|j|_d|jvrt|jd<tt j|}|j|z|_|r|D]}||dS|D]}||dS)N_unbound_load_dedupes) _attributesr?rrar flatten_iterator _with_optionsprocess_query_conditionally process_query)r. conditionalrVoptsopts r0rzQuery._optionsXs +0022 "$*: : :8;D 4 5T*40011!/$6  ( 6 6//5555 6 6 ( (!!$'''' ( (r2c||S)aReturn a new :class:`_query.Query` object transformed by the given function. E.g.:: def filter_something(criterion): def transform(q): return q.filter(criterion) return transform q = q.with_transformation(filter_something(x==5)) This allows ad-hoc recipes to be created for :class:`_query.Query` objects. See the example at :ref:`hybrid_transformers`. r))r.fns r0with_transformationzQuery.with_transformationhs"r$xxr2*cZ|t|j}|xj|||ffz c_dS)aAdd an indexing or other executional context hint for the given entity or selectable to this :class:`_query.Query`. Functionality is passed straight through to :meth:`_expression.Select.with_hint`, with the addition that ``selectable`` can be a :class:`_schema.Table`, :class:`_expression.Alias`, or ORM entity / mapped class /etc. .. seealso:: :meth:`_query.Query.with_statement_hint` :meth:`.Query.prefix_with` - generic SELECT prefixing which also can suit some database-specific HINT syntaxes such as MySQL optimizer hints N)rrG _with_hints)r.rGtext dialect_names r0 with_hintzQuery.with_hint{s>.  ! ,,7J j$ =??r2c0|d||S)aAdd a statement hint to this :class:`_expression.Select`. This method is similar to :meth:`_expression.Select.with_hint` except that it does not require an individual table, and instead applies to the statement as a whole. This feature calls down into :meth:`_expression.Select.with_statement_hint`. .. versionadded:: 1.0.0 .. seealso:: :meth:`_query.Query.with_hint` N)r)r.rrs r0with_statement_hintzQuery.with_statement_hints$~~dD,777r2c|jS)zGet the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`_query.Query.execution_options` )r%rs r0get_execution_optionszQuery.get_execution_optionss &&r2c D|j||_dS)aSet non-SQL options which take effect during execution. The options are the same as those accepted by :meth:`_engine.Connection.execution_options`. Note that the ``stream_results`` execution option is enabled automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()` method is used. .. seealso:: :meth:`_query.Query.get_execution_options` N)r%r&r.kwargss r0execution_optionszQuery.execution_optionss# #'"9"?"?"G"Gr2z0.9zThe :meth:`_query.Query.with_lockmode` method is deprecated and will be removed in a future release. Please refer to :meth:`_query.Query.with_for_update`. cDt||_dS)a"Return a new :class:`_query.Query` object with the specified "locking mode", which essentially refers to the ``FOR UPDATE`` clause. :param mode: a string representing the desired locking mode. Valid values are: * ``None`` - translates to no lockmode * ``'update'`` - translates to ``FOR UPDATE`` (standard SQL, supported by most dialects) * ``'update_nowait'`` - translates to ``FOR UPDATE NOWAIT`` (supported by Oracle, PostgreSQL 8.1 upwards) * ``'read'`` - translates to ``LOCK IN SHARE MODE`` (for MySQL), and ``FOR SHARE`` (for PostgreSQL) .. seealso:: :meth:`_query.Query.with_for_update` - improved API for specifying the ``FOR UPDATE`` clause. N) LockmodeArgparse_legacy_queryrK)r.modes r0 with_lockmodezQuery.with_lockmodes!B +==dCCr2c8t||||||_dS)areturn a new :class:`_query.Query` with the specified options for the ``FOR UPDATE`` clause. The behavior of this method is identical to that of :meth:`_expression.GenerativeSelect.with_for_update`. When called with no arguments, the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause appended. When additional arguments are specified, backend-specific options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE`` can take effect. E.g.:: q = sess.query(User).populate_existing().with_for_update(nowait=True, of=User) The above query on a PostgreSQL backend will render like:: SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT .. versionadded:: 0.9.0 :meth:`_query.Query.with_for_update` supersedes the :meth:`_query.Query.with_lockmode` method. .. note:: It is generally a good idea to combine the use of the :meth:`_orm.Query.populate_existing` method when using the :meth:`_orm.Query.with_for_update` method. The purpose of :meth:`_orm.Query.populate_existing` is to force all the data read from the SELECT to be populated into the ORM objects returned, even if these objects are already in the :term:`identity map`. .. seealso:: :meth:`_expression.GenerativeSelect.with_for_update` - Core level method with full argument and behavioral description. :meth:`_orm.Query.populate_existing` - overwrites attributes of objects already loaded in the identity map. )readnowaitof skip_locked key_shareN)rrK)r.rrrrrs r0with_for_updatezQuery.with_for_updates1f +#    r2c"t|dkr||dn't|dkrtjd|j|_|j|dS)aAdd values for bind parameters which may have been specified in filter(). Parameters may be specified using \**kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that \**kwargs is convenient, however some parameter dictionaries contain unicode keys in which case \**kwargs cannot be used. rrzFparams() takes zero or one positional argument, which is a dictionary.N)rcrrZr[rr?)r.rVrs r0rz Query.params&s t99>> MM$q' " " " " YY]]&) |((**  F#####r2ct|D]K}tj|}||dd}|j|j|z|_D||_LdS)a!Apply the given filtering criterion to a copy of this :class:`_query.Query`, using SQL expressions. e.g.:: session.query(MyClass).filter(MyClass.name == 'some name') Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the :func:`.and_` function:: session.query(MyClass).\ filter(MyClass.name == 'some name', MyClass.id > 5) The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced into SQL expression constructs via the :func:`_expression.text` construct. .. seealso:: :meth:`_query.Query.filter_by` - filter on keyword expressions. TN)rFr!_expression_literal_as_textrrr. criterions r0rfz Query.filter;sk4i , ,I">yIII**9dDAAI*"&/I"="+ , ,r2c |)tjd|zfd|D}|j|S)aApply the given filtering criterion to a copy of this :class:`_query.Query`, using keyword expressions. e.g.:: session.query(MyClass).filter_by(name = 'some name') Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the :func:`.and_` function:: session.query(MyClass).\ filter_by(name = 'some name', id = 5) The keyword expressions are extracted from the primary entity of the query, or the last entity that was the target of a call to :meth:`_query.Query.join`. .. seealso:: :meth:`_query.Query.filter` - filter on SQL expressions. NzCan't use filter_by when the first entity '%s' of a query is not a mapped class. Please use the filter method instead, or change the order of the entities in the queryc>g|]\}}t||kSr)r )rr3r zeros r0rz#Query.filter_by..s<   U tS ) )U 2   r2)rrZrritemsrf)r.rclausesrs @r0 filter_byzQuery.filter_by_s2##%% <,C))++,     $llnn   t{G$$r2ct|dkr-|ddurd|jvrd|_dS|d d|_dS||}|jdus|j ||_dS|j|z|_dS)agApply one or more ORDER BY criterion to the query and return the newly resulting :class:`_query.Query`. All existing ORDER BY settings can be suppressed by passing ``None`` - this will suppress any ordering configured on the :func:`.mapper` object using the deprecated :paramref:`.mapper.order_by` parameter. rrFrN)rcrrrrs r0rzQuery.order_bys y>>Q  |u$$$-//%*DN|#!%((33 >U " "dn&<&DNNN!^i7DNNNr2ct|dkr|d d|_dSttd|D}||}|jdur ||_dS|j|z|_dS)aApply one or more GROUP BY criterion to the query and return the newly resulting :class:`_query.Query`. All existing GROUP BY settings can be suppressed by passing ``None`` - this will suppress any GROUP BY configured on mappers as well. .. versionadded:: 1.1 GROUP BY can be cancelled by passing ``None``, in the same way as ORDER BY. rrNFc,g|]}t|Sr)rr;s r0rz"Query.group_by..s D D DQa D D Dr2)rcrrFrrrs r0group_byzQuery.group_bys y>>Q  |#!& D D) D D DEFF ((33 >U " "&DNNN!^i7DNNNr2ctj|}|.t|tjst jd||dd}|j|j|z|_dS||_dS)aApply a HAVING criterion to the query and return the newly resulting :class:`_query.Query`. :meth:`_query.Query.having` is used in conjunction with :meth:`_query.Query.group_by`. HAVING criterion makes it possible to use filters on aggregate functions like COUNT, SUM, AVG, MAX, and MIN, eg.:: q = session.query(User.id).\ join(User.addresses).\ group_by(User.id).\ having(func.count(Address.id) > 2) NzHhaving() argument must be of type sqlalchemy.sql.ClauseElement or stringT) r!rr^r ClauseElementrZr[rrwrs r0havingz Query.havings$:9EE   s(* * &9  &&y$== < #<)3DLLL$DLLLr2cz|||gt|zdSr)rnrFrt)r.expr_fnrs r0_set_opz Query._set_ops?$$ GtftAww& (  ! !% ( ( )r2c2|jtjg|RS)aProduce a UNION of this Query against one or more queries. e.g.:: q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar') q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo') q3 = q1.union(q2) The method accepts multiple Query objects so as to control the level of nesting. A series of ``union()`` calls such as:: x.union(y).union(z).all() will nest on each ``union()``, and produces:: SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y) UNION SELECT * FROM Z) Whereas:: x.union(y, z).all() produces:: SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION SELECT * FROM Z) Note that many database backends do not allow ORDER BY to be rendered on a query called within UNION, EXCEPT, etc. To disable all ORDER BY clauses including those configured on mappers, issue ``query.order_by(None)`` - the resulting :class:`_query.Query` object will not render ORDER BY within its SELECT statement. )rr!r&r.rs r0r&z Query.unions"Jt|J,1q1111r2c2|jtjg|RS)zProduce a UNION ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr! union_allrs r0rzQuery.union_all !t|J0515555r2c2|jtjg|RS)zProduce an INTERSECT of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr! intersectrs r0rzQuery.intersectrr2c2|jtjg|RS)zProduce an INTERSECT ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr! intersect_allrs r0rzQuery.intersect_alls!t|J49q9999r2c2|jtjg|RS)zProduce an EXCEPT of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr!except_rs r0rz Query.except_(s!t|J.33333r2c2|jtjg|RS)zProduce an EXCEPT ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr! except_allrs r0rzQuery.except_all1s!t|J16A6666r2cT|dd|dd|dd|ddf\}}}}|r2tddt|z||||||S) aO-Create a SQL JOIN against this :class:`_query.Query` object's criterion and apply generatively, returning the newly resulting :class:`_query.Query`. **Simple Relationship Joins** Consider a mapping between two classes ``User`` and ``Address``, with a relationship ``User.addresses`` representing a collection of ``Address`` objects associated with each ``User``. The most common usage of :meth:`_query.Query.join` is to create a JOIN along this relationship, using the ``User.addresses`` attribute as an indicator for how this should occur:: q = session.query(User).join(User.addresses) Where above, the call to :meth:`_query.Query.join` along ``User.addresses`` will result in SQL approximately equivalent to:: SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id In the above example we refer to ``User.addresses`` as passed to :meth:`_query.Query.join` as the "on clause", that is, it indicates how the "ON" portion of the JOIN should be constructed. To construct a chain of joins, multiple :meth:`_query.Query.join` calls may be used. The relationship-bound attribute implies both the left and right side of the join at once:: q = session.query(User).\ join(User.orders).\ join(Order.items).\ join(Item.keywords) .. note:: as seen in the above example, **the order in which each call to the join() method occurs is important**. Query would not, for example, know how to join correctly if we were to specify ``User``, then ``Item``, then ``Order``, in our chain of joins; in such a case, depending on the arguments passed, it may raise an error that it doesn't know how to join, or it may produce invalid SQL in which case the database will raise an error. In correct practice, the :meth:`_query.Query.join` method is invoked in such a way that lines up with how we would want the JOIN clauses in SQL to be rendered, and each call should represent a clear link from what precedes it. **Joins to a Target Entity or Selectable** A second form of :meth:`_query.Query.join` allows any mapped entity or core selectable construct as a target. In this usage, :meth:`_query.Query.join` will attempt to create a JOIN along the natural foreign key relationship between two entities:: q = session.query(User).join(Address) In the above calling form, :meth:`_query.Query.join` is called upon to create the "on clause" automatically for us. This calling form will ultimately raise an error if either there are no foreign keys between the two entities, or if there are multiple foreign key linkages between the target entity and the entity or entities already present on the left side such that creating a join requires more information. Note that when indicating a join to a target without any ON clause, ORM configured relationships are not taken into account. **Joins to a Target with an ON Clause** The third calling form allows both the target entity as well as the ON clause to be passed explicitly. A example that includes a SQL expression as the ON clause is as follows:: q = session.query(User).join(Address, User.id==Address.user_id) The above form may also use a relationship-bound attribute as the ON clause as well:: q = session.query(User).join(Address, User.addresses) The above syntax can be useful for the case where we wish to join to an alias of a particular target entity. If we wanted to join to ``Address`` twice, it could be achieved using two aliases set up using the :func:`~sqlalchemy.orm.aliased` function:: a1 = aliased(Address) a2 = aliased(Address) q = session.query(User).\ join(a1, User.addresses).\ join(a2, User.addresses).\ filter(a1.email_address=='ed@foo.com').\ filter(a2.email_address=='ed@bar.com') The relationship-bound calling form can also specify a target entity using the :meth:`_orm.PropComparator.of_type` method; a query equivalent to the one above would be:: a1 = aliased(Address) a2 = aliased(Address) q = session.query(User).\ join(User.addresses.of_type(a1)).\ join(User.addresses.of_type(a2)).\ filter(a1.email_address == 'ed@foo.com').\ filter(a2.email_address == 'ed@bar.com') **Joining to Tables and Subqueries** The target of a join may also be any table or SELECT statement, which may be related to a target entity or not. Use the appropriate ``.subquery()`` method in order to make a subquery out of a query:: subq = session.query(Address).\ filter(Address.email_address == 'ed@foo.com').\ subquery() q = session.query(User).join( subq, User.id == subq.c.user_id ) Joining to a subquery in terms of a specific relationship and/or target entity may be achieved by linking the subquery to the entity using :func:`_orm.aliased`:: subq = session.query(Address).\ filter(Address.email_address == 'ed@foo.com').\ subquery() address_subq = aliased(Address, subq) q = session.query(User).join( User.addresses.of_type(address_subq) ) **Controlling what to Join From** In cases where the left side of the current state of :class:`_query.Query` is not in line with what we want to join from, the :meth:`_query.Query.select_from` method may be used:: q = session.query(Address).select_from(User).\ join(User.addresses).\ filter(User.name == 'ed') Which will produce SQL similar to:: SELECT address.* FROM user JOIN address ON user.id=address.user_id WHERE user.name = :name_1 **Legacy Features of Query.join()** The :meth:`_query.Query.join` method currently supports several usage patterns and arguments that are considered to be legacy as of SQLAlchemy 1.3. A deprecation path will follow in the 1.4 series for the following features: * Joining on relationship names rather than attributes:: session.query(User).join("addresses") **Why it's legacy**: the string name does not provide enough context for :meth:`_query.Query.join` to always know what is desired, notably in that there is no indication of what the left side of the join should be. This gives rise to flags like ``from_joinpoint`` as well as the ability to place several join clauses in a single :meth:`_query.Query.join` call which don't solve the problem fully while also adding new calling styles that are unnecessary and expensive to accommodate internally. **Modern calling pattern**: Use the actual relationship, e.g. ``User.addresses`` in the above case:: session.query(User).join(User.addresses) * Automatic aliasing with the ``aliased=True`` flag:: session.query(Node).join(Node.children, aliased=True).\ filter(Node.name == 'some name') **Why it's legacy**: the automatic aliasing feature of :class:`_query.Query` is intensely complicated, both in its internal implementation as well as in its observed behavior, and is almost never used. It is difficult to know upon inspection where and when its aliasing of a target entity, ``Node`` in the above case, will be applied and when it won't, and additionally the feature has to use very elaborate heuristics to achieve this implicit behavior. **Modern calling pattern**: Use the :func:`_orm.aliased` construct explicitly:: from sqlalchemy.orm import aliased n1 = aliased(Node) session.query(Node).join(Node.children.of_type(n1)).\ filter(n1.name == 'some name') * Multiple joins in one call:: session.query(User).join("orders", "items") session.query(User).join(User.orders, Order.items) session.query(User).join( (Order, User.orders), (Item, Item.order_id == Order.id) ) # ... and several more forms actually **Why it's legacy**: being able to chain multiple ON clauses in one call to :meth:`_query.Query.join` is yet another attempt to solve the problem of being able to specify what entity to join from, and is the source of a large variety of potential calling patterns that are internally expensive and complicated to parse and accommodate. **Modern calling pattern**: Use relationship-bound attributes or SQL-oriented ON clauses within separate calls, so that each call to :meth:`_query.Query.join` knows what the left side should be:: session.query(User).join(User.orders).join( Item, Item.order_id == Order.id) :param \*props: Incoming arguments for :meth:`_query.Query.join`, the props collection in modern use should be considered to be a one or two argument form, either as a single "target" entity or ORM attribute-bound relationship, or as a target entity plus an "on clause" which may be a SQL expression or ORM attribute-bound relationship. :param isouter=False: If True, the join used will be a left outer join, just as if the :meth:`_query.Query.outerjoin` method were called. :param full=False: render FULL OUTER JOIN; implies ``isouter``. .. versionadded:: 1.1 :param from_joinpoint=False: When using ``aliased=True``, a setting of True here will cause the join to be from the most recent joined target, rather than starting back from the original FROM clauses of the query. .. note:: This flag is considered legacy. :param aliased=False: If True, indicate that the JOIN target should be anonymously aliased. Subsequent calls to :meth:`_query.Query.filter` and similar will adapt the incoming criterion to the target alias, until :meth:`_query.Query.reset_joinpoint` is called. .. note:: This flag is considered legacy. .. seealso:: :ref:`ormtutorial_joins` in the ORM tutorial. :ref:`inheritance_toplevel` for details on how :meth:`_query.Query.join` is used for inheritance relationships. :func:`_orm.join` - a standalone ORM-level join function, used internally by :meth:`_query.Query.join`, which in previous SQLAlchemy versions was the primary ORM-level joining interface. rFfrom_joinpointisouterfullunknown arguments: %s,  outerjoinrcreate_aliasesrrp TypeErrorrsorted_join)r.propsrrrrrs r0rz Query.join:sh JJy% ( ( JJ' / / JJy% ( ( JJvu % % 2 .$  '$))F6NN*C*CC zz ")    r2c"|dd|dd|dd}}}|r2tddt|z||d|||S) zCreate a left outer join against this :class:`_query.Query` object's criterion and apply generatively, returning the newly resulting :class:`_query.Query`. Usage is the same as the :meth:`_query.Query.join` method. rFrrrrTrr)r.rrrrrs r0rzQuery.outerjoin_ s JJy% ( ( JJ' / / JJvu % %"&  '$))F6NN*C*CC zz ")    r2c||_d|vrC|d\}}|}|||<||f|d<|}d|vC||_dS)Nprev)rr?rv)r.jpfrs r0_update_joinpointzQuery._update_joinpointx silljGAt99;;DggiiDGTBvJB ll r2c |s|t|dkrbt|dtjt t fr5t|dttjtj fr|f}tj |}t|D] \}}t|tr|\}} nd} t|tj tjfr| |} } n|| } } | :t!| } | js$t%| dst'jdt| tj rt+| dd} nd} t| tjr#t-|| } nl|rjt| tj rP|}t!|}t+|dd| jurt-|| j} t| tj rn| W| r| } nR| j} | j} nB#t8$r5}tjt'jd| z| Yd}~nd}~wwxYw| j}|j|d}t|t@r6|j!"|r|j#}t+|| j} | j}t| tHj%s|} |s|| |jf}||j&vro|j&|'}||j&f|d <|(||t|dz krtj)d |zndx}}|*|| | ||||dS) zConsumes arguments from :meth:`_query.Query.join` or :meth:`_query.Query.outerjoin`, places them into a consistent format with which to form the actual JOIN constructs. rrrNrAz9Expected mapped entity or selectable/table as join target_of_typez0Join target %s does not refer to a mapped entityrBrz:Pathed join target %s has already been joined to; skipping)+_reset_joinpointrcr^r!rxtyperstrrrPropComparatorr r8 enumeratera string_typesrr]rWrZr[getattrr r _parententityr3rgrLAttributeErrorrIr,rvrrAisa aliased_classrQueryableAttributerr?rwarn_join_left_to_right)r.keysrrrrkeylistidxarg1arg2rightonclauser_infoof_typejp0rlrQleftr`r@edgers r0rz Query._join sS $  ! ! # # # IINNQ*/|D Qj. 0IJ 7D,t$$"7++y y IC$&& " dd z0$2CD -#'x"&x +GFH4M4M .: (J$=>> !(J==(D$566 E.d.B.B.D.DhOO  EJ*3%% E**,,s||4400H4JJJ1#x|DDH(J$=>>; #= ' ( 1 $)LEE- K & 4%46;%<!"!"14  -266tTBBeZ00;U\5E5Ed5K5K; .D&tX\::H(!(J,IJJ$#H%!!%2Dt.."_T27799&*DO%<6 ..r222#g,,"222 I!;=A!B!#"t  $ $eXt^Y    oy y s>I J+JJcH|j|_| |J||||\}}} n|J||\}} ||ur|st jd|d|d||||||\} }}|L|j|} |jd|t| ||||fz|j|dzdz|_dS| |j | j } n|} |jt| ||||fz|_dS)zGiven raw "left", "right", "onclause" parameters consumed from a particular key within _join(), add a real ORMJoin object to our _from_obj list (or augment an existing one) NzCan't construct a join from z to z, they are the same entity)rrr) r,r?"_join_determine_implicit_left_side_join_place_explicit_left_siderZr _join_check_and_adapt_right_siderborm_joinr5rG) r.rr r r@rrrreplace_from_obj_indexuse_entity_indexr  left_clauses r0rzQuery._join_left_to_right s&*%?%D%D%F%F" <<<< 77eXNN  &  ###33D99 &  5===,,)-uuu6 #'"G"G %4# # x " -.)?@K6 667# )!  .!7!!;!=!=> ? NNN  +"n-=>I " !^)$/DNNNr2ct|}dx}}|jrtj|j|j|}t |dkr|d}|j|}nit |dkrt jdt jd|d|jri}t|jD]Q\} } | j } | t| } | |ur#t| tr | | f|| j<Ed| f|| j<Rt|} tj| |j|}t |dkr|| |d\}}nSt |dkrt jdt jd|dt jd|||fS)zWhen join conditions don't express the left side explicitly, determine if an existing FROM or entity in this query can serve as the left hand side. NrraCan't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Please use the .select_from() method to establish an explicit left side, as well as providing an explcit ON clause if not present already to help resolve the ambiguity.zDon't know how to join to z. Please use the .select_from() method to establish an explicit left side, as well as providing an explcit ON clause if not present already to help resolve the ambiguity.zgNo entities to join from; please use select_from() to establish the left entity/selectable of this join)rrbrEfind_left_clause_to_join_fromrGrcrZrr5rentity_zero_or_selectabler^rrFr)r.rr r r rrindexes potential entity_indexr;rLent_info all_clausess r0rz(Query._join_determine_implicit_left_sidel s?"488!1 >O < 18G7||q  )0&~&<=W!!0200 6;UU =^2 I%.t~%>%> D D! c6>"6??v%% c=11D1=v0FIcn--6:F^Ih122y~~//00K<V.G7||q  )2;wqz3J)K& $$W!!0200 6;UU =,1  +-===r2cdx}}t|}|jrPtj|j|j}t |dkrt jd|r|d}|_|jrXt|drHt|jD]3\}}t|tr| |r|}n4||fS)zWhen join conditions express a left side explicitly, determine where in our existing list of FROM clauses we should join towards, or if we need to make a new join, and if so is it from one of our existing entities. NrzrCan't identify which entity in which to assign the left side of this join. Please use a more specific ON clause.rrA)rrbrE#find_left_clause_that_matches_givenrGrcrZrr5rWrr^rcorresponds_to)r.rrrl_inforrr;s r0rz$Query._join_place_explicit_left_side s2598!1 > 4B 1G7||a0! 4)0& # * +)) +&dn55  Sc=11c6H6H6N6N'*$E%'777r2cLt|}t|}d}|st|dd} | rp| jst| jt jrJ|jp|jgD]:} tj |j| rtj | |jrd}n;|s|s*|j|jurtj d|jzt|dd|jt|dd} } } | r6|r4| |jstj d|d|t|dr|xj|fz c_d} |jr|r|j} | jr||dd}n|r| | js*tj d | jd | jjd t| t jr| } d} t1| | }n|rtj d | o*| o'| jrt| jt jp|}| s|s|rt1|d }d} | rB| sJt7|| j}|f|jz|_|s|| |t|t jr||dd}|s*|r(| ||||j!f|j"fdn d|i|_"|t||fS)zTransform the "right" side of the join as well as the onclause according to polymorphic mapping translations, aliasing on the query or on the join, special cases where the right and left side have overlapping tables. FrANTz*Can't join table/selectable '%s' to itselfr@z Join target z9 does not correspond to the right side of join condition z Selectable 'z' is not derived from 'rbzpThe aliased=True parameter on query.join() only works with an ORM entity, not a plain selectable, as the target.)flat) equivalents)rrr)#rrrBr^rCr!JoinrbrGrEselectables_overlaprZr common_parentrArW_join_entitiesr _is_lateralris_derived_from descriptionr_r`r_with_polymorphic_selectablerdrrHrrDrrr3r)r.rr r r@rr#r overlap right_mapperrkright_selectableright_is_aliased need_adapteraliased_entityrSs r0rz&Query._join_check_and_adapt_right_side sQ "68T::L - l=zOO !% E63D2EH3)8"6 &"3 #'  ) 6#444,<#$  FHd + +   F. 6 6)9&    !..t{;;  ,,9>J  68 $ $ -   F9 ,     #(  +#{ +# **5$>> (77 3 !44-888(;GGG. 0EFF('7'='='?'?$#'L .>?? 0  $$ - =z?O   > E---EL  O    !<#CG%,:0D#DD " O77 gNNN h 8 9 9 @))(D$??H ;$ ;  " ")."E484doF     3E:DOgennh..r2c,|j|_d|_dSNr))rvrrrs r0rzQuery._reset_joinpoint s.!r2c.|dS)acReturn a new :class:`_query.Query`, where the "join point" has been reset back to the base FROM entities of the query. This method is usually used in conjunction with the ``aliased=True`` feature of the :meth:`_query.Query.join` method. See the example in :meth:`_query.Query.join` for how this is used. N)rrs r0reset_joinpointzQuery.reset_joinpoint s r2c2||ddS)aSet the FROM clause of this :class:`_query.Query` explicitly. :meth:`_query.Query.select_from` is often used in conjunction with :meth:`_query.Query.join` in order to control which entity is selected from on the "left" side of the join. The entity or selectable object here effectively replaces the "left edge" of any calls to :meth:`_query.Query.join`, when no joinpoint is otherwise established - usually, the default "join point" is the leftmost entity in the :class:`_query.Query` object's list of entities to be selected. A typical example:: q = session.query(Address).select_from(User).\ join(User.addresses).\ filter(User.name == 'ed') Which produces SQL equivalent to:: SELECT address.* FROM user JOIN address ON user.id=address.user_id WHERE user.name = :name_1 :param \*from_obj: collection of one or more entities to apply to the FROM clause. Entities can be mapped classes, :class:`.AliasedClass` objects, :class:`_orm.Mapper` objects as well as core :class:`_expression.FromClause` elements like subqueries. .. versionchanged:: 0.9 This method no longer applies the given FROM object to be the selectable from which matching entities select from; the :meth:`.select_entity_from` method now accomplishes this. See that method for a description of this behavior. .. seealso:: :meth:`_query.Query.join` :meth:`_query.Query.select_entity_from` FNrnr.rks r0 select_fromzQuery.select_from s!^ h.....r2c4||gddS)aSet the FROM clause of this :class:`_query.Query` to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities. The :meth:`_query.Query.select_entity_from` method supplies an alternative approach to the use case of applying an :func:`.aliased` construct explicitly throughout a query. Instead of referring to the :func:`.aliased` construct explicitly, :meth:`_query.Query.select_entity_from` automatically *adapts* all occurrences of the entity to the target selectable. Given a case for :func:`.aliased` such as selecting ``User`` objects from a SELECT statement:: select_stmt = select([User]).where(User.id == 7) user_alias = aliased(User, select_stmt) q = session.query(user_alias).\ filter(user_alias.name == 'ed') Above, we apply the ``user_alias`` object explicitly throughout the query. When it's not feasible for ``user_alias`` to be referenced explicitly in many places, :meth:`_query.Query.select_entity_from` may be used at the start of the query to adapt the existing ``User`` entity:: q = session.query(User).\ select_entity_from(select_stmt).\ filter(User.name == 'ed') Above, the generated SQL will show that the ``User`` entity is adapted to our statement, even in the case of the WHERE clause: .. sourcecode:: sql SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name FROM (SELECT "user".id AS id, "user".name AS name FROM "user" WHERE "user".id = :id_1) AS anon_1 WHERE anon_1.name = :name_1 The :meth:`_query.Query.select_entity_from` method is similar to the :meth:`_query.Query.select_from` method, in that it sets the FROM clause of the query. The difference is that it additionally applies adaptation to the other parts of the query that refer to the primary entity. If above we had used :meth:`_query.Query.select_from` instead, the SQL generated would have been: .. sourcecode:: sql -- uses plain select_from(), not select_entity_from() SELECT "user".id AS user_id, "user".name AS user_name FROM "user", (SELECT "user".id AS id, "user".name AS name FROM "user" WHERE "user".id = :id_1) AS anon_1 WHERE "user".name = :name_1 To supply textual SQL to the :meth:`_query.Query.select_entity_from` method, we can make use of the :func:`_expression.text` construct. However, the :func:`_expression.text` construct needs to be aligned with the columns of our entity, which is achieved by making use of the :meth:`_expression.TextClause.columns` method:: text_stmt = text("select id, name from user").columns( User.id, User.name) q = session.query(User).select_entity_from(text_stmt) :meth:`_query.Query.select_entity_from` itself accepts an :func:`.aliased` object, so that the special options of :func:`.aliased` such as :paramref:`.aliased.adapt_on_names` may be used within the scope of the :meth:`_query.Query.select_entity_from` method's adaptation services. Suppose a view ``user_view`` also returns rows from ``user``. If we reflect this view into a :class:`_schema.Table`, this view has no relationship to the :class:`_schema.Table` to which we are mapped, however we can use name matching to select from it:: user_view = Table('user_view', metadata, autoload_with=engine) user_view_alias = aliased( User, user_view, adapt_on_names=True) q = session.query(User).\ select_entity_from(user_view_alias).\ order_by(User.name) .. versionchanged:: 1.1.7 The :meth:`_query.Query.select_entity_from` method now accepts an :func:`.aliased` object as an alternative to a :class:`_expression.FromClause` object. :param from_obj: a :class:`_expression.FromClause` object that will replace the FROM clause of this :class:`_query.Query`. It also may be an instance of :func:`.aliased`. .. seealso:: :meth:`_query.Query.select_from` TNr:r;s r0select_entity_fromzQuery.select_entity_from s#b xj$/////r2cZt|trtj|\}}}t|tr t|tr ||z dkrgSt|tr|dkst|tr|dkrt ||S|||}|t |dd|jSt |S|dkrt |dSt |||dzdS)Nrr)r^slicer decode_sliceintrFstep)r.itemstartstoprDress r0 __getitem__zQuery.__getitem__m s' dE " " 6 $ 1$ 7 7 E44%% (uc** (5LA%% UC(( (UQYY4%%.7*.((Dzz$''**UD))CCyyty!899Cyy rzzDzz"~%Dq122155r2cP|8|6|j|jnd|_|dkr|xj|z c_||z |_n;| |||_n/|-|+|j|jnd|_|dkr|xj|z c_t|jtr|jdkr d|_dSdSdS)aComputes the "slice" of the :class:`_query.Query` represented by the given indices and returns the resulting :class:`_query.Query`. The start and stop indices behave like the argument to Python's built-in :func:`range` function. This method provides an alternative to using ``LIMIT``/``OFFSET`` to get a slice of the query. For example, :: session.query(User).order_by(User.id).slice(1, 3) renders as .. sourcecode:: sql SELECT users.id AS users_id, users.name AS users_name FROM users ORDER BY users.id LIMIT ? OFFSET ? (2, 1) .. seealso:: :meth:`_query.Query.limit` :meth:`_query.Query.offset` Nr)rrr^rC)r.rFrGs r0rAz Query.slice s>  !1+/<+C4<<DLzz % ,DKK ]t/DKK  4<+/<+C4<<DLzz % dlC ( ( T\Q->->DLLL  ->->r2c||_dS)zfApply a ``LIMIT`` to the query and return the newly resulting :class:`_query.Query`. N)r)r.limits r0rLz Query.limit s  r2c||_dS)zhApply an ``OFFSET`` to the query and return the newly resulting :class:`_query.Query`. N)r)r.offsets r0rNz Query.offset s  r2c|s d|_dS||}t|jtr|xj|z c_dS||_dS)aApply a ``DISTINCT`` to the query and return the newly resulting :class:`_query.Query`. .. note:: The :meth:`.distinct` call includes logic that will automatically add columns from the ORDER BY of the query to the columns clause of the SELECT statement, to satisfy the common need of the database backend that ORDER BY columns be part of the SELECT list when DISTINCT is used. These columns *are not* added to the list of columns actually fetched by the :class:`_query.Query`, however, so would not affect results. The columns are passed through when using the :attr:`_query.Query.statement` accessor, however. :param \*expr: optional column expressions. When present, the PostgreSQL dialect will render a ``DISTINCT ON ()`` construct. TN)rrr^rF)r.exprs r0rzQuery.distinct s]. &!DNNN''--D$.$// &$&!%r2cF|jr|xj|z c_dS||_dS)aApply the prefixes to the query and return the newly resulting :class:`_query.Query`. :param \*prefixes: optional prefixes, typically strings, not using any commas. In particular is useful for MySQL keywords and optimizer hints: e.g.:: query = sess.query(User.name).\ prefix_with('HIGH_PRIORITY').\ prefix_with('SQL_SMALL_RESULT', 'ALL').\ prefix_with('/*+ BKA(user) */') Would render:: SELECT HIGH_PRIORITY SQL_SMALL_RESULT ALL /*+ BKA(user) */ users.name AS users_name FROM users .. seealso:: :meth:`_expression.HasPrefixes.prefix_with` N)rx)r.prefixess r0 prefix_withzQuery.prefix_with s-4 > & NNh &NNNN%DNNNr2cF|jr|xj|z c_dS||_dS)adApply the suffix to the query and return the newly resulting :class:`_query.Query`. :param \*suffixes: optional suffixes, typically strings, not using any commas. .. versionadded:: 1.0.0 .. seealso:: :meth:`_query.Query.prefix_with` :meth:`_expression.HasSuffixes.suffix_with` N)ry)r.suffixess r0 suffix_withzQuery.suffix_with s-" > & NNh &NNNN%DNNNr2c t|S)aReturn the results represented by this :class:`_query.Query` as a list. This results in an execution of the underlying SQL statement. .. warning:: The :class:`_query.Query` object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will **deduplicate entries based on primary key**. See the FAQ for more details. .. seealso:: :ref:`faq_query_deduplicating` )rFrs r0allz Query.all s Dzzr2ctj|}t|tjtjfst jd||_dS)a1Execute the given SELECT statement and return results. This method bypasses all internal statement compilation, and the statement is executed without modification. The statement is typically either a :func:`_expression.text` or :func:`_expression.select` construct, and should return the set of columns appropriate to the entity class represented by this :class:`_query.Query`. .. seealso:: :ref:`orm_tutorial_literal_sql` - usage examples in the ORM tutorial zBfrom_statement accepts text(), select(), and union() objects only.N)r!rr^ TextClauser_rZr[r)r.rs r0from_statementzQuery.from_statement/ s_&:9EE   -z/DE   &,  $r2c|jt|dd}nt|dd}t|dkr|dSdS)a7Return the first result of this ``Query`` or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present). Calling :meth:`_query.Query.first` results in an execution of the underlying query. .. seealso:: :meth:`_query.Query.one` :meth:`_query.Query.one_or_none` Nrr)rrFrcr.rets r0firstz Query.firstN sQ( ? &t**QqS/CCtAaCy//C s88a<<q6M4r2ct|}t|}|dkr|dS|dkrdStjd)aReturn at most one result or raise an exception. Returns ``None`` if the query selects no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound`` if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities. Calling :meth:`_query.Query.one_or_none` results in an execution of the underlying query. .. versionadded:: 1.0.9 Added :meth:`_query.Query.one_or_none` .. seealso:: :meth:`_query.Query.first` :meth:`_query.Query.one` rrNz*Multiple rows were found for one_or_none())rFrcorm_excMultipleResultsFound)r.r^rs r0 one_or_nonezQuery.one_or_nonek sR04jj HH 66q6M !VV4.< r2c |}|tjd|S#tj$r3}t jtjd|Yd}~dSd}~wwxYw)aBReturn exactly one result or raise an exception. Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound`` if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities. Calling :meth:`.one` results in an execution of the underlying query. .. seealso:: :meth:`_query.Query.first` :meth:`_query.Query.one_or_none` NzNo row was found for one()z"Multiple rows were found for one()rB)rcra NoResultFoundrbr rI)r.r^rQs r0onez Query.one s$ ""$$C{+,HIIIJ+    K,8!$            s.A0(A++A0c |}t|ts|S|dS#tj$rYdSwxYw)a4Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound. >>> session.query(Item).scalar() >>> session.query(Item.id).scalar() 1 >>> session.query(Item.id).filter(Item.id < 0).scalar() None >>> session.query(Item.id, Item.name).scalar() 1 >>> session.query(func.count(Parent.id)).scalar() 20 This results in an execution of the underlying query. rN)rfr^rararer]s r0scalarz Query.scalar sY& ((**Cc5))  q6M$   44 s*55AAc|}d|j_|jr |js|j||Sr)rr use_labelsrZrr+_execute_and_instances)r.contexts r0__iter__zQuery.__iter__ sZ''))'+$ ? &4#: & L # # % % %**7333r2c|} |jr |||jjnd}n#tj$rd}YnwxYwt |j|Sr=) rr+_get_bind_argsget_bindrZUnboundExecutionErrorrrcompile)r.rlbinds r0__str__z Query.__str__ s'')) <##GT\-BCCC D +   DDD 7$,,T22333s)AAAc \|jjdi|}|jr|jdi|j}|Sr6)r+ connectionr%r)r.kwconns r0_connection_from_sessionzQuery._connection_from_session sH&t|&,,,,  " E)4)DDD,CDDD r2c|||jd}||j|j}t j|j||S)NT)close_with_result)roryexecuterrr instancesquery)r. querycontextrxresults r0rkzQuery._execute_and_instances sX"" $74#  l4dlCC !3V\JJJr2ch|||d}|||jS)NT)rArr{)ryr|r)r.rrArxs r0 _execute_crudzQuery._execute_crud s;,,$$-  ||D$,///r2c F|d||jd|S)N)rArr))rr)r.rrrws r0rozQuery._get_bind_args s<r $$&&|/E  IK   r2c8dd|jDDS)aReturn metadata about the columns which would be returned by this :class:`_query.Query`. Format is a list of dictionaries:: user_alias = aliased(User, name='user2') q = sess.query(User, User.id, user_alias) # this expression: q.column_descriptions # would return: [ { 'name':'User', 'type':User, 'aliased':False, 'expr':User, 'entity': User }, { 'name':'id', 'type':Integer(), 'aliased':False, 'expr':User.id, 'entity': User }, { 'name':'user2', 'type':User, 'aliased':True, 'expr':user_alias, 'entity': user_alias } ] c g|]J\}}|j|jt|dd|j|j|jst|ddnddKS)r@FNrL)rrrrPrL) _label_namerrrPrr)rr;insp_ents r0rz-Query.column_descriptions..s   X"8-?GG?. 2/"(Hd;;;     r2cLg|]!}||jt|jndf"Sr=)rr)r_ents r0rz-Query.column_descriptions..*sP " " " +7  0111!  " " "r2rrs r0column_descriptionszQuery.column_descriptions sAP   " "!N " " "    r2cT|}|t|}tj|||S)aGiven a ResultProxy cursor as returned by connection.execute(), return an ORM result as an iterator. e.g.:: result = engine.execute("select * from users") for u in session.query(User).instances(result): print u )r'rr})r.cursor_Query__contextrls r0r}zQuery.instances7s0 ?"4((G vw777r2c.tj|||S)akMerge a result into this :class:`_query.Query` object's Session. Given an iterator returned by a :class:`_query.Query` of the same structure as this one, return an identical iterator of results, with all mapped instances merged into the session using :meth:`.Session.merge`. This is an optimized method which will merge all mapped instances, preserving the structure of the result rows and unmapped columns with less method overhead than that of calling :meth:`.Session.merge` explicitly for each value. The structure of the results is determined based on the column list of this :class:`_query.Query` - if these do not correspond, unchecked errors will occur. The 'load' argument is the same as that of :meth:`.Session.merge`. For an example of how :meth:`_query.Query.merge_result` is used, see the source code for the example :ref:`examples_caching`, where :meth:`_query.Query.merge_result` is used to efficiently restore state from a cache back into a target :class:`.Session`. )r merge_result)r.iteratorloads r0rzQuery.merge_resultGs4#D(D999r2c`|j|j|j|j|j|jpd|jdS)N)rLrNrrRrUrr)rrrrxryrrwrs r0 _select_argszQuery._select_argscs;[l.$l   r2c|j}|ddupB|ddup+|ddp|ddS)NrLrNrFr)rrvrs r0_should_nest_selectablezQuery._should_nest_selectableosj" JJw  t + -zz(##4/ -zz*e,, -zz*e,,  r2ctj|dtjdjdgS)aA convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...). e.g.:: q = session.query(User).filter(User.name == 'fred') session.query(q.exists()) Producing SQL similar to:: SELECT EXISTS ( SELECT 1 FROM users WHERE users.name = :name_1 ) AS anon_1 The EXISTS construct is usually used in the WHERE clause:: session.query(User.id).filter(q.exists()).scalar() Note that some databases such as SQL Server don't allow an EXISTS expression to be present in the columns clause of a SELECT. To select a simple boolean value based on the exists as a WHERE, use :func:`.literal`:: from sqlalchemy import literal session.query(literal(True)).filter(q.exists()).scalar() F1r)rexistsrrliteral_columnrrwith_only_columnsrs r0rz Query.existsys^Fz  " "5 ) ) [+C00 1 1 []] ((!--    r2ctjtjd}||S)aReturn a count of rows this the SQL formed by this :class:`Query` would return. This generates the SQL for this Query as follows:: SELECT count(1) AS count_1 FROM ( SELECT ) AS anon_1 The above SQL returns a single row, which is the aggregate value of the count function; the :meth:`_query.Query.count` method then returns that single integer value. .. warning:: It is important to note that the value returned by count() is **not the same as the number of ORM objects that this Query would return from a method such as the .all() method**. The :class:`_query.Query` object, when asked to return full entities, will **deduplicate entries based on primary key**, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present. This does not apply to a query that is against individual columns. .. seealso:: :ref:`faq_query_deduplicating` :ref:`orm_tutorial_query_returning` For fine grained control over specific columns to count, to skip the usage of a subquery or otherwise control of the FROM clause, or to use other aggregate functions, use :attr:`~sqlalchemy.sql.expression.func` expressions in conjunction with :meth:`~.Session.query`, i.e.:: from sqlalchemy import func # count User records, without # using a subquery. session.query(func.count(User.id)) # return count of user "id" grouped # by "name" session.query(func.count(User.id)).\ group_by(User.name) from sqlalchemy import distinct # count distinct "name" values session.query(func.count(distinct(User.name))) r)rfuncr'rrqrh)r.cols r0r'z Query.countsAnhnnS/4455~~c""))+++r2evaluatecxtj||}||jS)afPerform a bulk delete query. Deletes rows matched by this query from the database. E.g.:: sess.query(User).filter(User.age == 25).\ delete(synchronize_session=False) sess.query(User).filter(User.age == 25).\ delete(synchronize_session='evaluate') .. warning:: The :meth:`_query.Query.delete` method is a "bulk" operation, which bypasses ORM unit-of-work automation in favor of greater performance. **Please read all caveats and warnings below.** :param synchronize_session: chooses the strategy for the removal of matched objects from the session. Valid values are: ``False`` - don't synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, objects may still remain in the session which were in fact deleted which can lead to confusing results if they are accessed via get() or already loaded collections. ``'fetch'`` - performs a select query before the delete to find objects that are matched by the delete query and need to be removed from the session. Matched objects are removed from the session. ``'evaluate'`` - Evaluate the query's criteria in Python straight on the objects in the session. If evaluation of the criteria isn't implemented, an error is raised. The expression evaluator currently doesn't account for differing string collations between the database and Python. :return: the count of rows matched as returned by the database's "row count" feature. .. warning:: **Additional Caveats for bulk query deletes** * This method does **not work for joined inheritance mappings**, since the **multiple table deletes are not supported by SQL** as well as that the **join condition of an inheritance mapper is not automatically rendered**. Care must be taken in any multiple-table delete to first accommodate via some other means how the related table will be deleted, as well as to explicitly include the joining condition between those tables, even in mappings where this is normally automatic. E.g. if a class ``Engineer`` subclasses ``Employee``, a DELETE against the ``Employee`` table would look like:: session.query(Engineer).\ filter(Engineer.id == Employee.id).\ filter(Employee.name == 'dilbert').\ delete() However the above SQL will not delete from the Engineer table, unless an ON DELETE CASCADE rule is established in the database to handle it. Short story, **do not use this method for joined inheritance mappings unless you have taken the additional steps to make this feasible**. * The polymorphic identity WHERE criteria is **not** included for single- or joined- table updates - this must be added **manually** even for single table inheritance. * The method does **not** offer in-Python cascading of relationships - it is assumed that ON DELETE CASCADE/SET NULL/etc. is configured for any foreign key references which require it, otherwise the database may emit an integrity violation if foreign key references are being enforced. After the DELETE, dependent objects in the :class:`.Session` which were impacted by an ON DELETE may not contain the current state, or may have been deleted. This issue is resolved once the :class:`.Session` is expired, which normally occurs upon :meth:`.Session.commit` or can be forced by using :meth:`.Session.expire_all`. Accessing an expired object whose row has been deleted will invoke a SELECT to locate the row; when the row is not found, an :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. * The ``'fetch'`` strategy results in an additional SELECT statement emitted and will significantly reduce performance. * The ``'evaluate'`` strategy performs a scan of all matching objects within the :class:`.Session`; if the contents of the :class:`.Session` are expired, such as via a proceeding :meth:`.Session.commit` call, **this will result in SELECT queries emitted for every matching object**. * The :meth:`.MapperEvents.before_delete` and :meth:`.MapperEvents.after_delete` events **are not invoked** from this method. Instead, the :meth:`.SessionEvents.after_bulk_delete` method is provided to act upon a mass DELETE of entity rows. .. seealso:: :meth:`_query.Query.update` :ref:`inserts_and_updates` - Core SQL tutorial )r BulkDeletefactoryexec_rowcount)r.synchronize_session delete_ops r0deletez Query.deletes7p *2249LMM !!r2c|pi}tj||||}||jS)aPerform a bulk update query. Updates rows matched by this query in the database. E.g.:: sess.query(User).filter(User.age == 25).\ update({User.age: User.age - 10}, synchronize_session=False) sess.query(User).filter(User.age == 25).\ update({"age": User.age - 10}, synchronize_session='evaluate') .. warning:: The :meth:`_query.Query.update` method is a "bulk" operation, which bypasses ORM unit-of-work automation in favor of greater performance. **Please read all caveats and warnings below.** :param values: a dictionary with attributes names, or alternatively mapped attributes or SQL expressions, as keys, and literal values or sql expressions as values. If :ref:`parameter-ordered mode ` is desired, the values can be passed as a list of 2-tuples; this requires that the :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order` flag is passed to the :paramref:`.Query.update.update_args` dictionary as well. .. versionchanged:: 1.0.0 - string names in the values dictionary are now resolved against the mapped entity; previously, these strings were passed as literal column names with no mapper-level translation. :param synchronize_session: chooses the strategy to update the attributes on objects in the session. Valid values are: ``False`` - don't synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, updated objects may still remain in the session with stale values on their attributes, which can lead to confusing results. ``'fetch'`` - performs a select query before the update to find objects that are matched by the update query. The updated attributes are expired on matched objects. ``'evaluate'`` - Evaluate the Query's criteria in Python straight on the objects in the session. If evaluation of the criteria isn't implemented, an exception is raised. The expression evaluator currently doesn't account for differing string collations between the database and Python. :param update_args: Optional dictionary, if present will be passed to the underlying :func:`_expression.update` construct as the ``**kw`` for the object. May be used to pass dialect-specific arguments such as ``mysql_limit``, as well as other special arguments such as :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`. .. versionadded:: 1.0.0 :return: the count of rows matched as returned by the database's "row count" feature. .. warning:: **Additional Caveats for bulk query updates** * The method does **not** offer in-Python cascading of relationships - it is assumed that ON UPDATE CASCADE is configured for any foreign key references which require it, otherwise the database may emit an integrity violation if foreign key references are being enforced. After the UPDATE, dependent objects in the :class:`.Session` which were impacted by an ON UPDATE CASCADE may not contain the current state; this issue is resolved once the :class:`.Session` is expired, which normally occurs upon :meth:`.Session.commit` or can be forced by using :meth:`.Session.expire_all`. * The ``'fetch'`` strategy results in an additional SELECT statement emitted and will significantly reduce performance. * The ``'evaluate'`` strategy performs a scan of all matching objects within the :class:`.Session`; if the contents of the :class:`.Session` are expired, such as via a proceeding :meth:`.Session.commit` call, **this will result in SELECT queries emitted for every matching object**. * The method supports multiple table updates, as detailed in :ref:`multi_table_updates`, and this behavior does extend to support updates of joined-inheritance and other multiple table mappings. However, the **join condition of an inheritance mapper is not automatically rendered**. Care must be taken in any multiple-table update to explicitly include the joining condition between those tables, even in mappings where this is normally automatic. E.g. if a class ``Engineer`` subclasses ``Employee``, an UPDATE of the ``Engineer`` local table using criteria against the ``Employee`` local table might look like:: session.query(Engineer).\ filter(Engineer.id == Employee.id).\ filter(Employee.name == 'dilbert').\ update({"engineer_type": "programmer"}) * The polymorphic identity WHERE criteria is **not** included for single- or joined- table updates - this must be added **manually**, even for single table inheritance. * The :meth:`.MapperEvents.before_update` and :meth:`.MapperEvents.after_update` events **are not invoked from this method**. Instead, the :meth:`.SessionEvents.after_bulk_update` method is provided to act upon a mass UPDATE of entity rows. .. seealso:: :meth:`_query.Query.delete` :ref:`inserts_and_updates` - Core SQL tutorial )r BulkUpdaterrr)r.rr update_args update_ops r0rz Query.updateYsLD"'R *22 %v{   !!r2c|jjr0|jjD]#}||}|||ur|}|jsd|_$t|}|j|S||_|j|_|jD]}||||j D]}|d}||g|ddR|j rt|j |_ |j r|||js/|jrt#jdt#jd|jr"|jr|||_n|||_|S)NFrrzyNo column-based properties specified for refresh operation. Use session.expire() to reload collections and related items.z4Query contains no columns with which to SELECT from.)dispatchbefore_compile_bake_okr'rrrKr5 setup_contextcreate_eager_joins from_clauserFfromsro_adjust_for_single_inheritanceprimary_columnsrrZrmulti_row_eager_loadersr_compound_eager_statement_simple_statement)r.rr new_queryrlrLrecstrategys r0rzQuery._compile_contexts = ' .m2 . .BtHH (Yd-B-B$D;.(- t$$   (N"&"6n 0 0F  w / / / /- ( (C1vH HW 's122w ' ' ' ' '   6!!455GM  # 9  / / 8 8 8& $ 0? 0M  * @t/K @ $ > >w G GG   $ 6 6w ? ?G r2cb|jr tj|j|j}n d|_g}t j|j|z|jf|j|j|jd|j }|j |_ |j D] }|j |} |j r|j|j }|}|}tj|||_t j|g|jz|j}|j |j j |j |_ |}|jD]}tj|||j}|||jr'|j|j|j|j|j|S)Nrkrjr)rj)rrE expand_column_list_from_order_byrrselectrrrrrKrrrTrXr`rerFrSsecondary_columnsr eager_joinsr splice_joinsstop_on append_fromappend_order_bycopy_and_processeager_order_by) r.rlorder_by_col_exprinnerhintrmrr eager_joins r0rzQuery._compound_eager_statements   # ( I')9!!   $G  "   #&7 7    ]~%      !( 7$ + +D#EOT*EE ? 6#EOT_5E ""$$"0??J Gg/ /GN     # /'*2(/(?I % !-4466  J#/Z);KK k***    %I %11'2BCC   " !7#9::r2c|jsd|_|jdur4|jr-|xjtj|j|jz c_|xjt |jz c_tj |j|j z|j f|j|j |jd|j}|j|_|jD] }|j|} |jr|j|j}|jr|j|j|S)NTr)rrrrErrrarrrrrrrrrKrrrTrXrr)r.rlrrs r0rzQuery._simple_statementas? $#G  >T ! !g&6 !  # #9%w'7(9(9 9 # #  w299;;<<< J  #g&? ?   ]~%      %,$; !$ 3 3D+ +T2II ? >+ +T_=I  ! ? %I %w'= > >r2ct|j}|jrP|j|jvrBt |j}|jr|j}nd}||j|fg}|D]\}}||jvr|j j }|j|r| |}| |dd}tjtj|j||_dS)amApply single-table-inheritance filtering. For all distinct single-table-inheritance mappers represented in the columns clause of this query, as well as the "select from entity", add criterion to the WHERE clause of the given QueryContext such that only the appropriate subtypes are selected from the total results. NF)rr>rrYrr@rIr&r*rA_single_table_criteriontraverserrand_True__ifnoner)r.rlrzrrSrM single_crits r0rz$Query._adjust_for_single_inheritances!T-446677  $ I(0HHH4344D$ -\\D$rrfr immutabledictrvrr%rrrrrorr_path_registryrr7rrr1r-r9rDrnrqr{rr rrrrrrrgrrrrrrerrrrrrrrrrrrrrrGrr rrrrrrrrBr(rvr PASSIVE_OFFr4r*rXr\rr`rrjrlrqrtrnr_valuesr rrpending_deprecationrrrrrrrrr deprecatedrrrrfrrrrrr&rrrrrrrrrrrrrrr8r<r>rIrArLrNrrSrVrXr[r_rcrfrhrmrtryrkrrorr}rrrrr'rrrrrrr)r2r0r&r&>s , LJJIIGIIIG FOJJNJN"INOO/T/111I ++-- d ""G$$$&&KMKO#"M H"H%%%%@99998--->DDD -1-1-1^DDD ///$   []]&&]&[]]%%]%+B+B+BZ!!!(((    X MMM000####    LLL$AAAA+++       (   X """"@9 9 9 9 v C C CCCC ) )X )EEE[]] ) )] )  X *[]]((]("   []]!!]!4[]]((](*X[]] " "] "[,-->B   .- B[]]C C ]C JVBVBVBx& 4M4M4M4Ml=6=6=6=6~[]]]:[]] " "] "[]]'']'&[]]((](5P5P5P5Pn[]] * * *] *[]]]2yyyv[]]'']'[]];;];6   G[]]%%]%4[]] 9 9] 9T F  ((  (+++$***[]] ( (] (&[]]@@@]@68888( ' ' '[]]HH]H"[]]T_  1DD]D6[]]  8 8 8 ]8 t[]]$$]$([(*:;;!,!,<;!,F&%&%&%P[(*:;;88<;86[(*:;;88<;84[(*:;; % %<; %D))) %2%2%2N666666:::444777c c c J    2   [(*:;;XX<;XtKKKZf>f>f>P@8@8@8D`/`/`/D"""[())   *)  [,--././.-./`[,--p0p0.-p0d666:[())+ + *)+ Z[())*)[())*)[())&&*)&>[]]&&]&<[]]&&]&*$[,--$$.-$<:"""H@6444 4 4 4 KKK000   = = X= ~8888 ::::8   X    X ( ( ( T8,8,8,tz"z"z"z"xG"G"G"G"R4444lGGGR<"""""r2r&c$eZdZedZdS)rc|dvrdS|dkrd}d}n-|dkrdx}}n"|dkrd}d}ntjd|zt||S) NrrTFr update_nowaitz"Unknown with_lockmode argument: %r)rr)rZr[r)r.rrrs r0rzLockmodeArg.parse_legacy_querys = 4 6>>DFF X  ! !D66 _ $ $FDD&4t; V4444r2N)rerr classmethodrr)r2r0rrs-55[555r2rceZdZdZdZdZdS)r4z:Represent an entity column returned within a Query result.c|tur]|d}t|tjst |rt }n$t|t rt}nt}t |S)Nr) r4r^r rrrBundle _BundleEntityrobjectr)rrVrrLs r0rz_QueryEntity.__new__sy ,  !WFfd&788 $=M>> $$FF++ $##~~c"""r2c|j|j}|j|_|Sr=rrs r0rz_QueryEntity._clones3 N " "4> 2 2]'')) r2N)rerrrrrr)r2r0r4r4s8DD # # #r2r4c|eZdZdZdZdZdZdZdZe dZ e dZ dZ d Z d Zd Zd Zd ZdS)rz mapper/class/AliasedClass entityc|js||_|j|d|_|g|_||_dSr)r6r5r\r7r/rP)r.r~rLs r0r1z_MapperEntity.__init__sG$ )$(E ! t$$$%)"  r2Tc|j|_||_|j|_|j|_|j|_|j|_||_|jr|jj |_ n|jj j |_ |jj |_dSr=)rArNrGr@with_polymorphic_mappers_with_polymorphicr_polymorphic_discriminatorrrrrMrerrr.rMrNs r0rJz_MapperEntity.setup_entityso ."- ( 9!)!B*2*A'#  $ ;#/4D  #{1:D $3 r2cD|jrtd|||jdS|j||\}}||_||_||_||jtj ||jj dS)zReceive an update from a call to :meth:`_query.Query.with_polymorphic`. Note the newer style of using a free standing ``with_polymporphic()`` construct doesn't make use of this method. z6Can't use with_polymorphic() against an Aliased objectN) r@NotImplementedErrorrqrA_with_polymorphic_argsrrrGrDrErFrH)r.r~r rGrmappersrks r0rz"_MapperEntity.set_with_polymorphics   %K   !  , ,T[ 9 9 9 F K>> J  ")*8'" 00 K  "8T[-L M M     r2c|jjSr=)rArMrs r0rz_MapperEntity.types {!!r2c|jSr=)rrs r0rz'_MapperEntity.entity_zero_or_selectables r2c,t|j|Sr=)rrr.rLs r0r"z_MapperEntity.corresponds_tos%d&6???r2c:|j|dSr=)r5r\)r.r~sels r0rzz!_MapperEntity.adapt_to_selectables t$$$$$r2cd}|js(|jr |j|jd}n|j}|r%|jr||j}n |}n|j}|Sr=)r@r,rvrArNrfwrap)r.r~rlrSr^s r0_get_entity_clausesz!_MapperEntity._get_entity_clausess~$ +* M599$+tLL*G  ($ ll5#899'C r2c |||}|jr|r||j}n |s|j}|s0|jjr$t j|j|jj}|j |ur|j }|j }ndx}}tj |j|||j||||j}||jfS)N)rrpolymorphic_discriminator)rrSrrA_requires_row_aliasingrErFrGrHr6rrr_instance_processorrrr)r.r~rlrrSrr _instances r0 row_processorz_MapperEntity.row_processor0s**5':: ? &w &ll7?33GG &oG  4;= ,!@G  D ( (#4O#1MM.2 2Om/ K   I +'&*&E    $***r2c |||}|xj|jfz c_|jdurP|jjrD|jj|_|r1|t j|j|_tj ||j||j ||j |j |j |j dS)NF)rBrr)rrrGrrA adapt_listr r8r_setup_entity_queryrrrrr)r.r~rlrSs r0rz_MapperEntity.setup_contextSs**5'::  $/++  u $ $)= $#{3G  #*#5#5L!122$$  #  K  I   #!3!2&*&E r2c*t|jSr=)rrArs r0rtz_MapperEntity.__str__n4;r2N)rerrrr1r use_id_for_hashrJrrgrrr"rzrrrrtr)r2r0rrs**"O 4 4 4   B""X"  X @@@%%%(!+!+!+F   6     r2rcdeZdZdZdZ dZdZdZdZdZ dZ dZ dZ e dZdZd ZdS) raMA grouping of SQL expressions that are returned by a :class:`_query.Query` under one namespace. The :class:`.Bundle` essentially allows nesting of the tuple-based results returned by a column-oriented :class:`_query.Query` object. It also is extensible via simple subclassing, where the primary capability to override is that of how the set of expressions should be returned, allowing post-processing as well as custom return types, without involving ORM identity-mapped classes. .. versionadded:: 0.9.0 .. seealso:: :ref:`bundles` Fc|x|_|_||_tx|_|_|jd|D|d|j|_dS)aQConstruct a new :class:`.Bundle`. e.g.:: bn = Bundle("mybundle", MyClass.x, MyClass.y) for row in session.query(bn).filter( bn.c.x == 5).filter(bn.c.y == 4): print(row.mybundle.x, row.mybundle.y) :param name: name of the bundle. :param \*exprs: columns or SQL expressions comprising the bundle. :param single_entity=False: if True, rows for this :class:`.Bundle` can be returned as a "single entity" outside of any enclosing tuple in the same manner as a mapped entity. c3FK|]}t|d|j|fVdS)r3N)r_label)rrs r0r=z"Bundle.__init__..sF  7:WS% , ,c 2      r2 single_entityN) rr exprsr#r<rrrpr )r.rr rws r0r1zBundle.__init__s$#'& DK 0 2 22   >C       VVOT5GHHr2Nc|j|j}|j|j|Sr=)rrrr)r.cloneds r0rz Bundle._clones6''77t}--- r2c.tj|jddiS)NgroupF)r! ClauseListr rs r0rzBundle.__clause_element__s$4:>5>>>r2c4|jSr=)rrrs r0rzBundle.clausess&&((00r2c<|}||_|S)z.proc..s!<<.procs);<<< > > > > > r2)rerrrr rrXr@r1rr<rrrgrrrr)r2r0rrrs&M<IIII4G0 A/ ???11X1r2rceZdZdZddZedZedZedZdZ edZ d Z d Z d Z d Zd S)rFTcJ|j||x|_|_t ||_|j|_g|_|r@|jD]8}t|trt||(t||9|jj |_ dSr=)r5r\bundlerPrrrr r^rrrr r )r.r~rsetup_entitiesrPs r0r1z_BundleEntity.__init__s t$$$"(( diLL !;  .  . .dF++.!$----!$----&*k&?###r2c&|j}||jSdSr=)rrA)r.rs r0rAz_BundleEntity.mappers   < 4r2cRg}|jD]}||j|Sr=)r5extendr/)r.r/r;s r0r/z_BundleEntity.entitiess4> * *C OOCL ) ) ) )r2c4|jD]}|j}||cSdSr=)r5rr.r;rs r0rz_BundleEntity.entity_zeros5>  COE  !4r2cdSrr)rs r0r"z_BundleEntity.corresponds_tos ur2c4|jD]}|j}||cSdSr=)r5rr%s r0rz'_BundleEntity.entity_zero_or_selectables6>  C1E  !4r2ctt||jd}|jD]}|||dS)NF)r )rrr5rz)r.r~rr<r;s r0rzz!_BundleEntity.adapt_to_selectable%sN %U C C C > , ,C  # #As + + + + , ,r2cF|jD]}|||dSr=)r5rJ)r.rMrNr;s r0rJz_BundleEntity.setup_entity.s6> 8 8C   X 7 7 7 7 8 8r2cF|jD]}|||dSr=)r5r)r.r~rlr;s r0rz_BundleEntity.setup_context2s6> . .C   eW - - - - . .r2ctfd|jD\}}|j||}||jfS)Nc>g|]}|Sr))r)rr;rlr~rs r0rz/_BundleEntity.row_processor..8s;!!%&99r2)zipr5rrr)r.r~rlrrrrs ``` r0rz_BundleEntity.row_processor6sn> v{//ufEET%%%r2Nr~)rerrrr1rgrAr/rr"rrzrJrrr)r2r0rrsO@@@@ XX X X,,,888... & & & & &r2rcXeZdZdZd dZdZedZdZdZ dZ d Z d Z d Z dS) rzColumn/expression based entity.Nc> ||_||_d}d}t|tjr;tjdt j|}|j|_ d}d}d}nt|tj tj fr^t|dd}|d}|j|_ |}d}t|t"rt%||dSt|t jsLt)|dr$|jD]}||urnt-|||dSt/jd|d|st|d d|_ d}|jx|_}|j |_|js+t|d ds||j }|j|||_ tC|_"tG|j$|_%tC|j% |sG||_&|r|g|_'|j(|_(ng|_'d|_(tC|j'|_)dSd tUj+|d D} tj,d | D|_'tC fd| D|_)|j'r%|j'd|_&|j&j(|_(dS|j|j|_&d|_(dSd|_&d|_(dS)NTFzPlain string expression passed to Query() should be explicitly declared using literal_column(); automatic coercion of this value will be removed in SQLAlchemy 1.4r_select_iterable) namespacez9SQL expression, column, or mapped entity expected - got 'rbr3 is_literalc$g|] }d|jv |Srsrrrs r0rz*_ColumnEntity.__init__..s4"T%666 766r2)include_scalar_selectsc:g|]}d|jv |jdSr4rr5s r0rz*_ColumnEntity.__init__..s8%):::%n5:::r2cpg|]2}d|jv |j%|jd3Sr4)ru intersection _from_objects)rr actual_fromss r0rz*_ColumnEntity.__init__..sR%):::$11$2DEE;%n5:::r2r)-rPr1r^r rwarn_deprecatedrrrrrrrrrr3_query_clause_elementrr ColumnElementrWr0rrZrrhashablerr rr5r\rrrrFr:r;rr/rA_from_entitiesrEsurface_column_elements unique_list) r.r~rr1search_entities check_column_entityr<type_ all_elementsr;s @r0r1z_ColumnEntity.__init__Fs " fd/ 0 0   !    '//F%{D #OLGG  Z2J4MN  fot<1} 4WV\5%I%I 4\\$"233F t$$$ UU !!5664,-- * #&D  #!(  %n " " "%dm"4"4D   $<5L!, ,DM#& ,##D } ##'=#3 ".5 +#'> " #' " r2FcJ|j|jS|jr |jdSdS)Nr)rr;rs r0rz'_ColumnEntity.entity_zero_or_selectables2   '# #   $Q' '4r2ct|||j}|j|_|j|_|j|_dSr=)rcorresponding_columnrrrr/)r.r~rr<s r0rzz!_ColumnEntity.adapt_to_selectablesB %!9!9$+!F!F G G( ( ] r2cd|jvr |j|_t|j|jjr!|j|jdSdS)NrG)rrGrr;r9r:raddrs r0rJz_ColumnEntity.setup_entitysn t} , ,&1DO t ! ! . .   -   0 JNN8. / / / / / 0 0r2c|jdSt|r ||juSt|j o||jSr)rrr)rs r0r"z_ColumnEntity.corresponds_tosd   #5 v & & 9T-- -( 9&&t'788 9r2cd|f|jvr|jd|f}n||jdd}|jr|}|jr|jj|}||}||jfS)N fetch_columnFT) rrrru _deannotaterSr_getterr)r.r~rlrrgetters r0rz_ColumnEntity.row_processors D !W%7 7 7'(>?FF((eTBBF   *''))F ? 5_,V4F''t'''r2c||jdd}|jr|}|xjt |jz c_|j|||jd|f<dS)NFTrO) rrrurPrrarr\r)r.r~rlrs r0rz_ColumnEntity.setup_contexts$$T[%>>   *''))F tz*** &&v...5;ND1222r2c*t|jSr=)rrrs r0rtz_ColumnEntity.__str__rr2r=)rerrrr1r rgrrzrJr"rrrtr)r2r0rrCs))v#v#v#v#p# X### 000 9 9 9(((" < < <     r2rceZdZdZdZdS)r')rrSr for_updater~r+r\rinvoke_all_eagersrrrrrrrpropagate_optionsrrrrrrrKrunidpartialspost_load_pathsrc|jct|jtjr7|jjs+|jjs|j|_n8|j|_n+d|_|j|_ |j |_ |j |_ d|_d|_d|_d|_||_|j|_|j|_|j|_|j|_|j|_|j|_g|_g|_g|_ i|_!g|_"tGd|j$D|_%|j&'|_(|j|j)|_*dSd|_*dS)NFr)c3(K|] }|j |VdSr=)propagate_to_loaders)rrs r0r=z(QueryContext.__init__..Fs>% % a.D% % % % % % % r2)+rr^r!r__textualrj apply_labelsrrbrrrrrrrSrrVr~r+rZr\rrr_rWrrrrrrrrrrrrXrr?rrr)r.r~s r0r1zQueryContext.__init__%s   '5+Z-BCC 2(1 2(3 2 "'!1!>!>!@!@!&!1!DN$D $/D !ODM',$   } )!&!9!&!9"1"1!!# "$!$% % *% % % " "  +0022   )"'"?D   "&D   r2N)rerr __slots__r1r)r2r0r'r's*I>('('('('('r2r'ceZdZdZdZdS) AliasOptionc||_dS)a"Return a :class:`.MapperOption` that will indicate to the :class:`_query.Query` that the main table has been aliased. This is a seldom-used option to suit the very rare case that :func:`.contains_eager` is being used in conjunction with a user-defined SELECT statement that aliases the parent table. E.g.:: # define an aliased UNION called 'ulist' ulist = users.select(users.c.user_id==7).\ union(users.select(users.c.user_id>7)).\ alias('ulist') # add on an eager load of "addresses" statement = ulist.outerjoin(addresses).\ select().apply_labels() # create query, indicating "ulist" will be an # alias for the main table, "addresses" # property should be eager loaded query = session.query(User).options( contains_alias(ulist), contains_eager(User.addresses)) # then get results via the statement results = query.from_statement(statement).all() :param alias: is the string name of an alias, or a :class:`_expression.Alias` object representing the alias. N)r`)r.r`s r0r1zAliasOption.__init__QsB r2ct|jtjr2|j|j}n|j}t j||_dSr=) r^r`r rrrCrErFrf)r.r~r`s r0rzAliasOption.process_queryts_ dj$"3 4 4 &&((;AA$*MMEEJE ( 6u = =r2N)rerrr1rr)r2r0rcrcPs3!!!F>>>>>r2rcN);r itertoolsrrrrarrr r baser r rrrr path_registryrr rrrrrrrrrZrrrrr!rEr"sql.baser#sql.expressionr$sql.selectabler%__all__rootr_self_inspects class_loggerrr&rr4rrrrr' MapperOptionrcr)r2r0rrsl  $$$$$$######"""""" ''''''((((((""""""""""""''''''//////)))))) . . ." aAaAaAaAaAFaAaAaAHC55555,555,6,_ _ _ _ _ L_ _ _ D vvvvv^vvvrT&T&T&T&T&LT&T&T&n     L   DH'H'H'H'H'6H'H'H'V)>)>)>)>)>*))>)>)>)>)>r2