
    -h                    >   S r SSKrSSKrSSKrSSKJr  SSKJr  SSKJr  SSKJ	r
  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSK	Jr  SSK	Jr  SSK	Jr  SSK	Jr  SSK	Jr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ	r	  SSKJ r   SSKJ!r!  SSKJ"r"  SSKJ#r#  SSKJ$r$  SSKJ	r%  SS KJ&r&  SS!K'J(r(  SS"K)J*r*  SS#K)J+r+  SS$K)J,r,  SS%K-J.r.  SS&K-J/r/  SS'K-J0r0  SS(K-J1r1  SS)K-J2r2  SS*K-J3r3  SS+K-J4r4  SS,K-J5r5  SS-K-J6r6  SS.K-J7r7  SS/K8J9r9  SS0K	J:r:  / S1Qr;\Rx                  \Rz                   " S2 S3\/\(\3\4\2\,5      5       5       r> " S4 S5\1\6\,5      r? " S6 S7\R                  5      rA " S8 S9\B5      rC " S: S;\C5      rD " S< S=\C5      rEg)>a  The Query class and support.

Defines the :class:`_query.Query` class, the central
construct used by the ORM to construct database queries.

The :class:`_query.Query` class should not be confused with the
:class:`_expression.Select` class, which defines database
SELECT operations at the SQL (non-ORM) level.  ``Query`` differs from
``Select`` in that it returns ORM-mapped objects and interacts with an
ORM session, whereas the ``Select`` construct interacts directly with the
database to return iterable result sets.

    N   )exc)
interfaces)loading)util)_assertions_column_descriptions)$_legacy_determine_last_joined_entity)_legacy_filter_by_entity_zero)LABEL_STYLE_LEGACY_ORM)ORMCompileState)ORMFromStatementCompileState)QueryContext)ORMColumnsClauseRole)aliased)AliasedClass)object_mapper)with_parent)with_polymorphic   )inspect)
inspection)log)sql)	coercions)elements)
expression)roles)Select)visitors)SupportsCloneAnnotations)_entity_namespace_key)_generative)
Executable)_MemoizedSelectEntities)_SelectFromElements)ForUpdateArg)GroupedElement)HasHints)HasPrefixes)HasSuffixes)LABEL_STYLE_TABLENAME_PLUS_COL)
SelectBase)SelectStatementGrouping)InternalTraversal)collections_abc)Queryr   r   c                      \ rS rSrSrSrSrSrSrSr	Sr
SrSrSrSrSrSrSrSr\rSr\R.                  r\R4                  SS0-   r\R:                  rSrSr Sr!Sr"\RF                  " 5       r$SS jr%S	 r&S
 r'S r(S r)S r*\+S 5       r,S r-S r.SS jr/SS jr0S r1S r2S r3\4S 5       r5     SS jr6S r7\4S 5       r8SS jr9SS jr:   SS jr;SS jr<S r=\R|                  " SS 5      S! 5       r?S" r@\4S# 5       rAS$ rB\+S% 5       rC\4S& 5       rD\+S' 5       rE\+S( 5       rF\R                  " S)S*S+9S, 5       rH\HrI\4S- 5       rJS. rK\+S/ 5       rL\4S0 5       rM\+S1 5       rN\+\O" \15      \R                  " S2S3S+9 SS4 j5       5       5       rP\+S5 5       rQ\R                  " S6S7SS89S9 5       rRSS: jrS\4S; 5       rT\4S< 5       rU\+S= 5       rV\+S> 5       rW\+S? 5       rX\+S@ 5       rY\R                  " SASBSS89\R                  " SC5      SSD j5       5       r[\+SSE j5       r\\+SF 5       r]\R                  " SGSHS+9SI 5       r^SJ r_\+SK 5       r`\+SSL j5       ra\R|                  " SSM5      SN 5       rb\brc\R|                  " SSO5      SP 5       rd\+SQ 5       re\+SR 5       rf\R|                  " SSS5      ST 5       rg\+SU 5       rhSV riSW rj\+SX 5       rk\+     SSY j5       rl\+SZ 5       rmS[ rn\+\O" \2\35      S\ 5       5       ro\R                  S] 5       r!S^ rqS_ rr\+\O" \2\35      S` 5       5       rs\+\O" \2\35      Sa 5       5       rt\+\O" \2\35      Sb 5       5       ruSc rvSd rwSe rxSf rySg rzSh r{Si r|Sj r}\+\O" \2\35      Sk 5       5       r~Sl r\+\O" \25      Sm 5       5       r\+\O" \15      Sn 5       5       r\R                  " SoSpS+9\+\O" \15      Sq 5       5       5       rSr r\+\O" \25      Ss 5       5       r\+\O" \25      St 5       5       r\+\O" \25      Su 5       5       r\+\O" \25      Sv 5       5       rSw r\+\O" \15      Sx 5       5       rSy rSz rS{ rS| rS} rS~ rS rS r\4S 5       rSS jr\R                  " SSSSS9SS j5       rS rS rSS jrSS jrSS jrSS jrSrg)r2   L   a9  ORM-level SQL construction object.

:class:`_query.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.Query` object, a copy of the former with additional
criteria and options associated with it.

:class:`_query.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.Query` directly and
associating with a :class:`.Session` using the
:meth:`_query.Query.with_session`
method.

For a full walk through of :class:`_query.Query` usage, see the
:ref:`ormtutorial_toplevel`.

 NFT_legacy_uniquingc                 2    X l         U R                  U5        g)a?  Construct a :class:`_query.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.Query`
 will be associated.   Optional; a :class:`_query.Query`
 can be associated
 with a :class:`.Session` generatively via the
 :meth:`_query.Query.with_session` method as well.

.. seealso::

    :meth:`.Session.query`

    :meth:`_query.Query.with_session`

N)session_set_entities)selfentitiesr8   s      iC:\Users\ROHAN GUPTA\OneDrive\Desktop\mathbuddy-assessment\venv\Lib\site-packages\sqlalchemy/orm/query.py__init__Query.__init__   s    8 8$    c                 <    [         R                  " U5      U l        U $ N)r   immutabledict_propagate_attrs)r:   valuess     r<   _set_propagate_attrsQuery._set_propagate_attrs   s     $ 2 26 :r?   c           
          [         R                  " U5       Vs/ s H(  n[        R                  " [        R
                  UU SS9PM*     snU l        g s  snf NTapply_propagate_attrspost_inspect)r   to_listr   expectr   ColumnsClauseRole_raw_columns)r:   r;   ents      r<   r9   Query._set_entities   sS     ||H-
 . ''&*!	 .
 
s   /Ac                    U R                   (       d  g U R                   S   nSUR                  ;   a  UR                  S   $ [        U[        5      (       a  UR                  $ SUR                  ;   a  UR                  S   $ [
        R                  " U5       H$  nSUR                  ;   d  M  UR                  S   s  $    g )Nr   parententitybundle)rO   _annotations
isinstancer   entityr!   iterate)r:   rP   elements      r<   _entity_from_pre_ent_zeroQuery._entity_from_pre_ent_zero   s      "S---##N33122::)))##H-- $++C0!W%9%99"//?? 1 r?   c                    [        U R                  5      S:w  d;  SU R                  S   R                  ;  d  U R                  S   R                  (       d  [        R
                  " SU-  5      eU R                  S   R                  S   $ )Nr   rS   r   z4%s() can only be used against a single mapped class.)lenrO   rU   is_selectablesa_excInvalidRequestError)r:   methnames     r<   _only_full_mapper_zeroQuery._only_full_mapper_zero   s    !!"a'T%6%6q%9%F%FF$$Q'55,,)+34 
   #00@@r?   c           
          U Vs/ s H(  n[         R                  " [        R                  USU S9PM*     nnU =R                  SU0-  sl        [        U5      U l        g s  snf )NT)allow_selectrJ   _set_base_alias)r   rM   r   StrictFromClauseRole_compile_optionstuple	_from_obj)r:   objset_base_aliaselemfas        r<   _set_select_fromQuery._set_select_from   sn     
  **!&*	  	 
 	"3^!DDr
s   /Ac                 2    U =R                   SU0-  sl         g )N_lazy_loaded_fromload_options)r:   states     r<   _set_lazyload_fromQuery._set_lazyload_from   s    1599r?   c                 $    U R                  SSSS9$ NgetForder_bydistinct)_no_criterion_conditionr:   s    r<   _get_conditionQuery._get_condition   s!    ++EE , 
 	
r?   c                 &    U R                  SSSS9  g ry   )_no_criterion_assertionr   s    r<   _get_existing_conditionQuery._get_existing_condition   s    $$UUU$Kr?   c                    U R                   (       d  g U R                  (       d  U R                  c}  U R                  (       dl  U R                  (       d[  U R
                  cN  U R                  cA  U R                  (       d0  U(       a  U R                  (       d  U(       a+  U R                  (       a  [        R                  " SU-  5      eg g Nz<Query.%s() being called on a Query with existing criterion. )_enable_assertions_where_criteria
_statementrj   _legacy_setup_joins_limit_clause_offset_clause_group_by_clauses_order_by_clauses	_distinctr_   r`   r:   methr|   r}   s       r<   r   Query._no_criterion_assertion   s    &&  *~~''!!-"".%%T33T^^,,2489  ,r?   c                     U R                  XU5        S=U l        U l        U R                  b  U =R                  SS 0-  sl        SU l        SU l        S=U l        U l        g )Nr5   r   F)	r   rj   r   r   rh   r   r   r   r   r   s       r<   r~   Query._no_criterion_condition  s`    $$TX>4661??&!!lD%99!!:<<!7r?   c                     U R                   (       d  g U R                  (       a  [        R                  " SU-  5      eU R	                  U5        g r   )r   r   r_   r`   r~   r:   r   s     r<   _no_clauseelement_condition!Query._no_clauseelement_condition  sG    &&!!,,2489  	$$T*r?   c                 t    U R                   (       d  g U R                  b  [        R                  " SU-  5      eg )Nz[Query.%s() being called on a Query with an existing full statement - can't apply criterion.)r   r   r_   r`   r   s     r<   _no_statement_conditionQuery._no_statement_condition(  s?    &&??&,,9 	  'r?   c                     U R                   (       d  g U R                  c  U R                  b  [        R                  " SU< SU< S35      eg )NzQuery.zL() being called on a Query which already has LIMIT or OFFSET applied.  Call z*() before limit() or offset() are applied.)r   r   r   r_   r`   r   s     r<   _no_limit_offsetQuery._no_limit_offset4  sJ    &&)T-@-@-L,, #'.  .Mr?   c                 H    U R                   S L=(       d    U R                  S L$ rA   )r   r   r   s    r<   _has_row_limiting_clauseQuery._has_row_limiting_clause>  s'     d*Md.A.A.M	
r?   c                 
   0 n0 nU(       a  X&S'   U(       a  XS'   U(       a	  XFS'   SUS'   U(       a  [        U5      US'   U(       a  XVS'   U(       a  U =R                  U-  sl        U(       a  U =R                  U-  sl        U $ )N_version_check_populate_existing_refresh_stateT_for_refresh_state_only_load_props_refresh_identity_token)	frozensetrt   rh   )r:   populate_existingversion_checkonly_load_propsrefresh_stateidentity_tokenrt   compile_optionss           r<   _get_optionsQuery._get_optionsD  s     -:)*1B-.-:)*48O012;O2LO./6D23-!!_4!r?   c                 "    U R                  5       $ rA   )	_generater   s    r<   _cloneQuery._cloneb  s    ~~r?   c                    U R                   R                  (       d+  U R                   R                  (       d  U R                  SS9nOU R	                  SS9R
                  nU R                  (       a  UR                  U R                  5      nU$ )zThe full SELECT statement represented by this Query.

The statement by default will not have disambiguating labels
applied to the construct unless with_labels(True) is called
first.

Tfor_statement)rh   rf   _with_polymorphic_adapt_map_statement_20_compile_state	statement_paramsparams)r:   stmts     r<   r   Query.statemente  sn    < %%55))EE %%D%9D&&T&:DDD<<;;t||,Dr?   c                 T    U R                  5       nUR                  US9R                  $ )a  Return the 'final' SELECT statement for this :class:`.Query`.

This is the Core-only select() that will be rendered by a complete
compilation of this query, and is what .statement used to return
in 1.3.

This method creates a complete compile state so is fairly expensive.

)use_legacy_query_style)r   r   r   )r:   legacy_query_styleqs      r<   _final_statementQuery._final_statement  s/     KKM#5   

)	r?   c                 >   U R                   R                  (       a\  U R                   R                   HB  nU" U 5      nUc  M  X@Ld  M  Un UR                  (       a  M+  U =R                  SS0-  sl        MD     U R                  nUUUS.-  nU R                  bf  [        U R                  U R                  5      nUR                  R                  U R                  U R                  UU R                  U R                  S9  Ok[        R                  " S
0 U R                  D6nUR                  R                  U R                  UU R                  S9  UR                  R!                  SS 5        SUR                  ;  a#  UR                  R#                  SS S	.5      Ul        U$ )N_bake_okF)_for_statement_use_legacy_query_style)_with_options_with_context_optionsrh   _execution_optionsrC   )_label_stylerh   rC   r8   compile_state_pluginorm)r   plugin_subjectr5   )dispatchbefore_compiler   rh   r   FromStatementrO   __dict__updater   r   r   rC   r    _create_raw_selectr   popunion)r:   r   r   fn	new_queryr   r   s          r<   r   Query._statement_20  sr    ==''mm22tH	(Y-B$D;;;--*e1DD- 3 //+'=
 	

 ??& !2!2DOODDMM  "00&*&@&@!0#'#:#:!%!6!6 !  ,,=t}}=DMM  !..!0!%!6!6 ! 
 MMi. ")>)>>$($9$9$?$?).$G%D! r?   c                     U R                  S5      nU(       a  UR                  [        5      nUR                  nU(       a  UR	                  5       nUR                  US9$ )a  Return the full SELECT statement represented by
this :class:`_query.Query`, embedded within an
:class:`_expression.Alias`.

Eager JOIN generation within the query is disabled.

:param name: string name to be assigned as the alias;
    this is passed through to :meth:`_expression.FromClause.alias`.
    If ``None``, a name will be deterministically generated
    at compile time.

:param with_labels: if True, :meth:`.with_labels` will be called
 on the :class:`_query.Query` first to apply table-qualified labels
 to all columns.

:param reduce_columns: if True,
 :meth:`_expression.Select.reduce_columns` will
 be called on the resulting :func:`_expression.select` construct,
 to remove same-named columns where one also refers to the other
 via foreign key or WHERE clause equivalence.

F)name)enable_eagerloadsset_label_styler-   r   reduce_columnsalias)r:   r   with_labelsr   r   s        r<   subqueryQuery.subquery  sS    8 ""5)!!"@AAKK  "AwwDw!!r?   c                 T    U R                  S5      R                  R                  XUS9$ )a  Return the full SELECT statement represented by this
:class:`_query.Query` represented as a common table expression (CTE).

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

Here is the `PostgreSQL WITH
RECURSIVE example
<https://www.postgresql.org/docs/current/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:`_expression.HasCTE.cte`

F)r   	recursivenesting)r   r   cte)r:   r   r   r   s       r<   r   	Query.cte  s3    n %%e,66::G ; 
 	
r?   c                 V    U R                  S5      R                  R                  U5      $ )zReturn the full SELECT statement represented by this
:class:`_query.Query`, converted
to a scalar subquery with a label of the given name.

Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.label`.

F)r   r   label)r:   r   s     r<   r   Query.label3  s&     %%e,66<<TBBr?   1.4zThe :meth:`_query.Query.as_scalar` method is deprecated and will be removed in a future release.  Please refer to :meth:`_query.Query.scalar_subquery`.c                 "    U R                  5       $ )zmReturn the full SELECT statement represented by this
:class:`_query.Query`, converted to a scalar subquery.

)scalar_subqueryr   s    r<   	as_scalarQuery.as_scalar>  s     ##%%r?   c                 T    U R                  S5      R                  R                  5       $ )a9  Return the full SELECT statement represented by this
:class:`_query.Query`, converted to a scalar subquery.

Analogous to
:meth:`sqlalchemy.sql.expression.SelectBase.scalar_subquery`.

.. versionchanged:: 1.4 The :meth:`_query.Query.scalar_subquery`
   method replaces the :meth:`_query.Query.as_scalar` method.

F)r   r   r   r   s    r<   r   Query.scalar_subqueryK  s$     %%e,66FFHHr?   c                 "    U R                  5       $ )zReturn the :class:`_expression.Select` object emitted by this
:class:`_query.Query`.

Used for :func:`_sa.inspect` compatibility, this is equivalent to::

    query.enable_eagerloads(False).with_labels().statement

)__clause_element__r   s    r<   
selectableQuery.selectableY  s     &&((r?   c                 \    U R                  SSS9R                  [        5      R                  $ )NFT)_enable_eagerloads_render_for_subquery)_with_compile_optionsr   r-   r   r   s    r<   r   Query.__clause_element__e  s1    &&#(t '  _;<Y	
r?   c                 <    U =R                   [        US9-  sl         g)zWhen set to True, the query results will always be a tuple.

This is specifically for single element queries. The default is False.

.. versionadded:: 1.2.5

.. seealso::

    :meth:`_query.Query.is_single_entity`

)_only_return_tuplesN)rt   dictr:   values     r<   only_return_tuplesQuery.only_return_tuplesn  s     	Te<<r?   c                    U R                   R                  (       + =(       al    [        U R                  5      S:H  =(       aM    SU R                  S   R                  ;   =(       a*    [        U R                  S   R                  S   [        5      $ )a@  Indicates if this :class:`_query.Query`
returns tuples or single entities.

Returns True if this query returns a single entity for each instance
in its result list, and False if this query returns a tuple of entities
for each result.

.. versionadded:: 1.3.11

.. seealso::

    :meth:`_query.Query.only_return_tuples`

r   rS   r   )rt   r   r]   rO   rU   rV   r   r   s    r<   is_single_entityQuery.is_single_entity}  s|    " !!555 D%%&!+$"3"3A"6"C"CC !!!$11.A$		
r?   c                 2    U =R                   SU0-  sl         g)a  Control 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.Query.yield_per`.

r   Nrh   r  s     r<   r   Query.enable_eagerloads  s      	"6!>>r?   c                 .    U =R                   U-  sl         g rA   r
  )r:   opts     r<   r   Query._with_compile_options  s    $r?   zB:meth:`_orm.Query.with_labels` and :meth:`_orm.Query.apply_labels`z<Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) instead.)alternativec                 ,    U R                  [        5      $ rA   )r   r-   r   s    r<   r   Query.with_labels  s     ##$BCCr?   c                     U R                   $ )z;
Retrieve the current label style.

.. versionadded:: 1.4

r   r   s    r<   get_label_styleQuery.get_label_style  s        r?   c                 P    U R                   ULa  U R                  5       n Xl         U $ )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.Query.set_label_style` method *only* applies
   the output of :attr:`_query.Query.statement`, and *not* to any of
   the result-row invoking systems of :class:`_query.Query` itself,
   e.g.
   :meth:`_query.Query.first`, :meth:`_query.Query.all`, etc.
   To execute
   a query using :meth:`_query.Query.set_label_style`, invoke the
   :attr:`_query.Query.statement` using :meth:`.Session.execute`::

        result = session.execute(
            query
            .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
            .statement
        )

.. versionadded:: 1.4

)r   r   )r:   styles     r<   r   Query.set_label_style  s)    < E)>>#D %r?   c                     Xl         g)a  Control 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  s     r<   enable_assertionsQuery.enable_assertions  s
    ( #(r?   c                 h    [         R                  R                  R                  U R                  5      $ )zA readonly attribute which returns the current WHERE criterion for
this Query.

This returned value is a SQL expression construct, or ``None`` if no
criterion has been established.

)r   r   BooleanClauseList_construct_for_whereclauser   r   s    r<   whereclauseQuery.whereclause  s*     ||--HH  
 	
r?   c                 2    U =R                   SU0-  sl         g)zindicate 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.

_current_pathNr
  )r:   paths     r<   _with_current_pathQuery._with_current_path  s     	/4!88r?   z#:meth:`_orm.Query.with_polymorphic`z2Use the orm.with_polymorphic() standalone functionc                     [        U 5      n[        UUUUS9nU R                  R                  SU[	        U5      445      U l        g)a  Load columns for inheriting classes.

This is a legacy method which is replaced by the
:func:`_orm.with_polymorphic` function.

.. warning:: The :meth:`_orm.Query.with_polymorphic` method does
   **not** support 1.4/2.0 style features including
   :func:`_orm.with_loader_criteria`.  Please migrate code
   to use :func:`_orm.with_polymorphic`.

:meth:`_query.Query.with_polymorphic` applies transformations
to the "main" mapped class represented by this :class:`_query.Query`.
The "main" mapped class here means the :class:`_query.Query`
object's first argument is a full class, i.e.
``session.query(SomeClass)``. These transformations allow additional
tables to be present in the FROM clause so that columns for a
joined-inheritance subclass are available in the query, both for the
purposes of load-time efficiency as well as the ability to use
these columns at query time.

.. seealso::

    :ref:`with_polymorphic` - illustrates current patterns

)r   polymorphic_onr   N)r   r   rh   add_to_elementr   )r:   cls_or_mappersr   r'  rW   wps         r<   r   Query.with_polymorphic  sQ    F /t4!)	
 !% 5 5 D D)VWR[,A+C!
r?   c                 2    U =R                   SU0-  sl         g)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).

As of SQLAlchemy 1.4, the :meth:`_orm.Query.yield_per` method is
equivalent to using the ``yield_per`` execution option at the ORM
level. See the section :ref:`orm_queryguide_yield_per` for further
background on this option.

.. seealso::

    :ref:`orm_queryguide_yield_per`


_yield_perNrs   )r:   counts     r<   	yield_perQuery.yield_perC  s    . 	lE22r?   z:meth:`_orm.Query.get`z7The method is now available as :meth:`_orm.Session.get`)r  becomes_legacyc                 d    U R                  SSSS9  U R                  U[        R                  5      $ )a
  Return an instance based on the given primary key identifier,
or ``None`` if not found.

E.g.::

    my_user = session.query(User).get(5)

    some_object = session.query(VersionedFoo).get((5, 10))

    some_object = session.query(VersionedFoo).get(
        {"id": 5, "version_id": 10})

:meth:`_query.Query.get` is special in that it provides direct
access to the identity map of the owning :class:`.Session`.
If the given primary key identifier is present
in the local identity map, the object is returned
directly from this collection and no SQL is emitted,
unless the object has been marked fully expired.
If not present,
a SELECT is performed in order to locate the object.

:meth:`_query.Query.get` also will perform a check if
the object is present in the identity map and
marked as expired - a SELECT
is emitted to refresh the object as well as to
ensure that the row is still present.
If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.

:meth:`_query.Query.get` is only used to return a single
mapped instance, not multiple instances or
individual column constructs, and strictly
on a single primary key value.  The originating
:class:`_query.Query` must be constructed in this way,
i.e. against a single mapped entity,
with no additional filtering criterion.  Loading
options via :meth:`_query.Query.options` may be applied
however, and will be used if the object is not
yet locally present.

:param ident: A scalar, tuple, or dictionary representing the
 primary key.  For a composite (e.g. multiple column) primary key,
 a tuple or dictionary should be passed.

 For a single-column primary key, the scalar calling form is typically
 the most expedient.  If the primary key of a row is the value "5",
 the call looks like::

    my_object = query.get(5)

 The tuple form contains primary key values typically in
 the order in which they correspond to the mapped
 :class:`_schema.Table`
 object's primary key columns, or if the
 :paramref:`_orm.Mapper.primary_key` configuration parameter were
 used, in
 the order used for that parameter. For example, if the primary key
 of a row is represented by the integer
 digits "5, 10" the call would look like::

     my_object = query.get((5, 10))

 The dictionary form should include as keys the mapped attribute names
 corresponding to each element of the primary key.  If the mapped class
 has the attributes ``id``, ``version_id`` as the attributes which
 store the object's primary key value, the call would look like::

    my_object = query.get({"id": 5, "version_id": 10})

 .. versionadded:: 1.3 the :meth:`_query.Query.get`
    method now optionally
    accepts a dictionary of attribute names to values in order to
    indicate a primary key identifier.


:return: The object instance, or ``None``.

rz   Fr{   )r   	_get_implr   load_on_pk_identity)r:   idents     r<   rz   	Query.get\  s3    f 	$$UUU$K ~~eW%@%@AAr?   c                     U R                  S5      nU R                  R                  UUUU R                  R                  U R
                  U R                  UU R                  S9$ )Nrz   )r   with_for_updateoptionsr   execution_options)rb   r8   r3  rt   r   _for_update_argr   r   )r:   primary_key_identity
db_load_fnr   mappers        r<   r3  Query._get_impl  sd    ,,U3||%% "//BB 00&&)"55 & 	
 		
r?   c                 .    U R                   R                  $ )a`  An :class:`.InstanceState` that is using this :class:`_query.Query`
for a lazy load operation.

.. deprecated:: 1.4  This attribute should be viewed via the
   :attr:`.ORMExecuteState.lazy_loaded_from` attribute, within
   the context of the :meth:`.SessionEvents.do_orm_execute`
   event.

.. seealso::

    :attr:`.ORMExecuteState.lazy_loaded_from`

)rt   rr   r   s    r<   lazy_loaded_fromQuery.lazy_loaded_from  s       222r?   c                 .    U R                   R                  $ rA   )rh   r"  r   s    r<   r"  Query._current_path  s    $$222r?   c                     SU l         U(       a  US   S;   a  SU l        g[        U R                  5      R                  S U 5       5      U l        g)a  Return a :class:`.Query` construct which will correlate the given
FROM clauses to that of an enclosing :class:`.Query` or
:func:`~.expression.select`.

The method here accepts mapped classes, :func:`.aliased` constructs,
and :func:`.mapper` constructs as arguments, which are resolved into
expression constructs, in addition to appropriate expression
constructs.

The correlation arguments are ultimately passed to
:meth:`_expression.Select.correlate`
after coercion to expression constructs.

The correlation arguments take effect in such cases
as when :meth:`_query.Query.from_self` is used, or when
a subquery as returned by :meth:`_query.Query.subquery` is
embedded in another :func:`_expression.select` construct.

Fr   >   FNr5   c              3   l   #    U  H*  n[         R                  " [        R                  U5      v   M,     g 7frA   )r   rM   r   FromClauseRole).0fs     r<   	<genexpr>"Query.correlate.<locals>.<genexpr>  s)      9CNa	  !5!5q99;   24N)_auto_correlate
_correlatesetr   )r:   fromclausess     r<   	correlateQuery.correlate  sI    ,  %;q>]: DO!$//288 9CN9 DOr?   c                 2    U =R                   SU0-  sl         g)a  Return a Query with a specific 'autoflush' setting.

As of SQLAlchemy 1.4, the :meth:`_orm.Query.autoflush` method
is equivalent to using the ``autoflush`` execution option at the
ORM level. See the section :ref:`orm_queryguide_autoflush` for
further background on this option.


_autoflushNrs   )r:   settings     r<   	autoflushQuery.autoflush  s     	lG44r?   c                 2    U =R                   SS0-  sl         g)a  Return a :class:`_query.Query`
that will expire and refresh all instances
as they are loaded, or reused from the current :class:`.Session`.

As of SQLAlchemy 1.4, the :meth:`_orm.Query.populate_existing` method
is equivalent to using the ``populate_existing`` execution option at
the ORM level. See the section :ref:`orm_queryguide_populate_existing`
for further background on this option.

r   TNrs   r   s    r<   r   Query.populate_existing  s     	2D99r?   c                 2    U =R                   SU0-  sl         g)zSet the 'invoke all eagers' flag which causes joined- and
subquery loaders to traverse into already-loaded related objects
and collections.

Default is that of :attr:`_query.Query._invoke_all_eagers`.

_invoke_all_eagersNrs   r  s     r<   _with_invoke_all_eagersQuery._with_invoke_all_eagers  s     	2E::r?   z:meth:`_orm.Query.with_parent`z6Use the :func:`_orm.with_parent` standalone construct.zsqlalchemy.orm.relationshipsc                    [         R                  R                  nU(       a  [        U5      nO[	        U 5      nUc  [        U5      nUR                   H<  n[        XtR                  5      (       d  M  UR                  UR                  L d  M:  Un  OS   [        R                  " SUR                  R                  R                  < SUR                  R                  < S35      eU R                  [!        XUR"                  5      5      $ )a  Add filtering criterion that relates the given instance
to a child object or collection, using its attribute state
as well as an established :func:`_orm.relationship()`
configuration.

The method uses the :func:`.with_parent` function to generate
the clause, the result of which is passed to
:meth:`_query.Query.filter`.

Parameters are the same as :func:`.with_parent`, with the exception
that the given property can be None, in which case a search is
performed against this :class:`_query.Query` object's target mapper.

:param instance:
  An instance which has some :func:`_orm.relationship`.

:param property:
  String property name, or class-bound attribute, which indicates
  what relationship from the instance should be used to reconcile the
  parent/child relationship.

:param from_entity:
  Entity in which to consider as the left side.  This defaults to the
  "zero" entity of the :class:`_query.Query` itself.

z>Could not locate a property which relates instances of class 'z' to instances of class '')r   	preloadedorm_relationshipsr   r   r   iterate_propertiesrV   RelationshipPropertyr>  r_   r`   class___name__	__class__filterr   rW   )r:   instancepropertyfrom_entityrelationshipsentity_zeror>  props           r<   r   Query.with_parent  s    B 88!+.K7=K"8,F11t%G%GHH{'9'99#H 2 00 $**11:: **33	  {{;x;;M;MNOOr?   c                     Ub  [        X5      n[        U R                  5      U l        U R                  R                  [        R
                  " [        R                  XS95        g)zAadd a mapped entity to the list of result columns
to be returned.NrJ   )r   listrO   appendr   rM   r   rN   )r:   rW   r   s      r<   
add_entityQuery.add_entityX  sT    
 V+F !2!23  ''	
r?   c                     Xl         g)a  Return a :class:`_query.Query` that will use the given
:class:`.Session`.

While the :class:`_query.Query`
object is normally instantiated using the
:meth:`.Session.query` method, it is legal to build the
:class:`_query.Query`
directly without necessarily using a :class:`.Session`.  Such a
:class:`_query.Query` object, or any :class:`_query.Query`
already associated
with a different :class:`.Session`, can produce a new
:class:`_query.Query`
object associated with a target session using this method::

    from sqlalchemy.orm import Query

    query = Query([MyClass]).filter(MyClass.id == 5)

    result = query.with_session(my_session).one()

N)r8   )r:   r8   s     r<   with_sessionQuery.with_sessioni  s	    0 r?   z:meth:`_query.Query.from_self`zThe new approach is to use the :func:`.orm.aliased` construct in conjunction with a subquery.  See the section :ref:`Selecting from the query itself as a subquery <migration_20_query_from_self>` in the 2.0 migration notes for an example.c                      U R                   " U6 $ )a  return a Query that selects from this Query's
SELECT statement.

:meth:`_query.Query.from_self` essentially turns the SELECT statement
into a SELECT of itself.  Given a query such as::

    q = session.query(User).filter(User.name.like('e%'))

Given the :meth:`_query.Query.from_self` version::

    q = session.query(User).filter(User.name.like('e%')).from_self()

This query renders as:

.. sourcecode:: sql

    SELECT anon_1.user_id AS anon_1_user_id,
           anon_1.user_name AS anon_1_user_name
    FROM (SELECT "user".id AS user_id, "user".name AS user_name
    FROM "user"
    WHERE "user".name LIKE :name_1) AS anon_1

There are lots of cases where :meth:`_query.Query.from_self`
may be useful.
A simple one is where above, we may want to apply a row LIMIT to
the set of user objects we query against, and then apply additional
joins against that row-limited set::

    q = session.query(User).filter(User.name.like('e%')).\
        limit(5).from_self().\
        join(User.addresses).filter(Address.email.like('q%'))

The above query joins to the ``Address`` entity but only against the
first five results of the ``User`` query:

.. sourcecode:: sql

    SELECT anon_1.user_id AS anon_1_user_id,
           anon_1.user_name AS anon_1_user_name
    FROM (SELECT "user".id AS user_id, "user".name AS user_name
    FROM "user"
    WHERE "user".name LIKE :name_1
     LIMIT :param_1) AS anon_1
    JOIN address ON anon_1.user_id = address.user_id
    WHERE address.email LIKE :email_1

**Automatic Aliasing**

Another key behavior of :meth:`_query.Query.from_self`
is that it applies
**automatic aliasing** to the entities inside the subquery, when
they are referenced on the outside.  Above, if we continue to
refer to the ``User`` entity without any additional aliasing applied
to it, those references will be in terms of the subquery::

    q = session.query(User).filter(User.name.like('e%')).\
        limit(5).from_self().\
        join(User.addresses).filter(Address.email.like('q%')).\
        order_by(User.name)

The ORDER BY against ``User.name`` is aliased to be in terms of the
inner subquery:

.. sourcecode:: sql

    SELECT anon_1.user_id AS anon_1_user_id,
           anon_1.user_name AS anon_1_user_name
    FROM (SELECT "user".id AS user_id, "user".name AS user_name
    FROM "user"
    WHERE "user".name LIKE :name_1
     LIMIT :param_1) AS anon_1
    JOIN address ON anon_1.user_id = address.user_id
    WHERE address.email LIKE :email_1 ORDER BY anon_1.user_name

The automatic aliasing feature only works in a **limited** way,
for simple filters and orderings.   More ambitious constructions
such as referring to the entity in joins should prefer to use
explicit subquery objects, typically making use of the
:meth:`_query.Query.subquery`
method to produce an explicit subquery object.
Always test the structure of queries by viewing the SQL to ensure
a particular structure does what's expected!

**Changing the Entities**

:meth:`_query.Query.from_self`
also includes the ability to modify what
columns are being queried.   In our example, we want ``User.id``
to be queried by the inner query, so that we can join to the
``Address`` entity on the outside, but we only wanted the outer
query to return the ``Address.email`` column::

    q = session.query(User).filter(User.name.like('e%')).\
        limit(5).from_self(Address.email).\
        join(User.addresses).filter(Address.email.like('q%'))

yielding:

.. sourcecode:: sql

    SELECT address.email AS address_email
    FROM (SELECT "user".id AS user_id, "user".name AS user_name
    FROM "user"
    WHERE "user".name LIKE :name_1
     LIMIT :param_1) AS anon_1
    JOIN address ON anon_1.user_id = address.user_id
    WHERE address.email LIKE :email_1

**Looking out for Inner / Outer Columns**

Keep in mind that when referring to columns that originate from
inside the subquery, we need to ensure they are present in the
columns clause of the subquery itself; this is an ordinary aspect of
SQL.  For example, if we wanted to load from a joined entity inside
the subquery using :func:`.contains_eager`, we need to add those
columns.   Below illustrates a join of ``Address`` to ``User``,
then a subquery, and then we'd like :func:`.contains_eager` to access
the ``User`` columns::

    q = session.query(Address).join(Address.user).\
        filter(User.name.like('e%'))

    q = q.add_entity(User).from_self().\
        options(contains_eager(Address.user))

We use :meth:`_query.Query.add_entity` above **before** we call
:meth:`_query.Query.from_self`
so that the ``User`` columns are present
in the inner subquery, so that they are available to the
:func:`.contains_eager` modifier we are using on the outside,
producing:

.. sourcecode:: sql

    SELECT anon_1.address_id AS anon_1_address_id,
           anon_1.address_email AS anon_1_address_email,
           anon_1.address_user_id AS anon_1_address_user_id,
           anon_1.user_id AS anon_1_user_id,
           anon_1.user_name AS anon_1_user_name
    FROM (
        SELECT address.id AS address_id,
        address.email AS address_email,
        address.user_id AS address_user_id,
        "user".id AS user_id,
        "user".name AS user_name
    FROM address JOIN "user" ON "user".id = address.user_id
    WHERE "user".name LIKE :name_1) AS anon_1

If we didn't call ``add_entity(User)``, but still asked
:func:`.contains_eager` to load the ``User`` entity, it would be
forced to add the table on the outside without the correct
join criteria - note the ``anon1, "user"`` phrase at
the end:

.. sourcecode:: sql

    -- incorrect query
    SELECT anon_1.address_id AS anon_1_address_id,
           anon_1.address_email AS anon_1_address_email,
           anon_1.address_user_id AS anon_1_address_user_id,
           "user".id AS user_id,
           "user".name AS user_name
    FROM (
        SELECT address.id AS address_id,
        address.email AS address_email,
        address.user_id AS address_user_id
    FROM address JOIN "user" ON "user".id = address.user_id
    WHERE "user".name LIKE :name_1) AS anon_1, "user"

:param \*entities: optional list of entities which will replace
 those being selected.

)
_from_selfr:   r;   s     r<   	from_selfQuery.from_self  s    l ))r?   c                     U R                  [        5      R                  S 5      R                  5       R	                  5       nU R                  U5      nU(       a  UR                  U5        U$ rA   )r   r-   rQ  r   _anonymous_fromclause_from_selectabler9   )r:   r;   
fromclauser   s       r<   ry  Query._from_self;  sU      !?@Yt_XZ""$	 	 !!*-OOH%r?   c                 2    U =R                   SU0-  sl         g )N_enable_single_critr
  )r:   vals     r<   _set_enable_single_critQuery._set_enable_single_critI  s    "7!==r?   c                     S H  nU R                   R                  US 5        M!     U R                  U/U5        U =R                  SS0-  sl        U =R                  SS0-  sl        g )N)r   r   r   r   r   _last_joined_entityr   _memoized_select_entitiesr   _distinct_on_having_criteria	_prefixes	_suffixesr  F_orm_only_from_obj_alias)r   r   ro   rh   )r:   r  set_entity_fromattrs       r<   r  Query._from_selectableM  sl    
D MMdD)
  	zlO<!5"
 	
 	"<e!DDr?   z:meth:`_query.Query.values` is deprecated and will be removed in a future release.  Please use :meth:`_query.Query.with_entities`c                     U(       d  [        S5      $ U R                  5       R                  S5      nUR                  U5        UR                  R
                  (       d  U=R                  SS0-  sl        [        U5      $ )zVReturn an iterator yielding result tuples corresponding
to the given list of columns

r5   Fr-  
   )iterr   r   r9   rt   r-  )r:   columnsr   s      r<   rD   Query.valuesk  s[     8OKKM++E2	 ~~((NN|R00NAwr?   z:meth:`_query.Query.value` is deprecated and will be removed in a future release.  Please use :meth:`_query.Query.with_entities` in combination with :meth:`_query.Query.scalar`c                 ^     [        U R                  U5      5      S   $ ! [         a     gf = f)zFReturn a scalar result corresponding to the given
column expression.

r   N)nextrD   StopIterationr:   columns     r<   r  Query.value  s2    	F+,Q// 		s    
,,c                 R    [         R                  " U 5        U R                  U5        g)a  Return a new :class:`_query.Query`
replacing the SELECT list with the
given entities.

e.g.::

    # Users, filtered on some arbitrary criterion
    # and then ordered by related email address
    q = session.query(User).\
                join(User.address).\
                filter(User.name.like('%ed%')).\
                order_by(Address.email)

    # given *only* User.id==5, Address.email, and 'q', what
    # would the *next* User in the result be ?
    subq = q.with_entities(Address.email).\
                order_by(None).\
                filter(User.id==5).\
                subquery()
    q = q.join((subq, subq.c.email < Address.email)).\
                limit(1)

N)r&   _generate_for_statementr9   rz  s     r<   with_entitiesQuery.with_entities  s     2 	 77=8$r?   c                    ^  [        T R                  5      T l        T R                  R                  U 4S jU 5       5        g)zPAdd one or more column expressions to the list
of result columns to be returned.c              3   n   >#    U  H*  n[         R                  " [        R                  UTS S9v   M,     g7f)TrI   N)r   rM   r   rN   )rH  cr:   s     r<   rJ  $Query.add_columns.<locals>.<genexpr>  s9      !
  ''&*!	 s   25N)rq  rO   extendr  s   ` r<   add_columnsQuery.add_columns  s;    
 !!2!23   !
 !
 	
r?   z:meth:`_query.Query.add_column` is deprecated and will be removed in a future release.  Please use :meth:`_query.Query.add_columns`c                 $    U R                  U5      $ )zGAdd a column expression to the list of result columns to be
returned.

)r  r  s     r<   
add_columnQuery.add_column  s     ''r?   c                 X   [        [        R                  " U5      5      nU R                  R                  (       a.  U H'  nUR
                  (       d  M  UR                  U 5        M)     O-U H'  nUR
                  (       d  M  UR                  U 5        M)     U =R                  U-  sl        g)a  Return a new :class:`_query.Query` object,
applying the given list of
mapper options.

Most supplied options regard changing how column- and
relationship-mapped attributes are loaded.

.. seealso::

    :ref:`deferred_options`

    :ref:`relationship_loader_options`

N)	ri   r   flatten_iteratorrh   r"  _is_legacy_optionprocess_query_conditionallyprocess_queryr   )r:   argsoptsr  s       r<   r9  Query.options  s    " T**401  ..(((33D9  (((%%d+  	d"r?   c                     U" U 5      $ )a  Return a new :class:`_query.Query` object transformed by
the given function.

E.g.::

    def filter_something(criterion):
        def transform(q):
            return q.filter(criterion)
        return transform

    q = q.with_transformation(filter_something(x==5))

This allows ad-hoc recipes to be created for :class:`_query.Query`
objects.  See the example at :ref:`hybrid_transformers`.

r5   )r:   r   s     r<   with_transformationQuery.with_transformation  s    " $xr?   c                     U R                   $ )zGet the non-SQL options which will take effect during execution.

.. versionadded:: 1.3

.. seealso::

    :meth:`_query.Query.execution_options`
)r   r   s    r<   get_execution_optionsQuery.get_execution_options  s     &&&r?   c                 D    U R                   R                  U5      U l         g)a^  Set non-SQL options which take effect during execution.

Options allowed here include all of those accepted by
:meth:`_engine.Connection.execution_options`, as well as a series
of ORM specific options:

``populate_existing=True`` - equivalent to using
:meth:`_orm.Query.populate_existing`

``autoflush=True|False`` - equivalent to using
:meth:`_orm.Query.autoflush`

``yield_per=<value>`` - equivalent to using
:meth:`_orm.Query.yield_per`

Note that the ``stream_results`` execution option is enabled
automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()`
method or execution option is used.

.. versionadded:: 1.4 - added ORM options to
   :meth:`_orm.Query.execution_options`

The execution options may also be specified on a per execution basis
when using :term:`2.0 style` queries via the
:paramref:`_orm.Session.execution_options` parameter.

.. warning:: The
   :paramref:`_engine.Connection.execution_options.stream_results`
   parameter should not be used at the level of individual ORM
   statement executions, as the :class:`_orm.Session` will not track
   objects from different schema translate maps within a single
   session.  For multiple schema translate maps within the scope of a
   single :class:`_orm.Session`, see :ref:`examples_sharding`.


.. seealso::

    :ref:`engine_stream_results`

    :meth:`_query.Query.get_execution_options`

N)r   r   )r:   kwargss     r<   r:  Query.execution_options  s    X #'"9"9"?"?"Gr?   c                 (    [        UUUUUS9U l        g)a  return a new :class:`_query.Query`
with the specified options for the
``FOR UPDATE`` clause.

The behavior of this method is identical to that of
:meth:`_expression.GenerativeSelect.with_for_update`.
When called with no arguments,
the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause
appended.  When additional arguments are specified, backend-specific
options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE``
can take effect.

E.g.::

    q = sess.query(User).populate_existing().with_for_update(nowait=True, of=User)

The above query on a PostgreSQL backend will render like::

    SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT

.. warning::

    Using ``with_for_update`` in the context of eager loading
    relationships is not officially supported or recommended by
    SQLAlchemy and may not work with certain queries on various
    database backends.  When ``with_for_update`` is successfully used
    with a query that involves :func:`_orm.joinedload`, SQLAlchemy will
    attempt to emit SQL that locks all involved tables.

.. note::  It is generally a good idea to combine the use of the
   :meth:`_orm.Query.populate_existing` method when using the
   :meth:`_orm.Query.with_for_update` method.   The purpose of
   :meth:`_orm.Query.populate_existing` is to force all the data read
   from the SELECT to be populated into the ORM objects returned,
   even if these objects are already in the :term:`identity map`.

.. seealso::

    :meth:`_expression.GenerativeSelect.with_for_update`
    - Core level method with
    full argument and behavioral description.

    :meth:`_orm.Query.populate_existing` - overwrites attributes of
    objects already loaded in the identity map.

)readnowaitofskip_locked	key_shareN)r(   r;  )r:   r  r  r  r  r  s         r<   r8  Query.with_for_update5  s!    p  ,# 
r?   c                     [        U5      S:X  a  UR                  US   5        O%[        U5      S:  a  [        R                  " S5      eU R                  R                  U5      U l        g)aS  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.

r   r   zFparams() takes zero or one positional argument, which is a dictionary.N)r]   r   r_   ArgumentErrorr   r   )r:   r  r  s      r<   r   Query.paramsu  sZ     t9>MM$q'"Y]&&)  ||))&1r?   c                      U R                   " U6 $ )z=A synonym for :meth:`.Query.filter`.

.. versionadded:: 1.4

)rg  r:   	criterions     r<   whereQuery.where  s     {{I&&r?   c                    [        U5       Hp  n[        R                  " [        R                  XS9nU R
                  (       a#  [        R                  " USU R
                  05      nU =R                  U4-  sl        Mr     g)a  Apply the given filtering criterion to a copy
of this :class:`_query.Query`, using SQL expressions.

e.g.::

    session.query(MyClass).filter(MyClass.name == 'some name')

Multiple criteria may be specified as comma separated; the effect
is that they will be joined together using the :func:`.and_`
function::

    session.query(MyClass).\
        filter(MyClass.name == 'some name', MyClass.id > 5)

The criterion is any SQL expression object applicable to the
WHERE clause of a select.   String expressions are coerced
into SQL expression constructs via the :func:`_expression.text`
construct.

.. seealso::

    :meth:`_query.Query.filter_by` - filter on keyword expressions.

rp  aliased_generationN)	rq  r   rM   r   WhereHavingRole_aliased_generationsql_util_deep_annotater   r  s     r<   rg  Query.filter  sn    6 iI!((%%yI
 ''$33 4d6N6NO	
   YL0  )r?   c                 n    U R                   (       a$  [        U R                   U R                  5       5      $ g rA   )r   r   rZ   r   s    r<   r  Query._last_joined_entity  s1    ##7(($*H*H*J  r?   c                     U R                   (       a  U R                  nUb  U$ U R                  (       a*  U R                  R                  (       d  U R                  S   $ U R
                  S   $ )zfor the filter_by() method, return the target entity for which
we will attempt to derive an expression from based on string name.

r   )r   r  rj   rh   rf   rO   )r:   r  s     r<   _filter_by_zeroQuery._filter_by_zero  s\     ##"&":":".**8 >>$"7"7"G"G>>!$$  ##r?   c                     U R                  5       nUc'  [        R                  " SU R                  5       -  5      eUR	                  5        VVs/ s H  u  p4[        X#5      U:H  PM     nnnU R                  " U6 $ s  snnf )aj  Apply the given filtering criterion to a copy
of this :class:`_query.Query`, using keyword expressions.

e.g.::

    session.query(MyClass).filter_by(name = 'some name')

Multiple criteria may be specified as comma separated; the effect
is that they will be joined together using the :func:`.and_`
function::

    session.query(MyClass).\
        filter_by(name = 'some name', id = 5)

The keyword expressions are extracted from the primary
entity of the query, or the last entity that was the
target of a call to :meth:`_query.Query.join`.

.. seealso::

    :meth:`_query.Query.filter` - filter on SQL expressions.

zCan't use filter_by when the first entity '%s' of a query is not a mapped class. Please use the filter method instead, or change the order of the entities in the query)r  r_   r`   _query_entity_zeroitemsr#   rg  )r:   r  rj  keyr  clausess         r<   	filter_byQuery.filter_by  s    0 **,,,C ))+,  %lln
,
 "+3u<, 	 
 {{G$$	
s   A:c           
      B   [        U5      S:X  a  US   b  US   SL a  SU l        g[        S U 5       5      nU R                  (       a=  [        U Vs/ s H&  n[        R
                  " USU R                  05      PM(     sn5      nU =R                  U-  sl        gs  snf )a:  Apply one or more ORDER BY criteria to the query and return
the newly resulting :class:`_query.Query`.

e.g.::

    q = session.query(Entity).order_by(Entity.id, Entity.name)

Calling this method multiple times is equivalent to calling it once
with all the clauses concatenated. All existing ORDER BY criteria may
be cancelled by passing ``None`` by itself.  New ORDER BY criteria may
then be added by invoking :meth:`_orm.Query.order_by` again, e.g.::

    # will erase all ORDER BY and ORDER BY new_col alone
    q = q.order_by(None).order_by(new_col)

.. seealso::

    These sections describe ORDER BY in terms of :term:`2.0 style`
    invocation but apply to :class:`_orm.Query` as well:

    :ref:`tutorial_order_by` - in the :ref:`unified_tutorial`

    :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

r   r   NFr5   c              3   l   #    U  H*  n[         R                  " [        R                  U5      v   M,     g 7frA   )r   rM   r   OrderByRolerH  clauses     r<   rJ  !Query.order_by.<locals>.<genexpr>4  -      %F   !2!2F;;%rL  r  )r]   r   ri   r  r  r  r:   r  r  os       r<   r|   Query.order_by  s    : w<1'!*"4
e8K%'D" % I
 ''!
 "+	 "+A !// 4d6N6NO "+		 ""i/"   -Bc           
      B   [        U5      S:X  a  US   b  US   SL a  SU l        g[        S U 5       5      nU R                  (       a=  [        U Vs/ s H&  n[        R
                  " USU R                  05      PM(     sn5      nU =R                  U-  sl        gs  snf )a  Apply one or more GROUP BY criterion to the query and return
the newly resulting :class:`_query.Query`.

All existing GROUP BY settings can be suppressed by
passing ``None`` - this will suppress any GROUP BY configured
on mappers as well.

.. seealso::

    These sections describe GROUP BY in terms of :term:`2.0 style`
    invocation but apply to :class:`_orm.Query` as well:

    :ref:`tutorial_group_by_w_aggregates` - in the
    :ref:`unified_tutorial`

    :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

r   r   NFr5   c              3   l   #    U  H*  n[         R                  " [        R                  U5      v   M,     g 7frA   )r   rM   r   GroupByRoler  s     r<   rJ  !Query.group_by.<locals>.<genexpr>_  r  rL  r  )r]   r   ri   r  r  r  r  s       r<   group_byQuery.group_byF  s    , w<1'!*"4
e8K%'D" % I
 ''!
 "+	 "+A !// 4d6N6NO "+		 ""i/"r  c                 r    U =R                   [        R                  " [        R                  XS94-  sl         g)a  Apply a HAVING criterion to the query and return the
newly resulting :class:`_query.Query`.

:meth:`_query.Query.having` is used in conjunction with
:meth:`_query.Query.group_by`.

HAVING criterion makes it possible to use filters on aggregate
functions like COUNT, SUM, AVG, MAX, and MIN, eg.::

    q = session.query(User.id).\
                join(User.addresses).\
                group_by(User.id).\
                having(func.count(Address.id) > 2)

rp  N)r  r   rM   r   r  r  s     r<   havingQuery.havingq  s3    & 	%%y"
 	
r?   c                 `    U R                  U" U /[        U5      -   6 R                  5       5      $ rA   )r  rq  r   )r:   expr_fnr   s      r<   _set_opQuery._set_op  s,    $$WvQ/?%A%J%J%LMMr?   c                 D    U R                   " [        R                  /UQ76 $ )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.Query` object will not render ORDER BY within
its SELECT statement.

)r  r   r   r:   r   s     r<   r   Query.union  s    J ||J,,1q11r?   c                 D    U R                   " [        R                  /UQ76 $ )zProduce a UNION ALL of this Query against one or more queries.

Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.

)r  r   	union_allr  s     r<   r  Query.union_all       ||J005155r?   c                 D    U R                   " [        R                  /UQ76 $ )zProduce an INTERSECT of this Query against one or more queries.

Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.

)r  r   	intersectr  s     r<   r  Query.intersect  r  r?   c                 D    U R                   " [        R                  /UQ76 $ )zProduce an INTERSECT ALL of this Query against one or more queries.

Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.

)r  r   intersect_allr  s     r<   r  Query.intersect_all  s     ||J449q99r?   c                 D    U R                   " [        R                  /UQ76 $ )zProduce an EXCEPT of this Query against one or more queries.

Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.

)r  r   except_r  s     r<   r  Query.except_  s     ||J..333r?   c                 D    U R                   " [        R                  /UQ76 $ )zProduce an EXCEPT ALL of this Query against one or more queries.

Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.

)r  r   
except_allr  s     r<   r  Query.except_all  s     ||J116A66r?   c                 r    SU R                   ;  a  SU l        U =R                  S-  sl        U R                  $ )N_aliased_generation_counterr   r   )r   r
  r   s    r<   _next_aliased_generationQuery._next_aliased_generation  s3    (=/0D,((A-(///r?   c           	        ^ ^
^^^ UR                  SS5      UR                  SS5      UR                  SS5      UR                  SS5      4u  m
mmmT
(       d  T(       a  [        R                  " S5        U(       a&  [        SSR	                  [        U5      5      -  5      eT(       d  S	T l        S	T l        U(       a
  US
   USS	 pTOS	=pEU(       d  Uc  [        U[        5      (       d  U4/nGOZU(       d  [        U[        R                  [        [        [        R                  45      (       aH  [        U[         R"                  [$        [&        R(                  [        R                  45      (       a  X4/nO/ n/ nU4U-    H  n[        U[        5      (       a|  [        R                  " S5        U(       a  UR+                  S U 5       5        / n[        US
   [$        [&        R(                  45      (       a
  US   US
   4nUR-                  U5        M  UR-                  U5        M     U(       a  UR+                  S U 5       5        T
(       a  T R/                  5       T l        T R                  (       as  U Vs/ s Hf  n[1        U5      S:X  aR  US
   [        US   [        R2                  5      (       a&  [4        R6                  " US   ST R                  05      OUS   4OUPMh     nn[        U
UUUU 4S j[9        U5       5       5      n	[1        U	5      S:  a  [        R                  " S5        T =R:                  U	-  sl        T R<                  R                  SS	5        g	s  snf )a)  Create a SQL JOIN against this :class:`_query.Query`
object's criterion
and apply generatively, returning the newly resulting
:class:`_query.Query`.

**Simple Relationship Joins**

Consider a mapping between two classes ``User`` and ``Address``,
with a relationship ``User.addresses`` representing a collection
of ``Address`` objects associated with each ``User``.   The most
common usage of :meth:`_query.Query.join`
is to create a JOIN along this
relationship, using the ``User.addresses`` attribute as an indicator
for how this should occur::

    q = session.query(User).join(User.addresses)

Where above, the call to :meth:`_query.Query.join` along
``User.addresses`` will result in SQL approximately equivalent to::

    SELECT user.id, user.name
    FROM user JOIN address ON user.id = address.user_id

In the above example we refer to ``User.addresses`` as passed to
:meth:`_query.Query.join` as the "on clause", that is, it indicates
how the "ON" portion of the JOIN should be constructed.

To construct a chain of joins, multiple :meth:`_query.Query.join`
calls may be used.  The relationship-bound attribute implies both
the left and right side of the join at once::

    q = session.query(User).\
            join(User.orders).\
            join(Order.items).\
            join(Item.keywords)

.. note:: as seen in the above example, **the order in which each
   call to the join() method occurs is important**.    Query would not,
   for example, know how to join correctly if we were to specify
   ``User``, then ``Item``, then ``Order``, in our chain of joins; in
   such a case, depending on the arguments passed, it may raise an
   error that it doesn't know how to join, or it may produce invalid
   SQL in which case the database will raise an error. In correct
   practice, the
   :meth:`_query.Query.join` method is invoked in such a way that lines
   up with how we would want the JOIN clauses in SQL to be
   rendered, and each call should represent a clear link from what
   precedes it.

**Joins to a Target Entity or Selectable**

A second form of :meth:`_query.Query.join` allows any mapped entity or
core selectable construct as a target.   In this usage,
:meth:`_query.Query.join` will attempt to create a JOIN along the
natural foreign key relationship between two entities::

    q = session.query(User).join(Address)

In the above calling form, :meth:`_query.Query.join` is called upon to
create the "on clause" automatically for us.  This calling form will
ultimately raise an error if either there are no foreign keys between
the two entities, or if there are multiple foreign key linkages between
the target entity and the entity or entities already present on the
left side such that creating a join requires more information.  Note
that when indicating a join to a target without any ON clause, ORM
configured relationships are not taken into account.

**Joins to a Target with an ON Clause**

The third calling form allows both the target entity as well
as the ON clause to be passed explicitly.    A example that includes
a SQL expression as the ON clause is as follows::

    q = session.query(User).join(Address, User.id==Address.user_id)

The above form may also use a relationship-bound attribute as the
ON clause as well::

    q = session.query(User).join(Address, User.addresses)

The above syntax can be useful for the case where we wish
to join to an alias of a particular target entity.  If we wanted
to join to ``Address`` twice, it could be achieved using two
aliases set up using the :func:`~sqlalchemy.orm.aliased` function::

    a1 = aliased(Address)
    a2 = aliased(Address)

    q = session.query(User).\
            join(a1, User.addresses).\
            join(a2, User.addresses).\
            filter(a1.email_address=='ed@foo.com').\
            filter(a2.email_address=='ed@bar.com')

The relationship-bound calling form can also specify a target entity
using the :meth:`_orm.PropComparator.of_type` method; a query
equivalent to the one above would be::

    a1 = aliased(Address)
    a2 = aliased(Address)

    q = session.query(User).\
            join(User.addresses.of_type(a1)).\
            join(User.addresses.of_type(a2)).\
            filter(a1.email_address == 'ed@foo.com').\
            filter(a2.email_address == 'ed@bar.com')

**Augmenting Built-in ON Clauses**

As a substitute for providing a full custom ON condition for an
existing relationship, the :meth:`_orm.PropComparator.and_` function
may be applied to a relationship attribute to augment additional
criteria into the ON clause; the additional criteria will be combined
with the default criteria using AND::

    q = session.query(User).join(
        User.addresses.and_(Address.email_address != 'foo@bar.com')
    )

.. versionadded:: 1.4

**Joining to Tables and Subqueries**


The target of a join may also be any table or SELECT statement,
which may be related to a target entity or not.   Use the
appropriate ``.subquery()`` method in order to make a subquery
out of a query::

    subq = session.query(Address).\
        filter(Address.email_address == 'ed@foo.com').\
        subquery()


    q = session.query(User).join(
        subq, User.id == subq.c.user_id
    )

Joining to a subquery in terms of a specific relationship and/or
target entity may be achieved by linking the subquery to the
entity using :func:`_orm.aliased`::

    subq = session.query(Address).\
        filter(Address.email_address == 'ed@foo.com').\
        subquery()

    address_subq = aliased(Address, subq)

    q = session.query(User).join(
        User.addresses.of_type(address_subq)
    )


**Controlling what to Join From**

In cases where the left side of the current state of
:class:`_query.Query` is not in line with what we want to join from,
the :meth:`_query.Query.select_from` method may be used::

    q = session.query(Address).select_from(User).\
                    join(User.addresses).\
                    filter(User.name == 'ed')

Which will produce SQL similar to::

    SELECT address.* FROM user
        JOIN address ON user.id=address.user_id
        WHERE user.name = :name_1

**Legacy Features of Query.join()**

.. deprecated:: 1.4 The following features are deprecated and will
   be removed in SQLAlchemy 2.0.

The :meth:`_query.Query.join` method currently supports several
usage patterns and arguments that are considered to be legacy
as of SQLAlchemy 1.3.   A deprecation path will follow
in the 1.4 series for the following features:


* Joining on relationship names rather than attributes::

    session.query(User).join("addresses")

  **Why it's legacy**: the string name does not provide enough context
  for :meth:`_query.Query.join` to always know what is desired,
  notably in that there is no indication of what the left side
  of the join should be.  This gives rise to flags like
  ``from_joinpoint`` as well as the ability to place several
  join clauses in a single :meth:`_query.Query.join` call
  which don't solve the problem fully while also
  adding new calling styles that are unnecessary and expensive to
  accommodate internally.

  **Modern calling pattern**:  Use the actual relationship,
  e.g. ``User.addresses`` in the above case::

      session.query(User).join(User.addresses)

* Automatic aliasing with the ``aliased=True`` flag::

    session.query(Node).join(Node.children, aliased=True).\
        filter(Node.name == 'some name')

  **Why it's legacy**:  the automatic aliasing feature of
  :class:`_query.Query` is intensely complicated, both in its internal
  implementation as well as in its observed behavior, and is almost
  never used.  It is difficult to know upon inspection where and when
  its aliasing of a target entity, ``Node`` in the above case, will be
  applied and when it won't, and additionally the feature has to use
  very elaborate heuristics to achieve this implicit behavior.

  **Modern calling pattern**: Use the :func:`_orm.aliased` construct
  explicitly::

    from sqlalchemy.orm import aliased

    n1 = aliased(Node)

    session.query(Node).join(Node.children.of_type(n1)).\
        filter(n1.name == 'some name')

* Multiple joins in one call::

    session.query(User).join("orders", "items")

    session.query(User).join(User.orders, Order.items)

    session.query(User).join(
        (Order, User.orders),
        (Item, Item.order_id == Order.id)
    )

    session.query(User).join(Order, Item)

    # ... and several more forms actually

  **Why it's legacy**: being able to chain multiple ON clauses in one
  call to :meth:`_query.Query.join` is yet another attempt to solve
  the problem of being able to specify what entity to join from,
  and is the source of a large variety of potential calling patterns
  that are internally expensive and complicated to parse and
  accommodate.

  **Modern calling pattern**:  Use relationship-bound attributes
  or SQL-oriented ON clauses within separate calls, so that
  each call to :meth:`_query.Query.join` knows what the left
  side should be::

    session.query(User).join(User.orders).join(
        Item, Item.order_id == Order.id)


:param \*props: Incoming arguments for :meth:`_query.Query.join`,
 the props collection in modern use should be considered to be a  one
 or two argument form, either as a single "target" entity or ORM
 attribute-bound relationship, or as a target entity plus an "on
 clause" which  may be a SQL expression or ORM attribute-bound
 relationship.

:param isouter=False: If True, the join used will be a left outer join,
 just as if the :meth:`_query.Query.outerjoin` method were called.

:param full=False: render FULL OUTER JOIN; implies ``isouter``.

 .. versionadded:: 1.1

:param from_joinpoint=False: When using ``aliased=True``, a setting
 of True here will cause the join to be from the most recent
 joined target, rather than starting back from the original
 FROM clauses of the query.

 .. note:: This flag is considered legacy.

:param aliased=False: If True, indicate that the JOIN target should be
 anonymously aliased.  Subsequent calls to :meth:`_query.Query.filter`
 and similar will adapt the incoming criterion to the target
 alias, until :meth:`_query.Query.reset_joinpoint` is called.

 .. note:: This flag is considered legacy.

.. seealso::

    :ref:`ormtutorial_joins` in the ORM tutorial.

    :ref:`inheritance_toplevel` for details on how
    :meth:`_query.Query.join` is used for inheritance relationships.

    :func:`_orm.join` - a standalone ORM-level join function,
    used internally by :meth:`_query.Query.join`, which in previous
    SQLAlchemy versions was the primary ORM-level joining interface.

r   Ffrom_joinpointisouterfullz~The ``aliased`` and ``from_joinpoint`` keyword arguments to Query.join() are deprecated and will be removed in SQLAlchemy 2.0.zunknown arguments: %sz, Nr   r   zIQuery.join() will no longer accept tuples as arguments in SQLAlchemy 2.0.c              3   &   #    U  H  o4v   M	     g 7frA   r5   rH  _ss     r<   rJ  Query.join.<locals>.<genexpr>S	  s     %>geg   c              3   &   #    U  H  o4v   M	     g 7frA   r5   r  s     r<   rJ  r  _	  s     6gegr  r   r  c           
   3     >#    U  H  u  p[         R                  " [        R                  US    STS9[	        U5      S:X  a'  [         R                  " [        R
                  US   SS9OSSTTUS :  a  SOTTTR                  S.4v   M     g7f)r   T)legacyrJ   r   r   r  N)r  r   r  r  r  )r   rM   r   JoinTargetRoler]   OnClauseRoler  )rH  irm  r   r  r  r  r:   s      r<   rJ  r  w	  s      
0 --   ((G*.	 t9>	 $$U%7%7aN
 &&./!ed *.*B*B. -s   B	BzPassing a chain of multiple join conditions to Query.join() is deprecated and will be removed in SQLAlchemy 2.0. Please use individual join() calls per relationship.r  )r   r   warn_deprecated_20	TypeErrorjoinsortedr  r  rV   ri   r   
Selectabletyper   typesFunctionTyper   ColumnElementstrr   PropComparatorr  rr  r  r]   ClauseElementr  r  	enumerater   r   )r:   targetpropsr  onclauser  _props_singlerm  joins_to_addr   r  r  r  s   `         @@@@r<   r  
Query.join  s,   T	 JJy%(JJ'/JJy%(JJvu%	2
.$ n##% '$))F6N*CC 
 '+D$'+D$ $Qxqrf $$H(*:fe3L3Li[F)) &&	  **--&&	  ()F FG	E)dE**++7 %>g%>> G "$q'C1J1J+KLL $Qa1MM$'NN4(# *$ 6g66 '+'D'D'FD$## # #D t9> G
 "$q':+C+CDD	 ++Q-t/G/GH
 a 
 #  "  
 
0 %V,1
 
6 |q ##G 	  L0 /6ks   ;A-M#c                 8    SUS'   U R                   " U/UQ70 UD6$ )zCreate 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.

Tr  )r  )r:   r*  r+  r  s       r<   	outerjoinQuery.outerjoin	  s'     !yyy2%2622r?   c                      SU l         SU l        g)a#  Return 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)r  r  r   s    r<   reset_joinpointQuery.reset_joinpoint	  s     $( #' r?   c                 (    U R                  US5        g)a`  Set 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)ro   r:   from_objs     r<   select_fromQuery.select_from	  s    ^ 	h.r?   z%:meth:`_orm.Query.select_entity_from`z.Use the :func:`_orm.aliased` construct insteadc                 X    U R                  U/S5        U =R                  SS0-  sl        g)aD  Set the FROM clause of this :class:`_query.Query` to a
core selectable, applying it as a replacement FROM clause
for corresponding mapped entities.

The :meth:`_query.Query.select_entity_from`
method supplies an alternative
approach to the use case of applying an :func:`.aliased` construct
explicitly throughout a query.  Instead of referring to the
:func:`.aliased` construct explicitly,
:meth:`_query.Query.select_entity_from` automatically *adapts* all
occurrences of the entity to the target selectable.

Given a case for :func:`.aliased` such as selecting ``User``
objects from a SELECT statement::

    select_stmt = select(User).where(User.id == 7)
    user_alias = aliased(User, select_stmt)

    q = session.query(user_alias).\
        filter(user_alias.name == 'ed')

Above, we apply the ``user_alias`` object explicitly throughout the
query.  When it's not feasible for ``user_alias`` to be referenced
explicitly in many places, :meth:`_query.Query.select_entity_from`
may be
used at the start of the query to adapt the existing ``User`` entity::

    q = session.query(User).\
        select_entity_from(select_stmt.subquery()).\
        filter(User.name == 'ed')

Above, the generated SQL will show that the ``User`` entity is
adapted to our statement, even in the case of the WHERE clause:

.. sourcecode:: sql

    SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name
    FROM (SELECT "user".id AS id, "user".name AS name
    FROM "user"
    WHERE "user".id = :id_1) AS anon_1
    WHERE anon_1.name = :name_1

The :meth:`_query.Query.select_entity_from` method is similar to the
:meth:`_query.Query.select_from` method,
in that it sets the FROM clause
of the query.  The difference is that it additionally applies
adaptation to the other parts of the query that refer to the
primary entity.  If above we had used :meth:`_query.Query.select_from`
instead, the SQL generated would have been:

.. sourcecode:: sql

    -- uses plain select_from(), not select_entity_from()
    SELECT "user".id AS user_id, "user".name AS user_name
    FROM "user", (SELECT "user".id AS id, "user".name AS name
    FROM "user"
    WHERE "user".id = :id_1) AS anon_1
    WHERE "user".name = :name_1

To supply textual SQL to the :meth:`_query.Query.select_entity_from`
method,
we can make use of the :func:`_expression.text` construct.  However,
the
:func:`_expression.text`
construct needs to be aligned with the columns of our
entity, which is achieved by making use of the
:meth:`_expression.TextClause.columns` method::

    text_stmt = text("select id, name from user").columns(
        User.id, User.name).subquery()
    q = session.query(User).select_entity_from(text_stmt)

:meth:`_query.Query.select_entity_from` itself accepts an
:func:`.aliased`
object, so that the special options of :func:`.aliased` such as
:paramref:`.aliased.adapt_on_names` may be used within the
scope of the :meth:`_query.Query.select_entity_from`
method's adaptation
services.  Suppose
a view ``user_view`` also returns rows from ``user``.    If
we reflect this view into a :class:`_schema.Table`, this view has no
relationship to the :class:`_schema.Table` to which we are mapped,
however
we can use name matching to select from it::

    user_view = Table('user_view', metadata,
                      autoload_with=engine)
    user_view_alias = aliased(
        User, user_view, adapt_on_names=True)
    q = session.query(User).\
        select_entity_from(user_view_alias).\
        order_by(User.name)

.. versionchanged:: 1.1.7 The :meth:`_query.Query.select_entity_from`
   method now accepts an :func:`.aliased` object as an alternative
   to a :class:`_expression.FromClause` object.

:param from_obj: a :class:`_expression.FromClause`
 object that will replace
 the FROM clause of this :class:`_query.Query`.
 It also may be an instance
 of :func:`.aliased`.



.. seealso::

    :meth:`_query.Query.select_from`

Tr  FN)ro   rh   r8  s     r<   select_entity_fromQuery.select_entity_from	  s.    l 	xj$/"7!??r?   c                     [         R                  " U UU R                  (       + =(       d    U R                  R                  (       + S9$ )N)allow_negative)orm_util_getitemr8   future)r:   items     r<   __getitem__Query.__getitem__`
  s7      #||+F4<<3F3F/F
 	
r?   c                 v    [         R                  " U R                  U R                  X5      u  U l        U l        g)a~  Computes the "slice" of the :class:`_query.Query` represented by
the given indices and returns the resulting :class:`_query.Query`.

The start and stop indices behave like the argument to Python's
built-in :func:`range` function. This method provides an
alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
query.

For example, ::

    session.query(User).order_by(User.id).slice(1, 3)

renders as

.. sourcecode:: sql

   SELECT users.id AS users_id,
          users.name AS users_name
   FROM users ORDER BY users.id
   LIMIT ? OFFSET ?
   (2, 1)

.. seealso::

   :meth:`_query.Query.limit`

   :meth:`_query.Query.offset`

N)r  _make_slicer   r   )r:   startstops      r<   sliceQuery.sliceg
  s3    B 3;2F2F 3 3U3
/D/r?   c                 :    [         R                  " U5      U l        g)zJApply a ``LIMIT`` to the query and return the newly resulting
``Query``.

N)r  _offset_or_limit_clauser   )r:   limits     r<   rO  Query.limit
  s     &==eDr?   c                 :    [         R                  " U5      U l        g)zLApply an ``OFFSET`` to the query and return the newly resulting
``Query``.

N)r  rN  r   )r:   offsets     r<   rR  Query.offset
  s     '>>vFr?   c                 x    U(       a,  SU l         U R                  [        S U 5       5      -   U l        gSU l         g)a]  Apply a ``DISTINCT`` to the query and return the newly resulting
``Query``.


.. note::

    The ORM-level :meth:`.distinct` call includes logic that will
    automatically add columns from the ORDER BY of the query to the
    columns clause of the SELECT statement, to satisfy the common need
    of the database backend that ORDER BY columns be part of the SELECT
    list when DISTINCT is used.   These columns *are not* added to the
    list of columns actually fetched by the :class:`_query.Query`,
    however,
    so would not affect results. The columns are passed through when
    using the :attr:`_query.Query.statement` accessor, however.

    .. deprecated:: 2.0  This logic is deprecated and will be removed
       in SQLAlchemy 2.0.     See :ref:`migration_20_query_distinct`
       for a description of this use case in 2.0.

:param \*expr: optional column expressions.  When present,
 the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>)``
 construct.

 .. deprecated:: 1.4 Using \*expr in other dialects is deprecated
    and will raise :class:`_exc.CompileError` in a future version.

Tc              3   l   #    U  H*  n[         R                  " [        R                  U5      v   M,     g 7frA   )r   rM   r   ByOfRole)rH  es     r<   rJ  !Query.distinct.<locals>.<genexpr>
  s'      :=A	  33TrL  N)r   r  ri   )r:   exprs     r<   r}   Query.distinct
  s>    > !DN $ 1 1E :=A: 5 !D "DNr?   c                 >    U R                  5       R                  5       $ )a  Return the results represented by this :class:`_query.Query`
as a list.

This results in an execution of the underlying SQL statement.

.. warning::  The :class:`_query.Query` object,
   when asked to return either
   a sequence or iterator that consists of full ORM-mapped entities,
   will **deduplicate entries based on primary key**.  See the FAQ for
   more details.

    .. seealso::

        :ref:`faq_query_deduplicating`
)_iterallr   s    r<   r]  	Query.all
  s      zz|!!r?   c                 V    [         R                  " [        R                  XS9nXl        g)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.Query`.

.. seealso::

    :ref:`orm_tutorial_literal_sql` - usage examples in the
    ORM tutorial

rp  N)r   rM   r   SelectStatementRoler   )r:   r   s     r<   from_statementQuery.from_statement
  s&    ( $$%%y
	 $r?   c                     U R                   b  U R                  5       R                  5       $ U R                  S5      R                  5       R                  5       $ )a  Return the first result of this ``Query`` or
None if the result doesn't contain any row.

first() applies a limit of one within the generated SQL, so that
only one primary entity row is generated on the server side
(note this may consist of multiple result rows if join-loaded
collections are present).

Calling :meth:`_query.Query.first`
results in an execution of the underlying
query.

.. seealso::

    :meth:`_query.Query.one`

    :meth:`_query.Query.one_or_none`

r   )r   r\  firstrO  r   s    r<   rd  Query.first
  sC    * ??&::<%%''::a=&&(..00r?   c                 >    U R                  5       R                  5       $ )a(  Return at most one result or raise an exception.

Returns ``None`` if the query selects
no rows.  Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
if multiple object identities are returned, or if multiple
rows are returned for a query that returns only scalar values
as opposed to full identity-mapped entities.

Calling :meth:`_query.Query.one_or_none`
results in an execution of the
underlying query.

.. versionadded:: 1.0.9

    Added :meth:`_query.Query.one_or_none`

.. seealso::

    :meth:`_query.Query.first`

    :meth:`_query.Query.one`

)r\  one_or_noner   s    r<   rg  Query.one_or_none
  s    0 zz|''))r?   c                 >    U R                  5       R                  5       $ )a  Return exactly one result or raise an exception.

Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects
no rows.  Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
if multiple object identities are returned, or if multiple
rows are returned for a query that returns only scalar values
as opposed to full identity-mapped entities.

Calling :meth:`.one` results in an execution of the underlying query.

.. seealso::

    :meth:`_query.Query.first`

    :meth:`_query.Query.one_or_none`

)r\  oner   s    r<   rj  	Query.one$  s    $ zz|!!r?   c                      U R                  5       n[        U[        R                  5      (       d  U$ US   $ ! [        R
                   a     gf = f)a  Return 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.

r   N)rj  rV   r1   Sequenceorm_excNoResultFound)r:   rets     r<   scalarQuery.scalar8  sK    (	((*Cc?#;#;<<
q6M$$ 		s   08 8 AAc              #      #    U R                  5       n U H  nUv   M	     g ! [         a    UR                  5         e f = f7frA   )r\  GeneratorExit_soft_close)r:   resultrows      r<   __iter__Query.__iter__T  sC     		  	  		s   A" A>Ac                    U R                   nU R                  5       nU R                  R                  UUSU R                  0S9nUR
                  R                  SS5      (       a  UR                  5       nUR
                  R                  SS5      (       a+  U R                  R                  (       d  UR                  5       nU$ )N_sa_orm_load_optionsr:  r  Ffiltered)
r   r   r8   executert   _attributesrz   scalarsr-  unique)r:   r   r   rv  s       r<   r\  Query._iter_  s    &&(	%%5t7H7HI & 
 !!"4e<<^^%F "":u55%%00]]_Fr?   c                     U R                  5       n U R                  (       a%  U R                  XR                  R                  5      OS n[        UR                  U5      5      $ ! [        R
                   a    S n N2f = frA   )r   r8   _get_bind_argsget_bindr_   UnboundExecutionErrorr&  compile)r:   r   binds      r<   __str__Query.__str__v  st    &&(		 << ##I||/D/DE  9$$T*++ ++ 	D	s   8A$ $A=<A=c                     U" SSU0UD6$ )Nr  r5   r5   )r:   r   r   kws       r<   r  Query._get_bind_args  s    ))b))r?   c                     [        U SS9$ )a  Return metadata about the columns which would be
returned by this :class:`_query.Query`.

Format is a list of dictionaries::

    user_alias = aliased(User, name='user2')
    q = sess.query(User, User.id, user_alias)

    # this expression:
    q.column_descriptions

    # would return:
    [
        {
            'name':'User',
            'type':User,
            'aliased':False,
            'expr':User,
            'entity': User
        },
        {
            'name':'id',
            'type':Integer(),
            'aliased':False,
            'expr':User.id,
            'entity': User
        },
        {
            'name':'user2',
            'type':User,
            'aliased':True,
            'expr':user_alias,
            'entity': user_alias
        }
    ]

.. seealso::

    This API is available using :term:`2.0 style` queries as well,
    documented at:

    * :ref:`queryguide_inspection`

    * :attr:`.Select.column_descriptions`

Tr  r	   r   s    r<   column_descriptionsQuery.column_descriptions  s    b $D66r?   c                    Uc[  [         R                  " SSS9  U R                  SS9n[        UUR                  U R
                  U R                  U R                  5      n[        R                  " X5      nUR                  R                  SS5      (       a  UR                  5       nUR                  R                  SS5      (       a  UR                  5       nU$ )zXReturn an ORM result given a :class:`_engine.CursorResult` and
:class:`.QueryContext`.

zUsing the Query.instances() method without a context is deprecated and will be disallowed in a future release.  Please make use of :meth:`_query.Query.from_statement` for linking ORM results to arbitrary select constructs.r   )versionFr   r  r}  )r   warn_deprecatedr   r   r   r   r8   rt   r   	instancesr  rz   r  r  )r:   result_proxycontextcompile_staterv  s        r<   r  Query.instances  s    
 ?  J  !//e/DM"''!!G ""<9 !!"4e<<^^%F!!*e44]]_Fr?   z:meth:`_orm.Query.merge_result`zJThe method is superseded by the :func:`_orm.merge_frozen_result` function.)r  r1  enable_warningsc                 0    [         R                  " XU5      $ )a  Merge a result into this :class:`_query.Query` object's Session.

Given an iterator returned by a :class:`_query.Query`
of the same structure
as this one, return an identical iterator of results, with all mapped
instances merged into the session using :meth:`.Session.merge`. This
is an optimized method which will merge all mapped instances,
preserving the structure of the result rows and unmapped columns with
less method overhead than that of calling :meth:`.Session.merge`
explicitly for each value.

The structure of the results is determined based on the column list of
this :class:`_query.Query` - if these do not correspond,
unchecked errors
will occur.

The 'load' argument is the same as that of :meth:`.Session.merge`.

For an example of how :meth:`_query.Query.merge_result` is used, see
the source code for the example :ref:`examples_caching`, where
:meth:`_query.Query.merge_result` is used to efficiently restore state
from a cache back into a target :class:`.Session`.

)r   merge_result)r:   iteratorloads      r<   r  Query.merge_result  s    B ##DD99r?   c                 6   U R                  S5      R                  [        R                  " S5      5      R	                  [
        5      R                  R                  S5      nU R                  5       nUb  UR                  U5      n[        R                  " U5      $ )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   r  r   literal_columnr   r-   r   with_only_columnsrZ   r:  exists)r:   innerezeros      r<   r  Query.exists  s}    J ""5)[++C01_;<Y((+	 	 ..0%%e,Ezz%  r?   c                     [         R                  R                  [         R                  " S5      5      nU R	                  U5      R                  S5      R                  5       $ )a  Return a count of rows this the SQL formed by this :class:`Query`
would return.

This generates the SQL for this Query as follows::

    SELECT count(1) AS count_1 FROM (
        SELECT <rest of query follows...>
    ) AS anon_1

The above SQL returns a single row, which is the aggregate value
of the count function; the :meth:`_query.Query.count`
method then returns
that single integer value.

.. warning::

    It is important to note that the value returned by
    count() is **not the same as the number of ORM objects that this
    Query would return from a method such as the .all() method**.
    The :class:`_query.Query` object,
    when asked to return full entities,
    will **deduplicate entries based on primary key**, meaning if the
    same primary key value would appear in the results more than once,
    only one object of that primary key would be present.  This does
    not apply to a query that is against individual columns.

    .. seealso::

        :ref:`faq_query_deduplicating`

        :ref:`orm_tutorial_query_returning`

For fine grained control over specific columns to count, to skip the
usage of a subquery or otherwise control of the FROM clause, or to use
other aggregate functions, use :attr:`~sqlalchemy.sql.expression.func`
expressions in conjunction with :meth:`~.Session.query`, i.e.::

    from sqlalchemy import func

    # count User records, without
    # using a subquery.
    session.query(func.count(User.id))

    # return count of user "id" grouped
    # by "name"
    session.query(func.count(User.id)).\
            group_by(User.name)

    from sqlalchemy import distinct

    # count distinct "name" values
    session.query(func.count(distinct(User.name)))

*F)r   funcr.  r  ry  r   rq  )r:   cols     r<   r.  Query.count0  sE    n hhnnS//45s#55e<CCEEr?   c                    [        U 5      nU R                  R                  (       aE  U R                  R                   H+  nU" UR                  U5      nUb  XBl        UR                  n M-     [        R
                  " U R                  6 nU R                  Ul        U R                  R                  UU R                  SU0S9nXbl        U R                  R                  R                  U5        UR                  5         UR                  $ )aP  Perform a DELETE with an arbitrary WHERE clause.

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::

    See the section :ref:`orm_expression_update_delete` for important
    caveats and warnings, including limitations when using bulk UPDATE
    and DELETE with mapper inheritance configurations.

:param synchronize_session: chooses the strategy to update the
 attributes on objects in the session.   See the section
 :ref:`orm_expression_update_delete` for a discussion of these
 strategies.

:return: the count of rows matched as returned by the database's
  "row count" feature.

.. seealso::

    :ref:`orm_expression_update_delete`

synchronize_sessionr|  )
BulkDeleter   before_compile_deletequeryr   deleterO   r   r8   r~  r   rv  after_bulk_deletecloserowcount)r:   r  bulk_delr   r   delete_rv  s          r<   r  Query.deletej  s    B d#==..mm99x~~x8	(%.N~~ : **d//0"&"6"6%%LL46IJ & 

 !//9r?   c                    U=(       d    0 n[        XU5      nU R                  R                  (       aG  U R                  R                   H!  nU" UR                  U5      nUc  M  Xdl        M#     UR                  n [        R
                  " U R                  6 nUR                  SS5      nU(       a  UR                  " U6 nOUR                  U5      nU(       a  UR                  " S0 UD6nU R                  Ul        U R                  R                  UU R                  SU0S9n	Xl        U R                  R                  R!                  U5        U	R#                  5         U	R$                  $ )a  Perform an UPDATE with an arbitrary WHERE clause.

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::

    See the section :ref:`orm_expression_update_delete` for important
    caveats and warnings, including limitations when using arbitrary
    UPDATE and DELETE with mapper inheritance configurations.

: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 <tutorial_parameter_ordered_updates>` 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.

:param synchronize_session: chooses the strategy to update the
 attributes on objects in the session.   See the section
 :ref:`orm_expression_update_delete` for a discussion of these
 strategies.

:param update_args: Optional dictionary, if present will be passed
 to the underlying :func:`_expression.update`
 construct as the ``**kw`` for
 the object.  May be used to pass dialect-specific arguments such
 as ``mysql_limit``, as well as other special arguments such as
 :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`.

:return: the count of rows matched as returned by the database's
 "row count" feature.


.. seealso::

    :ref:`orm_expression_update_delete`


preserve_parameter_orderFr  r|  r5   )
BulkUpdater   before_compile_updater  r   r   rO   r   ordered_valuesrD   with_dialect_optionsr   r8   r~  r   rv  after_bulk_updater  r  )
r:   rD   r  update_argsbulk_udr   r   updpporv  s
             r<   r   Query.update  s*   f "'RT;7==..mm99w}}g6	($-M : ==Djj$++,oo8%@$$f-C**V$C**9[9C"22%%LL46IJ & 

  //8r?   c                     U R                   " SSU0UD6nXR                  R                  :X  d   e[        R                  " US5      nUR                  US5      $ )aj  Create an out-of-compiler ORMCompileState object.

The ORMCompileState object is normally created directly as a result
of the SQLCompiler.process() method being handed a Select()
or FromStatement() object that uses the "orm" plugin.   This method
provides a means of creating this ORMCompileState object directly
without using the compiler.

This method is used only for deprecated cases, which include
the .from_self() method for a Query that has multiple levels
of .from_self() in use, as well as the instances() method.  It is
also used within the test suite to generate ORMCompileState objects
for test purposes.

r   r   Nr5   )r   rh   r   r   _get_plugin_class_for_plugincreate_for_statement)r:   r   r  r   compile_state_clss        r<   r   Query._compile_state  sa    " !!DDD 5 5 D DDDD ,HH%
 !55dDAAr?   c                     U R                  US9n[        UUR                  U R                  U R                  U R
                  5      nU$ )Nr   )r   r   r   r   r8   rt   )r:   r   r  r  s       r<   _compile_contextQuery._compile_context  sI    ++-+H##LLLL
 r?   )r  r
  rM  rh   rN  r   r  r   r   r;  rj   r   r   r  r   r   r   r   r   rC   rO   r   r   r8   rA   )TT)NNNNN)T)FT)NFF)NN)FFNFF)evaluate)r  N)F)re  
__module____qualname____firstlineno____doc__r   r  r   r   r   r   r   r  r;  rN  rM  rj   _setup_joinsr   r   r   r  r   default_compile_optionsrh   r   default_load_optionsrt   r   
EMPTY_DICTr   r  r   r  r   rB   rC   r=   rE   r9   rZ   rb   ro   r$   rv   r   r   r   r~   r   r   r   ri  r   r   r   r   r   r   r   r   r   
deprecatedr   r   r   r   r  r  r   r   deprecated_20r   apply_labelsr  r   r  r  r$  r   r   r/  rz   r3  rA  r"  rQ  rV  r   r\  preload_moduler   rs  rv  r{  ry  r  r  rD   _valuesr  r  r  r  r9  r  r  r:  r8  r   r  rg  memoized_propertyr  r  r|   r  r  r  r   r  r  r  r  r  r  r  r2  r5  r:  r=  rE  rK  rO  rR  r}   r]  ra  rd  rg  rj  rq  rx  r\  r  r  r  r  r  r  r.  r  r   r   r  __static_attributes__r5   r?   r<   r2   r2   L   sR   . OMNILOJOIL)L "&>>44D8 L ooG J
 ))+%>	
(A# : :

L&	=+
 
 
 <  ) )V".d 	$"L9
v	C 
__	0&&I 	) 	)
 = = 
 
2 ? ?" % % 
L
D
D L! !!F ( (* 

 

 	9 	9 ,-	-H
 ?C(
	 . (
T 3 30 
 M
RB
RBh
 3 3  3 3  : 	5 	5 : : ; ; 
(L
 
786P 96Pp 
 
   2 
(n*n*` > > E E: 
__	I G	__	: % %6 
 
  
__	G(( # #8&	' +H +HZ  =
 =
~ 2 2&' (*:;%1 < %1N 
 ($T%%N (*:;.0 < .0` (*:;'0 < '0R (*:;
 < 
.N%2N66:470 (*:;r7 < r7h3 ()( * ( ,--/ . -/^ 
/D ,-q@ . 	q@f
 ()!
 * !
F ()E * E ()G * G ()#" * #"J"$ ,-$ . $.14*4"(8	.,* 07 07d D 
)5::8/!b8Ft5nQfB<
r?   r2   c                   (  ^  \ rS rSrSrSr\R                  r\R                  r
SrS\R                  4S\R                  4/\R                   -   r\S\R$                  4/-   rS rS	 rS
 r\S 5       rS rS rU 4S jr\S 5       r\S 5       rSrU =r$ )r   i  z`Core construct that represents a load of ORM objects from a finished
select or text construct.

orm_from_statementNrO   rY   rh   c           
          [         R                  " U5       Vs/ s H(  n[        R                  " [        R
                  UU SS9PM*     snU l        X l        g s  snf rH   )r   rL   r   rM   r   rN   rO   rY   )r:   r;   rY   rP   s       r<   r=   FromStatement.__init__6  sZ     ||H-
 . ''&*!	 .
 
s   /Ac                     U R                   $ rA   r  r   s    r<   r  FromStatement.get_label_styleB  s       r?   c                 J    [        U R                  R                  U5      5      $ rA   )r/   rY   r   )r:   label_styles     r<   r   FromStatement.set_label_styleE  s!    &LL((5
 	
r?   c                 .    U R                   R                  $ rA   )rY   r   r   s    r<   r   FromStatement._label_styleJ  s    ||(((r?   c                     U R                   " X40 UD6nUR                  (       + nU(       a  X1l        UR                  " UR                  40 UD6$ )zprovide a fixed _compiler_dispatch method.

This is roughly similar to using the sqlalchemy.ext.compiler
``@compiles`` extension.

)_compile_state_factorystackr  processr   )r:   compilerr  r  toplevels        r<   _compiler_dispatch FromStatement._compiler_dispatchN  sJ     33DIbI~~%%2" 7 7>2>>r?   c                     U $ rA   r5   r   s    r<   _ensure_disambiguated_names)FromStatement._ensure_disambiguated_names`  s    r?   c              +      >#    [         R                  R                  S U R                   5       5       H  nUv   M	     [        [
        U ]  " S0 UD6 H  nUv   M	     g 7f)Nc              3   8   #    U  H  oR                   v   M     g 7frA   )_from_objects)rH  rY   s     r<   rJ  -FromStatement.get_children.<locals>.<genexpr>d  s      2
1Bg!!1Bs   r5   )	itertoolschainfrom_iterablerO   superr   get_children)r:   r  rm   rf  s      r<   r  FromStatement.get_childrenc  sZ     OO11 2
151B1B2
 
D J
 -;AbADJ Bs   AAc                 h    U R                   R                  (       a  U R                   R                  $ S $ rA   )rY   is_dml
_returningr   s    r<   r  FromStatement._returningk  s#    *.,,*=*=t||&&G4Gr?   c                 h    U R                   R                  (       a  U R                   R                  $ S $ rA   )rY   r  _inliner   s    r<   r  FromStatement._inlineo  s#    '+||':':t||##DDr?   )rO   rY   ) re  r  r  r  r  __visit_name__r   r  rh   r  r  r;  r0   dp_clauseelement_listdp_clauseelementr%   _executable_traverse_internals_traverse_internalsdp_has_cache_key_cache_key_traversalr=   r  r   ri  r   r  r  r  r  r  r  __classcell__rf  s   @r<   r   r     s    
 *N3KK9NNO 
*@@A	%667 	112
 /	.??@2 
!

 ) )?$ H H E Er?   r   c                   P    \ rS rSr\R
                  " SS5      S 5       rSrS rSr	g)	AliasOptionit  r   zThe :class:`.AliasOption` is not necessary for entities to be matched up to a query that is established via :meth:`.Query.from_statement` and now does nothing.c                     g)zwReturn a :class:`.MapperOption` that will indicate to the
:class:`_query.Query`
that the main table has been aliased.

Nr5   )r:   r   s     r<   r=   AliasOption.__init__u  s    r?   Fc                     g rA   r5   )r:   r  s     r<   process_compile_state!AliasOption.process_compile_state  s    r?   r5   N)
re  r  r  r  r   r  r=   inherit_cacher  r  r5   r?   r<   r  r  t  s2    	__	B Mr?   r  c                   4    \ rS rSrSrS rS r\S 5       rSr	g)BulkUDi  zjState used for the orm.Query version of update() / delete().

This object is now specific to Query only.

c                     UR                  S5      U l        U R                  5         U R                  R                  5       U l        g )NF)r   r  _validate_query_staterZ   r>  )r:   r  s     r<   r=   BulkUD.__init__  s4    ,,U3
""$jj::<r?   c           
         SSS [         R                  4SSS [         R                  4SSS[         R                  4SS	S[         R                  4S
SS[         R                  4SSS[         R                  4SSS[         R                  44 HC  u  pp4U" [        U R                  U5      U5      (       a  M*  [
        R                  " SU< S35      e   g )Nr   zlimit()r   zoffset()r   z
order_by()r5   r   z
group_by()r   z
distinct()Frj   z2join(), outerjoin(), select_from(), or from_self()r   z1Can't call Query.update() or Query.delete() when z has been called)operatoris_eqgetattrr  r_   r`   )r:   r  ra   notsetops        r<   r  BulkUD._validate_query_state  s    ix||<z4> ,HKK@ ,HKK@,x||<D	 &D	+
&DF& gdjj$/880019< )+
r?   c                 .    U R                   R                  $ rA   )r  r8   r   s    r<   r8   BulkUD.session  s    zz!!!r?   )r>  r  N)
re  r  r  r  r  r=   r  ri  r8   r  r5   r?   r<   r  r    s%    =
4 " "r?   r  c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )r  i  zBulkUD which handles UPDATEs.c                 D   > [         [        U ]  U5        X l        X0l        g rA   )r  r  r=   rD   update_kwargs)r:   r  rD   r%  rf  s       r<   r=   BulkUpdate.__init__  s    j$(/*r?   )r%  rD   )re  r  r  r  r  r=   r  r
  r  s   @r<   r  r    s    '+ +r?   r  c                       \ rS rSrSrSrg)r  i  zBulkUD which handles DELETEs.r5   N)re  r  r  r  r  r  r5   r?   r<   r  r    s    'r?   r  )Fr  r  r  r#   r   rn  r   r   r   rA  baser   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!   sql.annotationr"   sql.baser#   r$   r%   sql.selectabler&   r'   r(   r)   r*   r+   r,   r-   r.   r/   sql.visitorsr0   r1   __all___self_inspectsclass_loggerr2   r   LoaderOptionr  objectr  r  r  r5   r?   r<   <module>r3     s7           ) 9 2 + $ 1 ! ,     "            "  5 , " ! 4 0 ) + % ( ( ; ' 4 , "
. N3N3  N3bfRENJ
 REj*)) (("V ("V+ +( (r?   