B ÃÌ4].¢ã@sHdZddlmZddlmZddlmZddlmZddlmZddlm 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*d#d$d%gZ+ej,Z-ej.e j/Gd&d#„d#e0ƒƒƒZ1Gd'd(„d(e*ƒZ2Gd)d*„d*e0ƒZ3Gd+d,„d,e3ƒZ4ej.Gd-d.„d.eƒƒZ5Gd/d0„d0e3ƒZ6Gd1d2„d2e3ƒZ7Gd3d$„d$e0ƒZ8Gd4d5„d5ej9ƒZ:d6S)7añThe Query class and support. Defines the :class:`.Query` class, the central construct used by the ORM to construct database queries. The :class:`.Query` class should not be confused with the :class:`.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@s¦eZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZeƒZdZdZdZdZdZdZdZdZdZdZiZ dZ!dZ"e# $¡Z%Z&e# $¡Z'e# $¡Z(e# $¡Z)dZ*dZ+dZ,dZ-dZ.e/Z0dZ1dZ2ddd„Z3ddd „Z4d d „Z5d d „Z6dd„Z7dd„Z8dd„Z9dd„Z:e;ƒdd„ƒZdd„Z?dd„Z@d d!„ZAeBd"d#„ƒZCd$d%„ZDd&d'„ZEd(d)„ZFdd*d+„ZGd,d-„ZHd.d/„ZId0d1„ZJdd2d3„ZKdd4d5„ZLd6d7„ZMd8d9„ZNd:d;„ZOddd?„ZQeBd@dA„ƒZRddBdC„ZSddDdE„ZTdFdG„ZUdHdI„ZVeBdJdK„ƒZWdLdM„ZXe;ƒdNdO„ƒZYe;ƒdPdQ„ƒZZdRdS„Z[e;ƒdTdU„ƒZ\e;ƒdVdW„ƒZ]eBdXdY„ƒZ^e;ƒdZd[„ƒZ_e;eMƒdd\d]„ƒZ`e;ƒd^d_„ƒZad`da„Zbdecjddfdbdc„Zedddde„Zfe;ƒdfdg„ƒZge;ƒdhdi„ƒZhe;ƒdjdk„ƒZie;ƒdldm„ƒZjddndo„Zke;ƒddpdq„ƒZle;ƒdrds„ƒZmdtdu„Zne;ƒdvdw„ƒZoe;ƒdxdy„ƒZpdzd{„ZqeqZrd|d}„Zse;ƒd~d„ƒZte;ƒd€d„ƒZue# vd‚dƒd¡d„d…„ƒZwd†d‡„Zxdˆd‰„Zye;ƒdŠd‹„ƒZzdŒd„Z{e;ƒddd„ƒZ|dd‘d’„Z}d“d”„Z~e;ƒd•d–„ƒZe;ƒe# €d—d˜¡d™dš„ƒƒZe;ƒdd›dœ„ƒZ‚e;ƒddž„ƒZƒe;eNeOƒdŸd „ƒZ„d¡d¢„Z…e;eNeOƒd£d¤„ƒZ†e;eNeOƒd¥d¦„ƒZ‡e;eNeOƒd§d¨„ƒZˆd©dª„Z‰d«d¬„ZŠd­d®„Z‹d¯d°„ZŒd±d²„Zd³d´„ZŽdµd¶„Zd·d¸„Zd¹dº„Z‘d»d¼„Z’e;eNeOƒd½d¾„ƒZ“d¿dÀ„Z”dÁd„Z•dÃdÄ„Z–dÅdÆ„Z—dÇdÈ„Z˜e;eNƒdÉdÊ„ƒZ™e;eMƒdËdÌ„ƒZše;eMƒdÍd΄ƒZ›dÏdЄZœe;eNƒdÑdÒ„ƒZe;eNƒdÓdÔ„ƒZže;eNƒdÕdÖ„ƒZŸe;eNƒd×dØ„ƒZ e;ƒdÙdÚ„ƒZ¡e;ƒdÛdÜ„ƒZ¢dÝdÞ„Z£e;eMƒdßdà„ƒZ¤dádâ„Z¥dãdä„Z¦dådæ„Z§dçdè„Z¨dédê„Z©dëdì„Zªdídî„Z«dïdð„Z¬dñdò„Z­dódô„Z®eBdõdö„ƒZ¯dd÷dø„Z°d dùdú„Z±eBdûdü„ƒZ²eBdýdþ„ƒZ³dÿd„Z´dd„Zµd!dd„Z¶d"dd„Z·d#dd „Z¸d d „Z¹d d „Zºdd„Z»dS($r#aLORM-level SQL construction object. :class:`.Query` is the source of all SELECT statements generated by the ORM, both those formulated by end-user query operations as well as by high level internal operations such as related collection loading. It features a generative interface whereby successive calls return a new :class:`.Query` object, a copy of the former with additional criteria and options associated with it. :class:`.Query` objects are normally initially generated using the :meth:`~.Session.query` method of :class:`.Session`, and in less common cases by instantiating the :class:`.Query` directly and associating with a :class:`.Session` using the :meth:`.Query.with_session` method. For a full walkthrough of :class:`.Query` usage, see the :ref:`ormtutorial_toplevel`. FTN©cCs||_i|_| |¡dS)a‡Construct a :class:`.Query` directly. E.g.:: q = Query([User, Address], session=some_session) The above is equivalent to:: q = some_session.query(User, Address) :param entities: a sequence of entities and/or SQL expressions. :param session: a :class:`.Session` with which the :class:`.Query` will be associated. Optional; a :class:`.Query` can be associated with a :class:`.Session` generatively via the :meth:`.Query.with_session` method as well. .. seealso:: :meth:`.Session.query` :meth:`.Query.with_session` N)ÚsessionÚ_polymorphic_adaptersÚ _set_entities)ÚselfÚentitiesr&r%r%úG/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/query.pyÚ__init__szQuery.__init__cCsT|dkr t}g|_d|_d|_|dk rPxt |¡D]}|||ƒq2W| |j¡dS)NFr%)Ú _QueryEntityÚ _entitiesÚ_primary_entityÚ_has_mapper_entitiesrÚto_listÚ_set_entity_selectables)r)r*Úentity_wrapperÚentr%r%r+r(ªszQuery._set_entitiesc Cs¬|j ¡|_}x–|D]Ž}xˆ|jD]~}||kr’t|ƒ}|jst|jjrt|jj|jkrn|  |jt   |j |jj ¡¡d}n|jr‚|j}nd}||f||<|j||Žq"WqWdS)N)Ú_mapper_adapter_mapÚcopyr*rÚis_aliased_classÚmapperÚwith_polymorphicÚpersist_selectabler'Ú"_mapper_loads_polymorphically_withÚsql_utilÚ ColumnAdapterÚ selectableÚ_equivalent_columnsÚ_adapterÚ setup_entity)r)r*Údr4ÚentityÚext_infoÚaliased_adapterr%r%r+r2Ês(    zQuery._set_entity_selectablescCsBx<|jp |gD],}||j|<x| ¡D]}||j|j<q&WqWdS)N)Ú_with_polymorphic_mappersr'Úiterate_to_rootÚ local_table)r)r8ÚadapterÚm2Úmr%r%r+r;és z(Query._mapper_loads_polymorphically_withcCsg}d}xŠ|D]‚}t|ƒ}t|dƒrX|js0|jrX||_|rJ|jsJt d¡‚| |j¡q|j sjt d¡‚qt |t j ƒr~|  ¡}|r†|}| |¡qWt|ƒ|_|rÚt|jƒdkrÚt |t jƒrÚ| ¡}t |jd|¡|_n2|r t|jƒdkr t|dƒr |jr |j|_dS)Nr8zPA selectable (FromClause) instance is expected when the base alias is being set.zJargument is not a mapped class, mapper, aliased(), or FromClause instance.rr)rÚhasattrÚ is_mapperr7Ú_select_from_entityÚsa_excÚ ArgumentErrorÚappendr>Ú is_selectableÚ isinstancerÚ SelectBaseÚaliasÚtupleÚ _from_objÚlenÚAliasÚ_Query__all_equivsr<r=Ú_from_obj_aliasr@)r)ÚobjZset_base_aliasÚfaZselect_from_aliasÚfrom_objÚinfoÚequivsr%r%r+Ú_set_select_fromïs>        zQuery._set_select_fromcCsDx>|jD]4}|j |d¡x | ¡D]}|j |jd¡q$WqWdS)N)rFr'ÚpoprGrH)r)r8rJrKr%r%r+Ú_reset_polymorphic_adapters z Query._reset_polymorphic_adaptercCsxd|jkr0|jd}|j |d¡}|r0| |¡St|tjƒrB|}nt|dƒrT|j}ndS|j |d¡}|rt| |¡SdS)NÚ parententityÚtable) Ú _annotationsr'ÚgetZ adapt_clauserSrÚ FromClauserLre)r)ZelementÚsearchrUr%r%r+Ú_adapt_polymorphic_element$s     z Query._adapt_polymorphic_elementcs‡fdd„|DƒS)Ncs g|]}ˆ t |¡dd¡‘qS)T)Ú _adapt_clauserZ_literal_as_label_reference)Ú.0Úo)r)r%r+ú 8sz)Query._adapt_col_list..r%)r)Zcolsr%)r)r+Ú_adapt_col_list6s zQuery._adapt_col_listcCs ||_dS)N)Úlazy_loaded_from)r)Ústater%r%r+Ú_set_lazyload_from>szQuery._set_lazyload_fromcCs d|_dS)NF)Ú_orm_only_adapt)r)r%r%r+Ú_adapt_all_clausesBszQuery._adapt_all_clausescs’g‰|jsd}|r8|jr8x|jD]}ˆ ||jf¡q W|jrZˆ |jrL|nd|jjf¡|jrpˆ ||jf¡ˆsx|S‡fdd„}t  |i|¡S)z\Adapt incoming clauses to transformations which have been applied within this query.FcsFd|jkpd|jk}x,ˆD]$\}}|r*|r||ƒ}|dk r|SqWdS)NZ _orm_adaptrd)rf)ÚelemZ is_orm_adaptZ _orm_onlyrIÚe)Úadaptersr%r+Úreplacefs  z$Query._adapt_clause..replace) rsÚ_filter_aliasesrQrxr[Ú_orm_only_from_obj_aliasr'rjrZreplacement_traverse)r)ÚclauseZ as_filterZorm_onlyr]rxr%)rwr+rkFs      zQuery._adapt_clausecCs |jdS)zReturn the first QueryEntity.r)r.)r)r%r%r+Ú_query_entity_zerosszQuery._query_entity_zerocCs |jdjS)z8return the Mapper associated with the first QueryEntity.r)r.r8)r)r%r%r+Ú _mapper_zerowszQuery._mapper_zerocCs|jdk r|jS| ¡jS)z›Return the 'entity' (mapper or AliasedClass) associated with the first QueryEntity, or alternatively the 'select from' entity if specified.N)rNr|Ú entity_zero)r)r%r%r+Ú _entity_zero{szQuery._entity_zeroccs$x|jD]}t|tƒr|VqWdS)N)r.rSÚ _MapperEntity)r)r4r%r%r+Ú_mapper_entities†s  zQuery._mapper_entitiescCs|j d| ¡¡S)NÚ_joinpoint_entity)Ú _joinpointrgr)r)r%r%r+Ú_joinpoint_zeroŒszQuery._joinpoint_zerocCs(| ¡}|dk r$t|ƒ}|js$|jSdS)N)rrÚis_clause_elementr8)r)ÚezeroÚinspr%r%r+Ú _bind_mappers zQuery._bind_mappercCs$|j|jgkrt d|¡‚|jjS)Nz4%s() can only be used against a single mapped class.)r.r/rOÚInvalidRequestErrorr~)r)Zmethnamer%r%r+Ú_only_full_mapper_zero˜s zQuery._only_full_mapper_zerocCs$t|jƒdkrt |pd¡‚| ¡S)Nrz8This operation requires a Query against a single mapper.)rXr.rOr‰r)r)Z rationaler%r%r+Ú_only_entity_zero s zQuery._only_entity_zerocCs&i}x|jD]}| |jj¡q W|S)N)rÚupdater8r?)r)r`r4r%r%r+Z __all_equivs©s zQuery.__all_equivscCs|jddddS)NrgF)Úorder_byÚdistinct)Ú_no_criterion_condition)r)r%r%r+Ú_get_condition¯szQuery._get_conditioncCs|jdddddS)NrgF)rrŽ)Ú_no_criterion_assertion)r)r%r%r+Ú_get_existing_condition´szQuery._get_existing_conditioncCsd|js dS|jdk sR|jdk sR|jsR|jdk sR|jdk sR|jsR|rH|jsR|r`|jr`t   d|¡‚dS)Nz`_. 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:`.HasCTE.cte` F)r¸Ú recursive)r¹r´Úcte)r)r¸r½r%r%r+r¾:s7 z Query.ctecCs| d¡j |¡S)zèReturn the full SELECT statement represented by this :class:`.Query`, converted to a scalar subquery with a label of the given name. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.label`. F)r¹r´Úlabel)r)r¸r%r%r+r¿us z Query.labelcCs| d¡j ¡S)zÅReturn the full SELECT statement represented by this :class:`.Query`, converted to a scalar subquery. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.as_scalar`. F)r¹r´Ú as_scalar)r)r%r%r+rÀ€szQuery.as_scalarcCs| ¡S)zÛReturn the :class:`.Select` object emitted by this :class:`.Query`. Used for :func:`.inspect` compatibility, this is equivalent to:: query.enable_eagerloads(False).with_labels().statement )Ú__clause_element__)r)r%r%r+r>Šs zQuery.selectablecCs| d¡ ¡jS)NF)r¹rºr´)r)r%r%r+rÁ•szQuery.__clause_element__cCs ||_dS)z­When set to True, the query results will always be a tuple, specifically for single element queries. The default is False. . .. versionadded:: 1.2.5 N)Ú_only_return_tuples)r)Úvaluer%r%r+Úonly_return_tuples˜szQuery.only_return_tuplescCs ||_dS)aControl whether or not eager joins and subqueries are rendered. When set to False, the returned Query will not render eager joins regardless of :func:`~sqlalchemy.orm.joinedload`, :func:`~sqlalchemy.orm.subqueryload` options or mapper-level ``lazy='joined'``/``lazy='subquery'`` configurations. This is used primarily when nesting the Query's statement into a subquery or other selectable, or when using :meth:`.Query.yield_per`. N)Ú_enable_eagerloads)r)rÃr%r%r+r¹¢szQuery.enable_eagerloadscCst d|¡‚dS)Nz¹The yield_per Query option is currently not compatible with %s eager loading. Please specify lazyload('*') or query.enable_eagerloads(False) in order to proceed with query.yield_per().)rOr‰)r)Úmessager%r%r+Ú _no_yield_per´szQuery._no_yield_percCs d|_dS)aºApply column labels to the return value of Query.statement. Indicates that this Query's `statement` accessor should return a SELECT statement that applies labels to all columns in the form _; 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.with_labels` method *only* applies the output of :attr:`.Query.statement`, and *not* to any of the result-row invoking systems of :class:`.Query` itself, e.g. :meth:`.Query.first`, :meth:`.Query.all`, etc. To execute a query using :meth:`.Query.with_labels`, invoke the :attr:`.Query.statement` using :meth:`.Session.execute`:: result = session.execute(query.with_labels().statement) TN)r³)r)r%r%r+rº½szQuery.with_labelscCs ||_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)r“)r)rÃr%r%r+Úenable_assertions×szQuery.enable_assertionscCs|jS)zÖA 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. )r”)r)r%r%r+Ú whereclauseís zQuery.whereclausecCs ||_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)Úpathr%r%r+Ú_with_current_pathøs zQuery._with_current_pathcCsJ|jst d¡‚|jd ¡}|g|jdd…|_|j||||ddS)açLoad columns for inheriting classes. :meth:`.Query.with_polymorphic` applies transformations to the "main" mapped class represented by this :class:`.Query`. The "main" mapped class here means the :class:`.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)r>Úpolymorphic_on)r/rOr‰r.r°Úset_with_polymorphic)r)Úcls_or_mappersr>rÍrCr%r%r+r9szQuery.with_polymorphiccCs||_|j d|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.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.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.enable_eagerloads` T)Zstream_resultsZmax_row_bufferN)Ú _yield_perÚ_execution_optionsÚunion)r)Úcountr%r%r+Ú yield_per&sAzQuery.yield_percCs| |tj¡S)aReturn 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.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.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.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` must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading options via :meth:`~.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:`.relationship`, using a simple foreign-key-to-primary-key criterion, will also use an operation equivalent to :meth:`~.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:`.Table` object's primary key columns, or if the :paramref:`.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.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_implrZload_on_pk_identity)r)Zidentr%r%r+rglsSz Query.getcCs|j||d}t |j||¡S)akLocate 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` 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©)Zidentity_key_from_primary_keyrZget_from_identityr&)r)r8Úprimary_key_identityr©ZpassiverpÚkeyr%r%r+Ú_identity_lookupÁs1 zQuery._identity_lookupc stˆdƒrˆ ¡‰| d¡}tˆtƒ}|s4t ˆ¡‰tˆƒt|jƒkrft   dd  dd„|jDƒ¡¡‚|r¼yt ‡fdd„|j Dƒƒ‰Wn4tk rºt   dd  d d„|j Dƒ¡¡‚YnX|js|js|jdkr|j|ˆ|d }|dk r| ¡t|j|jƒsdS|S||ˆƒS) NÚ__composite_values__rgzmIncorrect number of values in identifier to formulate primary key for query.get(); primary key columns are %sú,css|]}d|VqdS)z'%s'Nr%)rlÚcr%r%r+ú sz"Query._get_impl..c3s|]}ˆ|jVqdS)N)r×)rlÚprop)rÖr%r+rÜ sztIncorrect names of values in identifier to formulate primary key for query.get(); primary key attribute names are %scss|]}d|jVqdS)z'%s'N)r×)rlrÝr%r%r+rÜs)r©)rLrÙrŠrSÚdictrr1rXZ primary_keyrOr‰rÚlistZ_identity_key_propsÚKeyErrorrŸZalways_refreshÚ_for_update_argrØr’Ú issubclassr«Úclass_)r)rÖZ db_load_fnr©r8Zis_dictÚinstancer%)rÖr+rÕ÷s@        zQuery._get_implcGsDx>|D]6}|dkr$|j dg¡|_q|j t t|ƒ¡¡|_qWdS)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:`.Select.correlate` after coercion to expression constructs. The correlation arguments take effect in such cases as when :meth:`.Query.from_self` is used, or when a subquery as returned by :meth:`.Query.subquery` is embedded in another :func:`~.expression.select` construct. N)Ú _correlaterÒr<Zsurface_selectablesr!)r)ÚargsÚsr%r%r+Ú correlate/s  zQuery.correlatecCs ||_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)Zsettingr%r%r+Ú autoflushLs zQuery.autoflushcCs d|_dS)aæReturn a :class:`.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. TN)rŸ)r)r%r%r+r¥Xs zQuery.populate_existingcCs ||_dS)zäSet 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._invoke_all_eagers`. N)Ú_invoke_all_eagers)r)rÃr%r%r+Ú_with_invoke_all_eagersfs zQuery._with_invoke_all_eagerscCs„|rt|ƒ}n| ¡}|dkrpt|ƒ}xH|jD]"}t|tjƒr.|j|jkr.|}Pq.Wt  d|jj j |j j f¡‚|  t|||jƒ¡S)aAdd filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established :func:`.relationship()` configuration. The method uses the :func:`.with_parent` function to generate the clause, the result of which is passed to :meth:`.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` object's target mapper. :param instance: An instance which has some :func:`.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` itself. Nz\Could not locate a property which relates instances of class '%s' to instances of class '%s')rrrZiterate_propertiesrSr ZRelationshipPropertyr8rOr‰rãÚ__name__r«ÚfilterrrC)r)räÚpropertyZ from_entityr~r8rÝr%r%r+rqs    zQuery.with_parentcCs8|dk rt||ƒ}t|jƒ|_t||ƒ}| |g¡dS)zIadd a mapped entity to the list of result columns to be returned.N)rrßr.r€r2)r)rCrUrKr%r%r+Ú add_entity§s    zQuery.add_entitycCs ||_dS)aµReturn a :class:`.Query` that will use the given :class:`.Session`. While the :class:`.Query` object is normally instantiated using the :meth:`.Session.query` method, it is legal to build the :class:`.Query` directly without necessarily using a :class:`.Session`. Such a :class:`.Query` object, or any :class:`.Query` already associated with a different :class:`.Session`, can produce a new :class:`.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&r%r%r+Ú with_session³szQuery.with_sessioncGsB| ¡ d¡j d¡}| |¡}d|_| ¡|_|r>| |¡|S)aûreturn a Query that selects from this Query's SELECT statement. :meth:`.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.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.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.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.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.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.add_entity` above **before** we call :meth:`.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) rºr¹r´rèÚ_from_selectableÚ_enable_single_critrrNr()r)r*Ú fromclauser¯r%r%r+Ú from_selfÈs+   zQuery.from_selfcCs ||_dS)N)ró)r)Úvalr%r%r+Ú_set_enable_single_crit}szQuery._set_enable_single_critcCs`xdD]}|j |d¡qW| |gd¡d|_|j}g|_x|D]}| ||jd¡qBWdS)N) r•r”r™r˜r–r—Ú _joinpathrƒršÚ_havingÚ _prefixesÚ _suffixesTFr)r­rbrarzr.Úadapt_to_selectablerW)r)rôÚattrZ old_entitiesrvr%r%r+ròs  zQuery._from_selectablecGs6|s tdƒS| ¡}|j|td|js.d|_t|ƒS)z\Return an iterator yielding result tuples corresponding to the given list of columnsr%)r3é )Úiterr°r(Ú _ColumnEntityrÐ)r)Úcolumnsr¯r%r%r+Úvaluessz Query.valuescCs,yt| |¡ƒdStk r&dSXdS)zLReturn a scalar result corresponding to the given column expression.rN)ÚnextrÚ StopIteration)r)Úcolumnr%r%r+rësz Query.valuecGs| |¡dS)a)Return a new :class:`.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*r%r%r+Ú with_entities³szQuery.with_entitiescGsFt|jƒ|_t|jƒ}x|D]}t||ƒqW| |j|d…¡dS)zXAdd one or more column expressions to the list of result columns to be returned.N)rßr.rXrr2)r)rÚlrÛr%r%r+Ú add_columnsÍs    zQuery.add_columnsz0.7z9:meth:`.add_column` is superseded by :meth:`.add_columns`cCs | |¡S)z½Add a column expression to the list of result columns to be returned. Pending deprecation: :meth:`.add_column` will be superseded by :meth:`.add_columns`. )r)r)rr%r%r+Ú add_columnÚs zQuery.add_columncGs|jd|žŽS)a>Return a new :class:`.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)F)Ú_options)r)rær%r%r+Úoptionsész Query.optionscGs|jd|žŽS)NT)T)r )r)rær%r%r+Ú_conditional_optionsùszQuery._conditional_optionscGsv|j ¡|_d|jkr"tƒ|jd<tt |¡ƒ}|j||_|rZx0|D]}| |¡qFWnx|D]}| |¡q`WdS)NZ_unbound_load_dedupes) Ú _attributesr6r¢rVrZflatten_iteratorÚ _with_optionsZprocess_query_conditionallyÚ process_query)r)Z conditionalræZoptsÚoptr%r%r+r üs      zQuery._optionscCs||ƒS)aÎReturn a new :class:`.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` objects. See the example at :ref:`hybrid_transformers`. r%)r)Úfnr%r%r+Úwith_transformation szQuery.with_transformationÚ*cCs,|dk rt|ƒj}|j|||ff7_dS)a~Add an indexing or other executional context hint for the given entity or selectable to this :class:`.Query`. Functionality is passed straight through to :meth:`~sqlalchemy.sql.expression.Select.with_hint`, with the addition that ``selectable`` can be a :class:`.Table`, :class:`.Alias`, or ORM entity / mapped class /etc. .. seealso:: :meth:`.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)rr>Ú _with_hints)r)r>ÚtextÚ dialect_namer%r%r+Ú with_hints zQuery.with_hintcCs| d||¡S)a“add a statement hint to this :class:`.Select`. This method is similar to :meth:`.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:`.Select.with_statement_hint`. .. versionadded:: 1.0.0 .. seealso:: :meth:`.Query.with_hint` N)r)r)rrr%r%r+Úwith_statement_hint9szQuery.with_statement_hintcCs|jS)z­ Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`.Query.execution_options` )rÑ)r)r%r%r+Úget_execution_optionsKs zQuery.get_execution_optionscKs|j |¡|_dS)a› Set non-SQL options which take effect during execution. The options are the same as those accepted by :meth:`.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.get_execution_options` N)rÑrÒ)r)Úkwargsr%r%r+Úexecution_optionsVszQuery.execution_optionsz0.9zThe :meth:`.Query.with_lockmode` method is deprecated and will be removed in a future release. Please refer to :meth:`.Query.with_for_update`. cCst |¡|_dS)aReturn a new :class:`.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.with_for_update` - improved API for specifying the ``FOR UPDATE`` clause. N)Ú LockmodeArgÚparse_legacy_queryrá)r)Úmoder%r%r+Ú with_lockmodehszQuery.with_lockmodecCst|||||d|_dS)aóreturn a new :class:`.Query` with the specified options for the ``FOR UPDATE`` clause. The behavior of this method is identical to that of :meth:`.SelectBase.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).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.with_for_update` supersedes the :meth:`.Query.with_lockmode` method. .. seealso:: :meth:`.GenerativeSelect.with_for_update` - Core level method with full argument and behavioral description. )ÚreadÚnowaitÚofÚ skip_lockedÚ key_shareN)rrá)r)r r!r"r#r$r%r%r+Úwith_for_update‰s $zQuery.with_for_updatecOsNt|ƒdkr| |d¡nt|ƒdkr2t d¡‚|j ¡|_|j |¡dS)aƒadd 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)rXrŒrOrPrµr6)r)rærr%r%r+r¶µs   z Query.paramscGsLxFt|ƒD]:}t |¡}| |dd¡}|jdk r>|j|@|_q ||_q WdS)aapply the given filtering criterion to a copy of this :class:`.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:`.text` construct. .. seealso:: :meth:`.Query.filter_by` - filter on keyword expressions. TN)rßrÚ_expression_literal_as_textrkr”)r)Ú criterionr%r%r+rîÊs   z Query.filterc s ‡fdd„| ¡Dƒ}ˆj|ŽS)aÈapply the given filtering criterion to a copy of this :class:`.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.join`. .. seealso:: :meth:`.Query.filter` - filter on SQL expressions. cs"g|]\}}tˆ ¡|ƒ|k‘qSr%)r r„)rlr×rÃ)r)r%r+rnsz#Query.filter_by..)Úitemsrî)r)rÚclausesr%)r)r+Ú filter_byís  zQuery.filter_bycGsxt|ƒdkrB|ddkr,d|jkr(d|_dS|ddkrBd|_dS| |¡}|jdks`|jdkrh||_n |j||_dS)aZapply one or more ORDER BY criterion to the query and return the newly resulting ``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. rrFr™N)rXr­r™ro)r)r'r%r%r+r s     zQuery.order_bycGsdt|ƒdkr"|ddkr"d|_dSttdd„|DƒŽƒ}| |¡}|jdkrT||_n |j||_dS)aƒapply one or more GROUP BY criterion to the query and return the newly resulting :class:`.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. rrNFcSsg|] }t|ƒ‘qSr%)r)rlrÛr%r%r+rn;sz"Query.group_by..)rXr˜rßrro)r)r'r%r%r+Úgroup_by(s    zQuery.group_bycCsXt |¡}|dk r(t|tjƒs(t d¡‚| |dd¡}|jdk rN|j|@|_n||_dS)a apply a HAVING criterion to the query and return the newly resulting :class:`.Query`. :meth:`~.Query.having` is used in conjunction with :meth:`~.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) rr&rSrÚ ClauseElementrOrPrkrù)r)r'r%r%r+ÚhavingCs    z Query.havingcGs| ||gt|ƒŽ¡ d¡S)NF)ròrßr÷)r)Zexpr_fnr¯r%r%r+Ú_set_opfsz Query._set_opcGs|jtjf|žŽS)aŽProduce 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` object will not render ORDER BY within its SELECT statement. )r.rrÒ)r)r¯r%r%r+rÒks%z Query.unioncGs|jtjf|žŽS)z¾Produce 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. )r.rÚ union_all)r)r¯r%r%r+r/’szQuery.union_allcGs|jtjf|žŽS)z¿Produce 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. )r.rÚ intersect)r)r¯r%r%r+r0›szQuery.intersectcGs|jtjf|žŽS)zÃProduce 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. )r.rÚ intersect_all)r)r¯r%r%r+r1¤szQuery.intersect_allcGs|jtjf|žŽS)z¼Produce 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. )r.rÚexcept_)r)r¯r%r%r+r2­sz Query.except_cGs|jtjf|žŽS)zÀProduce 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. )r.rÚ except_all)r)r¯r%r%r+r3¶szQuery.except_allcOsb| dd¡| dd¡| dd¡| dd¡f\}}}}|rNtdd t|ƒ¡ƒ‚|j|||||dS) aŸ*Create a SQL JOIN against this :class:`.Query` object's criterion and apply generatively, returning the newly resulting :class:`.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.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.join` along ``User.addresses`` will result in SQL equivalent to:: SELECT user.* FROM user JOIN address ON user.id = address.user_id In the above example we refer to ``User.addresses`` as passed to :meth:`~.Query.join` as the *on clause*, that is, it indicates how the "ON" portion of the JOIN should be constructed. For a single-entity query such as the one above (i.e. we start by selecting only from ``User`` and nothing else), the relationship can also be specified by its string name:: q = session.query(User).join("addresses") :meth:`~.Query.join` can also accommodate multiple "on clause" arguments to produce a chain of joins, such as below where a join across four related entities is constructed:: q = session.query(User).join("orders", "items", "keywords") The above would be shorthand for three separate calls to :meth:`~.Query.join`, each using an explicit attribute to indicate the source entity:: q = session.query(User).\ join(User.orders).\ join(Order.items).\ join(Item.keywords) **Joins to a Target Entity or Selectable** A second form of :meth:`~.Query.join` allows any mapped entity or core selectable construct as a target. In this usage, :meth:`~.Query.join` will attempt to create a JOIN along the natural foreign key relationship between two entities:: q = session.query(User).join(Address) The above calling form of :meth:`~.Query.join` will raise an error if either there are no foreign keys between the two entities, or if there are multiple foreign key linkages between them. In the above calling form, :meth:`~.Query.join` is called upon to create the "on clause" automatically for us. The target can be any mapped entity or selectable, such as a :class:`.Table`:: q = session.query(User).join(addresses_table) **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. Suppose for example we wanted to join to ``Address`` twice, using an alias the second time. We use :func:`~sqlalchemy.orm.aliased` to create a distinct alias of ``Address``, and join to it using the ``target, onclause`` form, so that the alias can be specified explicitly as the target along with the relationship to instruct how the ON clause should proceed:: a_alias = aliased(Address) q = session.query(User).\ join(User.addresses).\ join(a_alias, User.addresses).\ filter(Address.email_address=='ed@foo.com').\ filter(a_alias.email_address=='ed@bar.com') Where above, the generated SQL would be similar to:: SELECT user.* FROM user JOIN address ON user.id = address.user_id JOIN address AS address_1 ON user.id=address_1.user_id WHERE address.email_address = :email_address_1 AND address_1.email_address = :email_address_2 The two-argument calling form of :meth:`~.Query.join` also allows us to construct arbitrary joins with SQL-oriented "on clause" expressions, not relying upon configured relationships at all. Any SQL expression can be passed as the ON clause when using the two-argument form, which should refer to the target entity in some way as well as an applicable source entity:: q = session.query(User).join(Address, User.id==Address.user_id) **Advanced Join Targeting and Adaption** There is a lot of flexibility in what the "target" can be when using :meth:`~.Query.join`. As noted previously, it also accepts :class:`.Table` constructs and other selectables such as :func:`.alias` and :func:`.select` constructs, with either the one or two-argument forms:: addresses_q = select([Address.user_id]).\ where(Address.email_address.endswith("@bar.com")).\ alias() q = session.query(User).\ join(addresses_q, addresses_q.c.user_id==User.id) :meth:`~.Query.join` also features the ability to *adapt* a :meth:`~sqlalchemy.orm.relationship` -driven ON clause to the target selectable. Below we construct a JOIN from ``User`` to a subquery against ``Address``, allowing the relationship denoted by ``User.addresses`` to *adapt* itself to the altered target:: address_subq = session.query(Address).\ filter(Address.email_address == 'ed@foo.com').\ subquery() q = session.query(User).join(address_subq, User.addresses) Producing SQL similar to:: SELECT user.* FROM user JOIN ( SELECT address.id AS id, address.user_id AS user_id, address.email_address AS email_address FROM address WHERE address.email_address = :email_address_1 ) AS anon_1 ON user.id = anon_1.user_id The above form allows one to fall back onto an explicit ON clause at any time:: q = session.query(User).\ join(address_subq, User.id==address_subq.c.user_id) **Controlling what to Join From** While :meth:`~.Query.join` exclusively deals with the "right" side of the JOIN, we can also control the "left" side, in those cases where it's needed, using :meth:`~.Query.select_from`. Below we construct a query against ``Address`` but can still make usage of ``User.addresses`` as our ON clause by instructing the :class:`.Query` to select first from the ``User`` entity:: 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 **Constructing Aliases Anonymously** :meth:`~.Query.join` can construct anonymous aliases using the ``aliased=True`` flag. This feature is useful when a query is being joined algorithmically, such as when querying self-referentially to an arbitrary depth:: q = session.query(Node).\ join("children", "children", aliased=True) When ``aliased=True`` is used, the actual "alias" construct is not explicitly available. To work with it, methods such as :meth:`.Query.filter` will adapt the incoming entity to the last join point:: q = session.query(Node).\ join("children", "children", aliased=True).\ filter(Node.name == 'grandchild 1') When using automatic aliasing, the ``from_joinpoint=True`` argument can allow a multi-node join to be broken into multiple calls to :meth:`~.Query.join`, so that each path along the way can be further filtered:: q = session.query(Node).\ join("children", aliased=True).\ filter(Node.name='child 1').\ join("children", aliased=True, from_joinpoint=True).\ filter(Node.name == 'grandchild 1') The filtering aliases above can then be reset back to the original ``Node`` entity using :meth:`~.Query.reset_joinpoint`:: q = session.query(Node).\ join("children", "children", aliased=True).\ filter(Node.name == 'grandchild 1').\ reset_joinpoint().\ filter(Node.name == 'parent 1) For an example of ``aliased=True``, see the distribution example :ref:`examples_xmlpersistence` which illustrates an XPath-like query system using algorithmic joins. :param \*props: A collection of one or more join conditions, each consisting of a relationship-bound attribute or string relationship name representing an "on clause", or a single target entity, or a tuple in the form of ``(target, onclause)``. A special two-argument calling form of the form ``target, onclause`` is also accepted. :param aliased=False: If True, indicate that the JOIN target should be anonymously aliased. Subsequent calls to :meth:`~.Query.filter` and similar will adapt the incoming criterion to the target alias, until :meth:`~.Query.reset_joinpoint` is called. :param isouter=False: If True, the join used will be a left outer join, just as if the :meth:`.Query.outerjoin` method were called. This flag is here to maintain consistency with the same flag as accepted by :meth:`.FromClause.join` and other Core constructs. .. versionadded:: 1.0.0 :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. .. seealso:: :ref:`ormtutorial_joins` in the ORM tutorial. :ref:`inheritance_toplevel` for details on how :meth:`~.Query.join` is used for inheritance relationships. :func:`.orm.join` - a standalone ORM-level join function, used internally by :meth:`.Query.join`, which in previous SQLAlchemy versions was the primary ORM-level joining interface. rFÚfrom_joinpointÚisouterÚfullzunknown arguments: %sz, )Ú outerjoinr6Úcreate_aliasesr4)rbÚ TypeErrorrÚsortedÚ_join)r)Úpropsrrr4r5r6r%r%r+r¿sw   z Query.joincOsV| dd¡| dd¡| dd¡}}}|rBtdd t|ƒ¡ƒ‚|j|d|||dS) zÊCreate a left outer join against this ``Query`` object's criterion and apply generatively, returning the newly resulting ``Query``. Usage is the same as the ``join()`` method. rFr4r6zunknown arguments: %sz, T)r7r6r8r4)rbr9rr:r;)r)r<rrr4r6r%r%r+r7Æs  zQuery.outerjoincCsJ||_x8d|kr>|d\}}| ¡}|||<||f|d<|}qW||_dS)NÚprev)rƒr6rø)r)ÚjpÚfr=r%r%r+Ú_update_joinpointÞs   zQuery._update_joinpointc Csf|s | ¡t|ƒdkrLt|dtjttfƒrLt|dttjt j fƒrL|f}t   |¡}xt |ƒD]ú\}}t|tƒr€|\}} nd} t|t j t jfƒr¢| |} } n || } } | dkrÖt| ƒ} | jsÖt| dƒsÖt d¡‚t| t j ƒrðt| ddƒ} nd} t| t jƒrt| ¡| ƒ} nD|rVt| t j ƒrV| ¡}t|ƒ}t|ddƒ| jkrVt|| jƒ} t| t j ƒr@| dkr‚| rz| } n| jj} | j}|j |d¡}t|tƒrÂ|j  |¡rÂ|j!}t|| jƒ} | j}t| t"j#ƒsÚ|} |sH|| |jf}||j$krH|j$| %¡}||j$f|d<| &|¡|t|ƒdkrbt  'd |¡qbnd}}| (|| | ||||¡qbWdS) z”consumes arguments from join() or outerjoin(), places them into a consistent format with which to form the actual JOIN constructs. rrrNr8z9Expected mapped entity or selectable/table as join targetZ_of_typer=z:Pathed join target %s has already been joined to; skipping))Ú_reset_joinpointrXrSrrhÚtyperÚstrr,rÚPropComparatorrr1Ú enumeraterVÚ string_typesrrRrLrOrPÚgetattrr r„Ú _parententityr×rïrCr'rgrr8ZisaZ aliased_classrÚQueryableAttributerƒr6r@ÚwarnÚ_join_left_to_right)r)Úkeysr7r6r8r4ZkeylistÚidxZarg1Zarg2ÚrightÚonclauseÚr_infoZof_typeZjp0r_ÚleftrUrÝZedger>r%r%r+r;êsz               z Query._joinc Cs |j ¡|_|dkr6|dks t‚| |||¡\}}} n|dk sBt‚| |¡\}} ||krn|snt d||f¡‚| |||||¡\} }}|dk rÐ|j|} |jd|…t | ||||df|j|dd…|_n6| dk ræ|j | j } n|} |jt | ||||df|_dS)zÆgiven 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) Nz>Can't construct a join from %s to %s, they are the same entity)r5r6r) r'r6ÚAssertionErrorÚ"_join_determine_implicit_left_sideÚ_join_place_explicit_left_siderOr‰Ú _join_check_and_adapt_right_siderWÚorm_joinr.r>) r)rQrNrOrÝr8r7r6Úreplace_from_obj_indexÚuse_entity_indexrPZ left_clauser%r%r+rKy s*      8zQuery._join_left_to_rightcCs`t|ƒ}d}}|jrrt |j|j|¡}t|ƒdkrH|d}|j|}n(t|ƒdkr`t d¡‚nt d|f¡‚nä|jrLi}x`t |jƒD]R\} } | j } | dkr¢qŠt| ƒ} | |kr´qŠt | t ƒrÎ| | f|| j<qŠd| f|| j<qŠWt | ¡ƒ} t | |j|¡}t|ƒdkr || |d\}}n*t|ƒdkr:t d¡‚nt d|f¡‚n t d¡‚|||fS)z­When 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. Nrrz§Can't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Try adding an explicit ON clause to help resolve the ambiguity.zjDon't know how to join to %s; please use an ON clause to more clearly establish the left side of this joinzgNo entities to join from; please use select_from() to establish the left entity/selectable of this join)rrWr<Zfind_left_clause_to_join_fromr>rXrOr‰r.rEÚentity_zero_or_selectablerSr€rßrL)r)rQrNrOrPrWrXÚindexesZ potentialZ entity_indexr4rCZent_infoZ all_clausesr%r%r+rSÆ sP        z(Query._join_determine_implicit_left_sidecCsšd}}t|ƒ}|jrHt |j|j¡}t|ƒdkrrXrOr‰r.rLrErSr€Úcorresponds_to)r)rQrWrXÚl_inforZrMr4r%r%r+rT& s$    z$Query._join_place_explicit_left_sidecCsxt|ƒ}t|ƒ}d}|svt|ddƒ} | rv| jsr<Zselectables_overlaprOr‰Ú common_parentr8rLÚ_join_entitiesr…Z _is_lateralrkZis_derived_fromÚ descriptionrTrUrZ_with_polymorphic_selectablerYrRrr?ryr;r,r@r×rƒ)r)rQrNrOrÝr8r\rPZoverlapZ right_mapperr^Zright_selectableZright_is_aliasedZ need_adapterZaliased_entityrIr%r%r+rUh s–                  z&Query._join_check_and_adapt_right_sidecCs|j|_d|_dS)Nr%)rørƒry)r)r%r%r+rA szQuery._reset_joinpointcCs | ¡dS)aSReturn a new :class:`.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.join` method. See the example in :meth:`~.Query.join` for how this is used. N)rA)r)r%r%r+Úreset_joinpoint s zQuery.reset_joinpointcGs| |d¡dS)aPSet the FROM clause of this :class:`.Query` explicitly. :meth:`.Query.select_from` is often used in conjunction with :meth:`.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.join`, when no joinpoint is otherwise established - usually, the default "join point" is the leftmost entity in the :class:`~.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:`.Mapper` objects as well as core :class:`.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.join` :meth:`.Query.select_entity_from` FN)ra)r)r^r%r%r+Ú select_from s.zQuery.select_fromcCs| |gd¡dS)aôSet the FROM clause of this :class:`.Query` to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities. The :meth:`.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.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.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.select_entity_from` method is similar to the :meth:`.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.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.select_entity_from` method, we can make use of the :func:`.text` construct. However, the :func:`.text` construct needs to be aligned with the columns of our entity, which is achieved by making use of the :meth:`.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.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.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:`.Table`, this view has no relationship to the :class:`.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.select_entity_from` method now accepts an :func:`.aliased` object as an alternative to a :class:`.FromClause` object. :param from_obj: a :class:`.FromClause` object that will replace the FROM clause of this :class:`.Query`. It also may be an instance of :func:`.aliased`. .. seealso:: :meth:`.Query.select_from` TN)ra)r)r^r%r%r+Úselect_entity_fromL sfzQuery.select_entity_fromcCsÐt|tƒr t |¡\}}}t|tƒr>t|tƒr>||dkr>gSt|tƒrP|dksbt|tƒrn|dkrnt|ƒ|S| ||¡}|dk r–t|ƒdd|j…St|ƒSn,|dkr´t|ƒdSt|||d…ƒdSdS)Nréÿÿÿÿr)rSÚslicerZ decode_sliceÚintrßÚstep)r)ÚitemÚstartÚstoprfZresr%r%r+Ú __getitem__´ s         zQuery.__getitem__cCsx|dk r,|dk r,|jpd||_|||_n8|dkrD|dk rD||_n |dk rd|dkrd|jp\d||_|jdkrtd|_dS)aöComputes the "slice" of the :class:`.Query` represented by the given indices and returns the resulting :class:`.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.limit` :meth:`.Query.offset` Nr)r—r–)r)rhrir%r%r+rdÑ s  z Query.slicecCs ||_dS)zZApply a ``LIMIT`` to the query and return the newly resulting ``Query``. N)r–)r)Úlimitr%r%r+rkû sz Query.limitcCs ||_dS)z\Apply an ``OFFSET`` to the query and return the newly resulting ``Query``. N)r—)r)Úoffsetr%r%r+rl sz Query.offsetcGs<|s d|_n,| |¡}t|jtƒr2|j|7_n||_dS)a{Apply a ``DISTINCT`` to the query and return the newly resulting ``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`, however, so would not affect results. The columns are passed through when using the :attr:`.Query.statement` accessor, however. :param \*expr: optional column expressions. When present, the PostgreSQL dialect will render a ``DISTINCT ON ()`` construct. TN)ršrorSrß)r)Úexprr%r%r+rŽ s   zQuery.distinctcGs |jr|j|7_n||_dS)a°Apply the prefixes to the query and return the newly resulting ``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:`.HasPrefixes.prefix_with` N)rú)r)Úprefixesr%r%r+Ú prefix_with+ szQuery.prefix_withcGs |jr|j|7_n||_dS)aGApply the suffix to the query and return the newly resulting ``Query``. :param \*suffixes: optional suffixes, typically strings, not using any commas. .. versionadded:: 1.0.0 .. seealso:: :meth:`.Query.prefix_with` :meth:`.HasSuffixes.suffix_with` N)rû)r)Úsuffixesr%r%r+Ú suffix_withJ szQuery.suffix_withcCst|ƒS)z„Return the results represented by this ``Query`` as a list. This results in an execution of the underlying query. )rß)r)r%r%r+Úall` sz Query.allcCs0t |¡}t|tjtjfƒs&t d¡‚||_dS)a%Execute 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`. .. seealso:: :ref:`orm_tutorial_literal_sql` - usage examples in the ORM tutorial zBfrom_statement accepts text(), select(), and union() objects only.N)rr&rSZ TextClauserTrOrPr•)r)r´r%r%r+Úfrom_statementh s  zQuery.from_statementcCsH|jdk rt|ƒdd…}nt|dd…ƒ}t|ƒdkr@|dSdSdS)aReturn 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.first` results in an execution of the underlying query. .. seealso:: :meth:`.Query.one` :meth:`.Query.one_or_none` Nrr)r•rßrX)r)Úretr%r%r+Úfirst† s   z Query.firstcCs:t|ƒ}t|ƒ}|dkr |dS|dkr,dSt d¡‚dS)axReturn 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.one_or_none` results in an execution of the underlying query. .. versionadded:: 1.0.9 Added :meth:`.Query.one_or_none` .. seealso:: :meth:`.Query.first` :meth:`.Query.one` rrNz*Multiple rows were found for one_or_none())rßrXÚorm_excÚMultipleResultsFound)r)rtrr%r%r+Ú one_or_none¢ szQuery.one_or_nonecCsHy | ¡}Wn tjk r,t d¡‚YnX|dkr@t d¡‚|SdS)a6Return 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.first` :meth:`.Query.one_or_none` z"Multiple rows were found for one()NzNo row was found for one())rxrvrwÚ NoResultFound)r)rtr%r%r+ÚoneÅ s   z Query.onecCs:y| ¡}t|tƒs|S|dStjk r4dSXdS)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)rzrSrVrvry)r)rtr%r%r+Úscalarâ s z Query.scalarcCs0| ¡}d|j_|jr&|js&|j ¡| |¡S)NT)r²r´Ú use_labelsrérŸr&Ú_execute_and_instances)r)Úcontextr%r%r+Ú__iter__ý s   zQuery.__iter__cCsR| ¡}y|jr | ||jj¡nd}Wntjk r@d}YnXt|j |¡ƒS)N) r²r&Ú_get_bind_argsZget_bindrOZUnboundExecutionErrorrCr´Úcompile)r)r~Zbindr%r%r+Ú__str__ s z Query.__str__cKs&|jjf|Ž}|jr"|jf|jŽ}|S)N)r&Z connectionrÑr)r)ÚkwÚconnr%r%r+Ú_connection_from_session szQuery._connection_from_sessioncCs2|j||jdd}| |j|j¡}t |j||¡S)NT)Úclose_with_result)r€r…Úexecuter´rµrÚ instancesÚquery)r)Ú querycontextr„Úresultr%r%r+r} szQuery._execute_and_instancescCs|j||dd}| ||j¡S)NT)r8r{r†)r…r‡rµ)r)r·r8r„r%r%r+Ú _execute_crud s zQuery._execute_crudcKs|f| ¡|jdœ|—ŽS)N)r8r{)rˆr´)r)rŠrrƒr%r%r+r€% szQuery._get_bind_argscCsdd„dd„|jDƒDƒS)aþReturn metadata about the columns which would be returned by this :class:`.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 SsJg|]B\}}|j|jt|ddƒ|j|jdk r>|js>t|ddƒnddœ‘qS)r7FNrC)r¸rBrrmrC)Ú _label_namerBrGrmr~r…)rlr4Zinsp_entr%r%r+rnS s z-Query.column_descriptions..cSs(g|] }||jdk rt|jƒndf‘qS)N)r~r)rlZ_entr%r%r+rn^ s)r.)r)r%r%r+Úcolumn_descriptions* s) zQuery.column_descriptionscCs"|}|dkrt|ƒ}t |||¡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 N)r$rrˆ)r)ZcursorZ_Query__contextr~r%r%r+rˆj s zQuery.instancescCst |||¡S)a?Merge a result into this :class:`.Query` object's Session. Given an iterator returned by a :class:`.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` - 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.merge_result` is used, see the source code for the example :ref:`examples_caching`, where :meth:`~.Query.merge_result` is used to efficiently restore state from a cache back into a target :class:`.Session`. )rÚ merge_result)r)ÚiteratorÚloadr%r%r+rz szQuery.merge_resultcCs&|j|j|j|j|j|jpd|jdœS)N)rkrlrŽrnrpr+r-)r–r—ršrúrûr˜rù)r)r%r%r+Ú _select_args” szQuery._select_argscCs.|j}| d¡dk p,| d¡dk p,| dd¡S)NrkrlrŽF)r’rg)r)rr%r%r+Ú_should_nest_selectable  szQuery._should_nest_selectablecCs$t | d¡ d¡ ¡j dg¡¡S)a‚A 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() FÚ1r)rÚexistsr¹rrºr´Zwith_only_columns)r)r%r%r+r•© s#  z Query.existscCs tj t d¡¡}| |¡ ¡S)aReturn a count of rows this Query would return. This generates the SQL for this Query as follows:: SELECT count(1) AS count_1 FROM ( SELECT ) AS anon_1 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)rÚfuncrÓÚliteral_columnrõr{)r)Úcolr%r%r+rÓÓ s"z Query.countÚevaluatecCstj ||¡}| ¡|jS)aOPerform 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.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.update` :ref:`inserts_and_updates` - Core SQL tutorial )rZ BulkDeleteÚfactoryÚexec_Úrowcount)r)Úsynchronize_sessionZ delete_opr%r%r+Údeleteø swz Query.deletecCs(|pi}tj ||||¡}| ¡|jS)auPerform 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.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:`.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.delete` :ref:`inserts_and_updates` - Core SQL tutorial )rZ BulkUpdateršr›rœ)r)rrZ update_argsZ update_opr%r%r+rŒss  z Query.updatecCs|jjr.x$|jjD]}||ƒ}|dk r|}qWt|ƒ}|jdk rD|S||_|j|_x|jD]}| ||¡qZWx&|jD]}|d}||dd…ŽqvW|j r¨t |j ƒ|_ |j r¸|  |¡|jsÚ|jrÐt d¡‚n t d¡‚|jrô|jrô| |¡|_n | |¡|_|S)NrrzyNo 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.)ÚdispatchZbefore_compiler$r´r±rár.Ú setup_contextÚcreate_eager_joinsÚ from_clauserßÚfromsróÚ_adjust_for_single_inheritanceÚprimary_columnsr£rOr‰Úmulti_row_eager_loadersr“Ú_compound_eager_statementÚ_simple_statement)r)r±rZ new_queryr~rCZrecZstrategyr%r%r+r²ús:       zQuery._compile_contextc Cs4|jrt |j|j¡}n d|_g}tj|j||jf|j|j|jdœ|j —Ž}|j |_ x|j D]}|j |Ž}q^W|j r‚|j|j Ž}| ¡}| ¡}t ||¡|_tj|g|j|jd}|j dk rÖ|j jdkrÖ|j |_ |}x"|j ¡D]}t |||j¡}qæW| |¡|jr$|j|j |j¡Ž|j|jŽ|S)N)r^r|r)r|)rr<Ú expand_column_list_from_order_byr¥rÚselectrÉr£r±r’rárrrårèrUrZr=rIÚsecondary_columnsr"Ú eager_joinsrZ splice_joinsZstop_onZ append_fromÚappend_order_byZcopy_and_processÚeager_order_by) r)r~Zorder_by_col_exprÚinnerÚhintr`r´r¢Z eager_joinr%r%r+r§.sF       zQuery._compound_eager_statementcCsÆ|js d|_|jdkr6|jr6|jt |j|j¡7_|jt|j ¡ƒ7_t j |j|j |j f|j|j |jdœ|j—Ž}|j|_x|jD]}|j|Ž}qŒW|jr°|j|jŽ}|jrÂ|j|jŽ|S)NT)r^r|r)rršr¥r<r©r£rVr¬rrrªr«rÉr±r’rárrrårèr®r­)r)r~r´r°r%r%r+r¨ws,     zQuery._simple_statementcCs´t|j ¡ƒ}|jrN|j|jkrNt|jƒ}|jr8|j}nd}| |j|fg¡}x`|D]X\}}||jkrhqT|j j }|dk rT|r†|  |¡}|  |dd¡}t  t j |j¡|¡|_qTWdS)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)r¢r5rrNrr7r@rÒr^r8Z_single_table_criterionZtraverserkrÚand_ZTrue_Z_ifnonerÉ)r)r~rir‡rIrDZ single_critr%r%r+r¤•s$     z$Query._adjust_for_single_inheritance)N)N)N)TT)TT)NNNNN)NFF)NF)NN)N)NN)N)r)r)FFNFF)N)T)r™)r™N)T)¼ríÚ __module__Ú __qualname__Ú__doc__rÂrÅr“r³r”rÐr™r˜rùršrúrûr—r–rár•Ú frozensetrårŸrër rér£r¡r¤rWr^rNr5ryr[rZ immutabledictrørƒrÑrµr rrrórsrzÚ_path_registryrÊr0rpr,r(r2r;rarcrjror rrrtrkr|r}rrïrr„rˆrŠr‹rZrr’r‘rrœrržrªr°r´r¼r¾r¿rÀr>rÁrÄr¹rÇrºrÈrÉrÌr9rÔrgrZ PASSIVE_OFFrØrÕrèrêr¥rìrrðrñrõr÷ròrZ_valuesrÃrrZpending_deprecationr r r r rrrrrZ deprecatedrr%r¶rîr*rr+r-r.rÒr/r0r1r2r3rr7r@r;rKrSrTrUrAr`rarbrjrdrkrlrŽrorqrrrsrurxrzr{rr‚r…r}rŒr€rŽrˆrr’r“r•rÓržrŒr²r§r¨r¤r%r%r%r+r#@s   /-           ;       FY 0 8  6 6     %##'       M`B$ 0h* #  @   * %{4 I c@seZdZedd„ƒZdS)rcCs\|dkr dS|dkrd}d}n2|dkr0d}}n |dkrBd}d}nt d|¡‚t||dS) N)NFr TFrŒZ update_nowaitz"Unknown with_lockmode argument: %r)r r!)rOrPr)r)rr r!r%r%r+r»s  zLockmodeArg.parse_legacy_queryN)rír²r³Ú classmethodrr%r%r%r+rºsrc@s eZdZdZdd„Zdd„ZdS)r-z:represent an entity column returned within a Query result.cOsH|tkr>|d}t|tjƒs*t|ƒr*t}nt|tƒr:t}nt}t   |¡S)Nr) r-rSrrFr r€ÚBundleÚ _BundleEntityrÚobjectr¬)r®rærrCr%r%r+r¬Ós z_QueryEntity.__new__cCs|j |j¡}|j ¡|_|S)N)r«r¬r­r6)r)r¯r%r%r+r°às z_QueryEntity._cloneN)rír²r³r´r¬r°r%r%r%r+r-Ðs r-c@sxeZdZdZdd„ZdZdZdd„Zdd„Ze d d „ƒZ e d d „ƒZ d d„Z dd„Z dd„Zdd„Zdd„Zdd„ZdS)r€z mapper/class/AliasedClass entitycCs0|js ||_|j |¡d|_|g|_||_dS)NT)r/r.rQr0r*rm)r)r‰rCr%r%r+r,és  z_MapperEntity.__init__TcCs`|j|_||_|j|_|j|_|j|_|j|_||_|jrF|jj |_ n |jj j |_ |jj |_dS)N)r8rEr>r7Zwith_polymorphic_mappersÚ_with_polymorphicrÍÚ_polymorphic_discriminatorr~r¸rrãrír¶rË)r)rDrEr%r%r+rAõs  z_MapperEntity.setup_entitycCsh|jrtdƒ‚|dkr&| |j¡dS|j ||¡\}}||_||_||_| |jt   ||jj ¡¡dS)zÃReceive an update from a call to 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) r7ÚNotImplementedErrorrcr8Z_with_polymorphic_argsr»r¼r>r;r<r=r?)r)r‰rÏr>rÍZmappersr^r%r%r+rÎs   z"_MapperEntity.set_with_polymorphiccCs|jjS)N)r8rã)r)r%r%r+rB#sz_MapperEntity.typecCs|jS)N)r~)r)r%r%r+rY'sz'_MapperEntity.entity_zero_or_selectablecCs t|j|ƒS)N)rr~)r)rCr%r%r+r[+sz_MapperEntity.corresponds_tocCs|j |¡dS)N)r.rQ)r)r‰Úselr%r%r+rü.sz!_MapperEntity.adapt_to_selectablecCsPd}|js"|jr(|j |jd¡}n|j}|rF|jr@| |j¡}qL|}n|j}|S)N)r7r'rgr8rEr[Úwrap)r)r‰r~rIrtr%r%r+Ú_get_entity_clauses1sz!_MapperEntity._get_entity_clausesc Cs–| ||¡}|jr$|r$| |j¡}n |s.|j}|sL|jjrLt |j|jj¡}|j |krd|j }|j }nd}}t j |j|||j||||jd}||jfS)N)r§r¨Úpolymorphic_discriminator)rÀrIr¿r8Z_requires_row_aliasingr<r=r>r?r/r£r¨rZ_instance_processorrËr¼r)r)r‰r~r‹rIr§r¨Z _instancer%r%r+Ú row_processorEs,     z_MapperEntity.row_processorc Cs~| ||¡}|j|jf7_|jdkrR|jjrR|jj|_|rR| t |j¡¡|_tj ||j||j ||j |j |j |jd dS)NF)r9r§rÁ)rÀr£r>rr8Z adapt_listrr1rZ_setup_entity_queryrËr¥r»r£r¼)r)r‰r~rIr%r%r+r hs"  z_MapperEntity.setup_contextcCs t|jƒS)N)rCr8)r)r%r%r+r‚ƒsz_MapperEntity.__str__N)rír²r³r´r,Úsupports_single_entityÚuse_id_for_hashrArÎrïrBrYr[rürÀrÂr r‚r%r%r%r+r€æs  #r€c@s\eZdZdZdZdZdZdZdd„ZdZ dZ dd„Z dd „Z e d d „ƒZd d „Zdd„ZdS)r¸a>A grouping of SQL expressions that are returned by a :class:`.Query` under one namespace. The :class:`.Bundle` essentially allows nesting of the tuple-based results returned by a column-oriented :class:`.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` FcOsJ||_|_||_tƒ|_|_|j dd„|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. css |]}t|d|jƒ|fVqdS)r×N)rGÚ_label)rlr˜r%r%r+rÜ»sz"Bundle.__init__..Ú single_entityN) r¸rÅÚexprsr rÛrrŒrbrÆ)r)r¸rÇrƒr%r%r+r,¥s  zBundle.__init__NcCs |j |j¡}|j |j¡|S)N)r«r¬r­rŒ)r)Úclonedr%r%r+r°Ûsz Bundle._clonecCstj|jddiŽS)NÚgroupF)rZ ClauseListrÇ)r)r%r%r+rÁàszBundle.__clause_element__cCs | ¡jS)N)rÁr))r)r%r%r+r)ãszBundle.clausescCs| ¡}||_|S)z.proc..r%)rË)Ú keyed_tupleÚprocs)rËr+rÊúsz)Bundle.create_row_processor..proc)rZlightweight_named_tuple)r)r‰rÍr±rÊr%)rÌrÍr+Úcreate_row_processorîs zBundle.create_row_processor)rír²r³r´rÆr…rMr7r,rrÛr°rÁrïr)r¿rÎr%r%r%r+r¸‡s r¸c@sreZdZdZddd„Zedd„ƒZedd„ƒZed d „ƒZd d „Z ed d„ƒZ dd„Z dd„Z dd„Z dd„ZdS)r¹FTcCsr|j |¡||_|_t|ƒ|_|j|_g|_|rdx.|jD]$}t|t ƒrVt ||ƒq.)Úzipr.rÏrÎr)r)r‰r~r‹rÍr±rÊr%)r~r‰r‹r+rÂJs z_BundleEntity.row_processorN)T)rír²r³rÄr,rïr8r*r~r[rYrürAr rÂr%r%r%r+r¹s      r¹c@sZeZdZdZddd„ZdZedd„ƒZdd „Zd d „Z d d „Z dd„Z dd„Z dd„Z dS)rzColumn/expression based entity.Nc s4||_||_d}d}t|tjƒr@t |¡}|j|_d}d}d}nVt|t j t j fƒr–t |ddƒ}|dk rjd}|j|_| ¡}d}t|tƒr–t||ƒdSt|tjƒsêt|dƒrØx*|jD]}||krÂPt|||dq´WdSt d|f¡‚n|st |ddƒ|_d}|j|_}|j |_|js:t |ddƒs:| |j¡}|j |¡||_t ƒ|_!t |j"ƒ|_#‰|s¢||_$|rˆ|g|_%|j&|_&n g|_%d|_&t |j%ƒ|_'nŽd d „t(j)|dd Dƒ} t *d d „| Dƒ¡|_%t ‡fd d „| Dƒƒ|_'|j%r|j%d|_$|j$j&|_&n(|jdk r$|j|_$d|_&n d|_$d|_&dS)NTFrHÚ_select_iterable)Ú namespacez.)Zinclude_scalar_selectscSs g|]}d|jkr|jd‘qS)rd)rf)rlrur%r%r+rn³scs,g|]$}d|jkrˆ |j¡r|jd‘qS)rd)rfÚ intersectionÚ _from_objects)rlru)Ú actual_fromsr%r+rn»s r)+rmrÔrSrrFrr—r¸rrrIrrDrGr×Z_query_clause_elementr¸r¹Z ColumnElementrLrÓrrOr‰rBZhashablerÄrÅr¿r.rQrr¢r£rÖr×r~r*r8Z_from_entitiesr<Zsurface_column_elementsZ unique_list) r)r‰rrÔZsearch_entitiesZ check_columnZ_entityrÛZtype_Z all_elementsr%)r×r+r,Zs†                    z_ColumnEntity.__init__FcCs,|jdk r|jS|jr$t|jƒdSdSdS)Nr)r~r×rß)r)r%r%r+rYÍs  z'_ColumnEntity.entity_zero_or_selectablecCs.t|| |j¡ƒ}|j|_|j|_|j|_dS)N)rZcorresponding_columnrrr~r*)r)r‰r¾rÛr%r%r+rüÖsz!_ColumnEntity.adapt_to_selectablecCs4d|jkr|j|_|j |jj¡r0|j |j¡dS)Nr>)r­r>r×rÕrÖr£Úadd)r)rDrEr%r%r+rAÜs z_ColumnEntity.setup_entitycCs<|jdkrdSt|ƒr ||jkSt|jƒ o6| |j¡SdS)NF)r~r r])r)rCr%r%r+r[ãs   z_ColumnEntity.corresponds_tocCsbd|f|jkr|jd|f}n| |jdd¡}|jr<| ¡}|jrN|jj|}| |¡}||jfS)NÚ fetch_columnFT) rrkrrfÚ _deannotaterIrZ_getterr)r)r‰r~r‹rÚgetterr%r%r+rÂîs  z_ColumnEntity.row_processorcCsP| |jdd¡}|jr| ¡}|jt|jƒ7_|j |¡||jd|f<dS)NFTrÙ) rkrrfrÚr£rVr¥rQr)r)r‰r~rr%r%r+r ÿs  z_ColumnEntity.setup_contextcCs t|jƒS)N)rCr)r)r%r%r+r‚ sz_ColumnEntity.__str__)N)rír²r³r´r,rÃrïrYrürAr[rÂr r‚r%r%r%r+rWs q   rc@seZdZdZdd„ZdS)r$)r¦rIr£Ú for_updater‰r&rêr¥Úinvoke_all_eagersr¦r¨r¥r«r®r¬r¡Úpropagate_optionsrr´r¢rÉrr±ráZrunidZpartialsZpost_load_pathsr©cCs |jdk r@t|jtjƒr6|jjs6|jjs6|j ¡|_q^|j|_nd|_|j|_ |j |_ |j |_ d|_d|_d|_d|_||_|j|_|j|_|j|_|j|_|j|_|j|_g|_g|_g|_ i|_!g|_"t#dd„|j$Dƒƒ|_%|j& '¡|_(|jdk r|j)|_*nd|_*dS)NFr%css|]}|jr|VqdS)N)Zpropagate_to_loaders)rlrmr%r%r+rÜRsz(QueryContext.__init__..)+r•rSrrTZ_textualr|Z apply_labelsr´rWr¢r”rÉr™rr¦rIr£rÜr‰r&rérêrŸr¥rërÝr r¦r¡r¨r¥r«r®r¬r¡r¢rrÞr r6rr¤r©)r)r‰r%r%r+r,0s@     zQueryContext.__init__N)rír²r³Ú __slots__r,r%r%r%r+r$sc@seZdZdd„Zdd„ZdS)Ú AliasOptioncCs ||_dS)a!Return a :class:`.MapperOption` that will indicate to the :class:`.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:`~.sql.expression.Alias` object representing the alias. N)rU)r)rUr%r%r+r,\s!zAliasOption.__init__cCs8t|jtjƒr"| ¡j |j¡}n|j}t |¡|_dS)N) rSrUrrFr}r:r<r=r[)r)r‰rUr%r%r+rszAliasOption.process_queryN)rír²r³r,rr%r%r%r+rà[s#ràN);r´Ú itertoolsrÚrrrvrrrr Úbaser r r r rrZ path_registryrrrrrrrVrrrrOrrrrrr<rZsql.baser Zsql.expressionr!Zsql.selectabler"Ú__all__Úrootr¶Z_self_inspectsZ class_loggerrºr#rr-r€r¸r¹rr$Z MapperOptionràr%r%r%r+Ús                                    "xW:K