403Webshell
Server IP : 192.158.238.246  /  Your IP : 3.15.27.146
Web Server : LiteSpeed
System : Linux uniform.iwebfusion.net 4.18.0-553.27.1.lve.1.el8.x86_64 #1 SMP Wed Nov 20 15:58:00 UTC 2024 x86_64
User : jenniferflocom ( 1321)
PHP Version : 8.1.32
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/__pycache__/query.cpython-37.pyc
B

��4].��@sHdZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlm
Z
ddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm 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
dZdZdZ
dZdZdZdZdZdZe�ZdZdZdZdZdZdZdZdZdZdZiZ dZ!dZ"e#�$�Z%Z&e#�$�Z'e#�$�Z(e#�$�Z)dZ*dZ+dZ,dZ-dZ.e/Z0dZ1dZ2�ddd�Z3�ddd	�Z4d
d�Z5dd
�Z6dd�Z7dd�Z8dd�Z9dd�Z:e;�dd��Z<e;�dd��Z=dd�Z>dd�Z?dd�Z@d d!�ZAeBd"d#��ZCd$d%�ZDd&d'�ZEd(d)�ZF�dd*d+�ZGd,d-�ZHd.d/�ZId0d1�ZJ�dd2d3�ZK�dd4d5�ZLd6d7�ZMd8d9�ZNd:d;�ZO�dd<d=�ZPd>d?�ZQeBd@dA��ZR�ddBdC�ZS�ddDdE�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�Ze�dddde�Zfe;�dfdg��Zge;�dhdi��Zhe;�djdk��Zie;�dldm��Zj�ddndo�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;��dd�d���Z|�dd�d��Z}d�d��Z~e;�d�d���Ze;�e#��d�d��d�d����Z�e;��dd�d���Z�e;�d�d���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��Z�d�d��Z�d�d��Z�d�d��Z�d�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҄�Z�e;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��d�d�Z��d!�d�d�Z��d"�d�d�Z��d#�d�d	�Z��d
�d�Z��d�d
�Z��d�d�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
|tj�r~|�
�}|r�|}|�|�qWt|�|_|r�t|j�dkr�t
|tj�r�|��}t�|jd|�|_n2|�rt|j�dk�rt|d��r|j�r|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)�element�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+�
<listcomp>8sz)Query._adapt_col_list.<locals>.<listcomp>r%)r)�colsr%)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.<locals>.replace)
ru�_filter_aliasesrQrzr[�_orm_only_from_obj_aliasr'rkrZreplacement_traverse)r)�clauseZ	as_filterZorm_onlyr]rzr%)ryr+rlFs 
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)r�r�is_clause_elementr8)r)�ezero�inspr%r%r+�_bind_mapper�s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|jdddd�S)NrgF)�order_by�distinct)�_no_criterion_condition)r)r%r%r+�_get_condition�szQuery._get_conditioncCs|jdddd�dS)NrgF)r�r�)�_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<Query.%s() being called on a Query with existing criterion. )�_enable_assertions�
_criterion�
_statementrW�_limit�_offset�	_group_by�	_order_by�	_distinctrOr�)r)�methr�r�r%r%r+r��s





zQuery._no_criterion_assertioncCs6|�|||�d|_d|_|_d|_|_|_dS)Nr%F)r�rWr�r�r�r�r�)r)r�r�r�r%r%r+r��szQuery._no_criterion_conditioncCs,|js
dS|jrt�d|��|�|�dS)Nz<Query.%s() being called on a Query with existing criterion. )r�r�rOr�r�)r)r�r%r%r+�_no_clauseelement_condition�sz!Query._no_clauseelement_conditioncCs&|js
dS|jdk	r"t�d|��dS)Nz[Query.%s() being called on a Query with an existing full statement - can't apply criterion.)r�r�rOr�)r)r�r%r%r+�_no_statement_condition�s
zQuery._no_statement_conditioncCs4|js
dS|jdk	s|jdk	r0t�d||f��dS)Nz�Query.%s() 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 %s() before limit() or offset() are applied.)r�r�r�rOr�)r)r�r%r%r+�_no_limit_offset�szQuery._no_limit_offsetcCs:|r
||_|r||_|r||_|r,t|�|_|r6||_|S)N)�_populate_existing�_version_check�_refresh_state�set�_only_load_props�_refresh_identity_token)r)�populate_existing�
version_check�only_load_props�
refresh_state�identity_tokenr%r%r+�_get_options�s
zQuery._get_optionscCs |j}|�|�}|j��|_|S)N)�	__class__�__new__�__dict__r6)r)�cls�qr%r%r+�_clones
zQuery._clonecCs&|j|jd�j}|jr"|�|j�}|S)z�The 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�_params�params)r)�stmtr%r%r+r�s
zQuery.statementcCs4|�d�}|r|��}|j}|r(|��}|j|d�S)aMreturn the full SELECT statement represented by
        this :class:`.Query`, embedded within an :class:`.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:`.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` first to apply table-qualified labels
         to all columns.

        :param reduce_columns: if True, :meth:`.Select.reduce_columns` will
         be called on the resulting :func:`.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_labelsr��reduce_columnsrU)r)r�r�r�r�r%r%r+�subquerys
zQuery.subquerycCs|�d�jj||d�S)a*Return the full SELECT statement represented by this
        :class:`.Query` represented as a common table expression (CTE).

        Parameters and usage are the same as those of the
        :meth:`.SelectBase.cte` method; see that method for
        further details.

        Here is the `PostgreSQL WITH
        RECURSIVE example
        <http://www.postgresql.org/docs/8.4/static/queries-with.html>`_.
        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	zQuery.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 <tablename>_<columnname>; 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||||d�dS)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)�identr%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�Zpassiverr�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|j�s|j�s|jdk�r|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%)rm�cr%r%r+�	<genexpr>sz"Query._get_impl.<locals>.<genexpr>c3s|]}�|jVqdS)N)r�)rm�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�)rmr�r%r%r+r�s)r�)rLr�r�rS�dictrr1rXZprimary_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jf��|�
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')rr�rZiterate_propertiesrSr	ZRelationshipPropertyr8rOr�r��__name__r��filterrrC)r)r��propertyZfrom_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_critr�rNr()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�rbrar|r.�adapt_to_selectablerW)r)r��attrZold_entitiesrxr%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+�values�szQuery.valuescCs,yt|�|��dStk
r&dSXdS)zLReturn a scalar result corresponding to the given
        column expression.rN)�nextr�
StopIteration)r)�columnr%r%r+r��szQuery.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)Zconditionalr��opts�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.9z�The :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)r r�)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_textrlr�)r)�	criterionr%r%r+r��s

zQuery.filtercs �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�)rmr�r�)r)r%r+rosz#Query.filter_by.<locals>.<listcomp>)�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�rq)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)rmr�r%r%r+ro;sz"Query.group_by.<locals>.<listcomp>)rXr�r�rrq)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�
ClauseElementrOrPrlr�)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.

        )r2rr�)r)r�r%r%r+r�ks%zQuery.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.

        )r2r�	union_all)r)r�r%r%r+r3�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.

        )r2r�	intersect)r)r�r%r%r+r4�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.

        )r2r�
intersect_all)r)r�r%r%r+r5�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.

        )r2r�except_)r)r�r%r%r+r6�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.

        )r2r�
except_all)r)r�r%r%r+r7�szQuery.except_allcOsb|�dd�|�dd�|�dd�|�dd�f\}}}}|rNtdd�t|����|j|||||d�S)	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, )�	outerjoinr:�create_aliasesr8)rb�	TypeErrorr�sorted�_join)r)�propsrrr8r9r:r%r%r+r�sw


z
Query.joincOsV|�dd�|�dd�|�dd�}}}|rBtdd�t|����|j|d|||d�S)	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.

        rFr8r:zunknown arguments: %sz, T)r;r:r<r8)rbr=rr>r?)r)r@rrr8r:r%r%r+r;�s

zQuery.outerjoincCsJ||_x8d|kr>|d\}}|��}|||<||f|d<|}qW||_dS)N�prev)r�r6r�)r)�jp�frAr%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
tjf�r�|	|}
}n
||	}
}|dkr�t|
�}|js�t|d�s�t�d��t|t	j
�r�t|dd�}
nd}
t|tj��rt|��|�}nD|�rVt|t	j
��rV|��}t|�}t|dd�|jk�rVt||j�}t|t	j
��r@|
dk�r�|
�rz|
}
n|jj}
|j}|j�|d�}t|t��r�|j� |��r�|j!}t||j�}|j}t|t"j#��s�|}|�sH||
|jf}||j$k�rH|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_typerAz:Pathed join target %s has already been joined to; skipping))�_reset_joinpointrXrSrrh�typer�strr0r�PropComparatorrr1�	enumeraterV�string_typesrrRrLrOrP�getattrr
r��
_parententityr�r�rCr'rgrr8ZisaZ
aliased_classr�QueryableAttributer�r6rD�warn�_join_left_to_right)r)�keysr;r:r<r8Zkeylist�idxZarg1Zarg2�right�onclause�r_infoZof_typeZjp0r_�leftrUr�ZedgerBr%r%r+r?�sz





zQuery._joincCs
|j��|_|dkr6|dks t�|�|||�\}}}	n|dk	sBt�|�|�\}}	||krn|snt�d||f��|�|||||�\}
}}|dk	r�|j|}|jd|�t	|||||d�f|j|dd�|_n6|	dk	r�|j
|	j}n|}|jt	|||||d�f|_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)r9r:r)r'r6�AssertionError�"_join_determine_implicit_left_side�_join_place_explicit_left_siderOr�� _join_check_and_adapt_right_siderW�orm_joinr.r>)r)rUrRrSr�r<r;r:�replace_from_obj_index�use_entity_indexrTZleft_clauser%r%r+rOy	s*	

8zQuery._join_left_to_rightcCs`t|�}d}}|jrrt�|j|j|�}t|�dkrH|d}|j|}n(t|�dkr`t�d��nt�d|f��n�|j�rLi}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|�dk�r ||
|d\}}n*t|�dk�r: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.rI�entity_zero_or_selectablerSr�r�rP)r)rUrRrSrTr[r\�indexesZ	potentialZentity_indexr4rCZent_infoZall_clausesr%r%r+rW�	sP
z(Query._join_determine_implicit_left_sidecCs�d}}t|�}|jrHt�|j|j�}t|�dkr<t�d��|rH|d}|dkr�|jr�t	|d�r�x0t
|j�D]"\}}t|t�rl|�
|�rl|}PqlW||fS)z�When 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.rr8)rrWr<Z#find_left_clause_that_matches_givenr>rXrOr�r.rLrIrSr��corresponds_to)r)rUr[r\�l_infor^rQr4r%r%r+rX&
s$

z$Query._join_place_explicit_left_sidecCsxt|�}t|�}d}|svt|dd�}	|	rv|	js<t|	jtj�rvx8|jpJ|jgD]&}
t	�
|j|
�rLt	�
|
|j�rLd}PqLW|s~|s�|j|jkr�t�d|j��t|dd�|jt|dd�}	}}|	r�|r�|	�
|j�s�t�d||f��t|d�r�|j|f7_d}
|j�r�|�r|j}	|j�r,|�|dd�}nb|�r~|�|	j��sXt�d|j|	jjf��t|tj��rr|��}d}
t|	|�}n|�r�t�d	��|	�o�|�o�|	j�r�t|	jtj��p�|}|
�s�|�s�|�r�t|dd
�}d}
|
�r|	�s�t�t||	jd�}|f|j|_|�s|�|	|�t|tj ��r4|�|dd�}|�s`|�r`|�!||||j"f|j#fd��n
d
|i|_#|t|�|fS)z�transform 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.

        Fr8NTz*Can't join table/selectable '%s' to itselfr7zIJoin target %s does not correspond to the right side of join condition %sz(Selectable '%s' is not derived from '%s'zpThe aliased=True parameter on query.join() only works with an ORM entity, not a plain selectable, as the target.)Zflat)Zequivalents)r�rAr�)$rrKr9rSr:rZJoinrWr>r<Zselectables_overlaprOr��
common_parentr8rL�_join_entitiesr�Z_is_lateralrlZis_derived_from�descriptionrTrUrZ_with_polymorphic_selectablerYrVrr?r{r;r0rDr�r�)r)rUrRrSr�r<r`rT�overlapZright_mapperr^Zright_selectableZright_is_aliasedZneed_adapterZaliased_entityrIr%r%r+rYh
s�








z&Query._join_check_and_adapt_right_sidecCs|j|_d|_dS)Nr%)r�r�r{)r)r%r%r+rEszQuery._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)rE)r)r%r%r+�reset_joinpointszQuery.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_froms.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_fromLsfzQuery.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�stoprk�resr%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)rmrnr%r%r+ri�s
zQuery.slicecCs
||_dS)zZApply a ``LIMIT`` to the query and return the newly resulting
        ``Query``.

        N)r�)r)�limitr%r%r+rq�szQuery.limitcCs
||_dS)z\Apply an ``OFFSET`` to the query and return the newly resulting
        ``Query``.

        N)r�)r)�offsetr%r%r+rr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 (<expressions>)``
         construct.

        TN)r�rqrSr�)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
zQuery.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)rzr
r%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())r~r|r}�
NoResultFound)r)rzr%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()
          <Item>
          >>> 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)r�rSrVr|r)r)rzr%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_bindrOZUnboundExecutionErrorrGr��compile)r)r��bindr%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�rFrrsrC)�_label_namerFrKrsr�r�)rmr4Zinsp_entr%r%r+roS
s
z-Query.column_descriptions.<locals>.<listcomp>cSs(g|] }||jdk	rt|j�ndf�qS)N)r�r)rmZ_entr%r%r+ro^
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+r�z
szQuery.merge_resultcCs&|j|j|j|j|j|jpd|jd�S)N)rqrrr�rtrvr/r1)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)Nrqrrr�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 <rest of query follows...>
            ) 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"zQuery.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 <updates_order_parameters>` 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)rr�Zupdate_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|jD]}|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|�|�|j�r$|j|j�|j��|j|j�|S)N)r^r�r�)r�)r�r<� expand_column_list_from_order_byr�r�selectr�r�r�r�r�rrr�r�rUrZr=rI�secondary_columnsr&�eager_joinsrZsplice_joinsZstop_onZappend_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�)r�r�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�rbr8Z_single_table_criterionZtraverserlr�and_ZTrue_Z_ifnoner�)r)r�rjr�rIrDZsingle_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�rWrbrNr5r{r[rZ
immutabledictr�r�r�r�rrrr�rur|�_path_registryr�r0rrr,r(r2r;rarcrkrqrrtrvrlr~rr�r�r�r�r�r�r�rZr�r�r�r�r�r�r�r�r�r�r�r�r�r�r>r�r�r�r�r�r�r�r�r9r�rgrZPASSIVE_OFFr�r�r�r�r�r�rr�r�r�r�r�rZ_valuesr�r	rZpending_deprecationrrrr
rrrrrZ
deprecatedr#r)r�r�r.r�r/r1r2r�r3r4r5r6r7rr;rDr?rOrWrXrYrErerfrgrprirqrrr�rurwrxryr{r~r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r%r%r%r+r#@s� /-		
;

	 FY0866
%##'						M`B$
0h* #@	
*%{4Ic@seZdZedd��ZdS)r cCs\|dkrdS|dkrd}d}n2|dkr0d}}n |dkrBd}d}nt�d|��t||d�S)	N)NFr$TFr�Z
update_nowaitz"Unknown with_lockmode argument: %r)r$r%)rOrPr )r)r"r$r%r%r%r+r!�s

zLockmodeArg.parse_legacy_queryN)r�r�r��classmethodr!r%r%r%r+r �sr c@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-rSrrJr
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	dd��Zd
d�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdS)r�z mapper/class/AliasedClass entitycCs0|js||_|j�|�d|_|g|_||_dS)NT)r/r.rQr0r*rs)r)r�rCr%r%r+r,�sz_MapperEntity.__init__TcCs`|j|_||_|j|_|j|_|j|_|j|_||_|jrF|jj	|_
n|jjj|_
|jj
|_dS)N)r8rEr>r7Zwith_polymorphic_mappers�_with_polymorphicr��_polymorphic_discriminatorr�r�r�r�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+rF#sz_MapperEntity.typecCs|jS)N)r�)r)r%r%r+r]'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�rIrzr%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_processorcCs~|�||�}|j|jf7_|jdkrR|jjrR|jj|_|rR|�t�|j��|_tj	||j||j
||j|j|j
|jd�	dS)NF)r9r�r�)r�r�r>r�r8Z
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)rGr8)r)r%r%r+r��sz_MapperEntity.__str__N)r�r�r�r�r,�supports_single_entity�use_id_for_hashrAr�r�rFr]r_r�r�r�r�r�r%r%r%r+r��s #r�c@s\eZdZdZdZdZdZdZdd�ZdZ	dZ
dd�Zdd	�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)rK�_label)rmr�r%r%r+r��sz"Bundle.__init__.<locals>.<genexpr>�
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<Provide a copy of this :class:`.Bundle` passing a new label.)r�r�)r)r�r�r%r%r+r��szBundle.labelcst�d|����fdd�}|S)z�Produce the "row processing" function for this :class:`.Bundle`.

        May be overridden by subclasses.

        .. seealso::

            :ref:`bundles` - includes an example of subclassing.

        r�cs��fdd��D��S)Ncsg|]}|���qSr%r%)rm�proc)�rowr%r+ro�sz=Bundle.create_row_processor.<locals>.proc.<locals>.<listcomp>r%)r�)�keyed_tuple�procs)r�r+r��sz)Bundle.create_row_processor.<locals>.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
��Zdd�Z	ed
d��Z
dd�Zdd�Zdd�Z
dd�ZdS)r�FTcCsr|j�|�||_|_t|�|_|j|_g|_|rdx.|jD]$}t|t	�rVt
||�q<t||�q<W|jj|_
dS)N)r.rQ�bundlersrFr�r�r�rSr�r�rr�r�)r)r�r��setup_entitiesrsr%r%r+r,s

z_BundleEntity.__init__cCs|j}|dk	r|jSdSdS)N)r�r8)r)r�r%r%r+r8sz_BundleEntity.mappercCs$g}x|jD]}|�|j�qW|S)N)r.�extendr*)r)r*r4r%r%r+r*sz_BundleEntity.entitiescCs*x$|jD]}|j}|dk	r|SqWdSdS)N)r.r�)r)r4r�r%r%r+r�"s
z_BundleEntity.entity_zerocCsdS)NFr%)r)rCr%r%r+r_+sz_BundleEntity.corresponds_tocCs*x$|jD]}|j}|dk	r|SqWdSdS)N)r.r])r)r4r�r%r%r+r]0s
z'_BundleEntity.entity_zero_or_selectablecCs0t||jdd�}x|jD]}|�||�qWdS)NF)r�)r�r�r.r�)r)r�r�r�r4r%r%r+r�9sz!_BundleEntity.adapt_to_selectablecCs x|jD]}|�||�qWdS)N)r.rA)r)rDrEr4r%r%r+rABsz_BundleEntity.setup_entitycCs x|jD]}|�||�qWdS)N)r.r�)r)r�r�r4r%r%r+r�Fsz_BundleEntity.setup_contextcs:t���fdd�|jD��\}}|j��||�}||jfS)Ncsg|]}|������qSr%)r�)rmr4)r�r�r�r%r+roMsz/_BundleEntity.row_processor.<locals>.<listcomp>)�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_r]r�rAr�r�r%r%r%r+r�s
			r�c@sZeZdZdZddd�ZdZedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dS)rzColumn/expression based entity.Nc
s4||_||_d}d}t|tj�r@t�|�}|j|_d}d}d}nVt|t	j
tjf�r�t
|dd�}|dk	rjd}|j|_|��}d}t|t�r�t||�dSt|tj�s�t|d�r�x*|jD]}||kr�Pt|||d�q�WdSt�d|f��n|�st
|dd�|_d}|j|_}|j|_|j�s: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)NTFrL�_select_iterable)�	namespacez<SQL expression, column, or mapped entity expected - got '%r'r�Z
is_literalcSsg|]}d|jkr|�qS)rd)rf)rmrwr%r%r+ro�sz*_ColumnEntity.__init__.<locals>.<listcomp>)Zinclude_scalar_selectscSs g|]}d|jkr|jd�qS)rd)rf)rmrwr%r%r+ro�scs,g|]$}d|jkr��|j�r|jd�qS)rd)rf�intersection�
_from_objects)rmrw)�actual_fromsr%r+ro�s
r)+rsr�rSrrJrr�r�r�rrMrrHrKr�Z_query_clause_elementr�r�Z
ColumnElementrLr�rrOr�rFZhashabler�r�r�r.rQrr�r�r�r�r�r*r8Z_from_entitiesr<Zsurface_column_elementsZunique_list)
r)r�rr�Zsearch_entitiesZcheck_columnZ_entityr��type_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+r]�s

z'_ColumnEntity.entity_zero_or_selectablecCs.t||�|j��}|j|_|j|_|j|_dS)N)rZcorresponding_columnrr�r�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ra)r)rCr%r%r+r_�s


z_ColumnEntity.corresponds_tocCsbd|f|jkr|jd|f}n|�|jdd�}|jr<|��}|jrN|jj|}|�|�}||jfS)N�fetch_columnFT)	rrlrrf�_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�)	rlrrfr�r�rVr�rQr)r)r�r�rr%r%r+r��sz_ColumnEntity.setup_contextcCs
t|j�S)N)rGr)r)r%r%r+r�sz_ColumnEntity.__str__)N)r�r�r�r�r,r�r�r]r�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�r�r�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)rmrnr%r%r+r�Rsz(QueryContext.__init__.<locals>.<genexpr>)+r�rSrrTZ_textualr�Zapply_labelsr�rWr�r�r�r�r�r�rIr�r�r�r&r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�rr6rr�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)	rSrUrrJrr: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�rrr|rrrr	�baser
rrr
rrZ
path_registryrrrrrrrZrrrrOrrrrrr<rZsql.baser Zsql.expressionr!Zsql.selectabler"�__all__�rootr�Z_self_inspectsZclass_loggerr�r#r r-r�r�r�rr$ZMapperOptionr�r%r%r%r+�<module>s�

"xW:K

Youez - 2016 - github.com/yon3zu
LinuXploit