????
Your IP : 18.217.62.185
�
c�3��L{���dZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm
Z
dd
lmZddlm
Z
ddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlmZddl!m"Z"ddl!mZ#ddl!m$Z$dd l%m&Z&dd!l'm(Z(dd"l)m*Z*gd#�Z+ej,Z-ej.e j/Gd$�d%e0������Z1Gd&�d'e*��Z2Gd(�d)e0��Z3Gd*�d+e3��Z4ej.Gd,�d-e����Z5Gd.�d/e3��Z6Gd0�d1e3��Z7Gd2�d3e0��Z8Gd4�d5ej9��Z:d6S)7aThe Query class and support.
Defines the :class:`_query.Query` class, the central
construct used by the ORM to construct database queries.
The :class:`_query.Query` class should not be confused with the
:class:`_expression.Select` class, which defines database
SELECT operations at the SQL (non-ORM) level. ``Query`` differs from
``Select`` in that it returns ORM-mapped objects and interacts with an
ORM session, whereas the ``Select`` construct interacts directly with the
database to return iterable result sets.
�)�chain�)�
attributes)�exc)�
interfaces)�loading)�persistence)�
properties��_entity_descriptor)�_generative)�_is_aliased_class)�_is_mapped_class��_orm_columns)�InspectionAttr)�PathRegistry)�_entity_corresponds_to)�aliased)�AliasedClass)�join)�
object_mapper)�
ORMAdapter)�with_parent�)�inspect)�
inspection)�log)�sql)�util)�
expression)�visitors)�ColumnCollection)�_interpret_as_from)�ForUpdateArg)�Query�QueryContextrc�
�eZdZdZdZdZdZdZdZdZ dZ
dZdZdZ
dZdZdZdZdZdZe��ZdZdZdZdZdZdZdZdZdZdZiZ dZ!dZ"e#j$��xZ%Z&e#j$��Z'e#j$��Z(e#j$��Z)dZ*dZ+dZ,dZ-dZ.e/Z0dZ1dZ2dZ3 d�d�Z4d�d�Z5d�Z6d �Z7d
�Z8d�Z9d�Z:d
�Z;e<��d���Z=e<��d���Z>d�Z?d�Z@d�ZAd�ZBeCd���ZDd�ZEd�ZFd�ZGd�d�ZHd�ZId�ZJd�ZKd�d�ZLd�d�ZMd�ZNd�ZOd �ZP d�d!�ZQd"�ZReCd#���ZSd�d$�ZTd�d%�ZUd&�ZVd'�ZWeCd(���ZXd)�ZYe<��d*���ZZeCd+���Z[e<��d,���Z\d-�Z]e<��d.���Z^e<��d/���Z_eCd0���Z`e<��d1���Zae<eN�� d�d2���Zbe<��d3���Zcd4�Zddeejfdfd5�Zgd�d6�Zhe<��d7���Zie<��d8���Zje<��d9���Zke<��d:���Zld�d;�Zme<��d�d<���Zne<��d=���Zod>�Zpe<��d?���Zqe<��d@���ZrdA�ZsesZtdB�Zue<��dC���Zve<��dD���Zwe#jxdEdFd��dG���ZydH�ZzdI�Z{e<��dJ���Z|dK�Z}e<��d�dM���Z~d�dN�ZdO�Z�e<��dP���Z�e<��e#j�dQdR��dS�����Z�e<�� d�dT���Z�e<��dU���Z�e<eOeP��dV���Z�dW�Z�e<eOeP��dX���Z�e<eOeP��dY���Z�e<eOeP��dZ���Z�d[�Z�d\�Z�d]�Z�d^�Z�d_�Z�d`�Z�da�Z�db�Z�dc�Z�dd�Z�e<eOeP��de���Z�df�Z�dg�Z�dh�Z�di�Z�dj�Z�e<eO��dk���Z�e<eN��dl���Z�e<eN��dm���Z�dn�Z�e<eO��do���Z�e<eO��dp���Z�e<eO��dq���Z�e<eO��dr���Z�e<��ds���Z�e<��dt���Z�du�Z�e<eN��dv���Z�dw�Z�dx�Z�dy�Z�dz�Z�d{�Z�d|�Z�d}�Z�d~�Z�d�Z�d��Z�eCd����Z�d�d��Z�d�d��Z�eCd����Z�eCd����Z�d��Z�d��Z�d�d��Z�d�d��Z�d�d��Z�d��Z�d��Z�d��Z�dS)�r&axORM-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 walkthrough of :class:`_query.Query` usage, see the
:ref:`ormtutorial_toplevel`.
FTN�c�L�||_i|_|�|��dS)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�_polymorphic_adapters�
_set_entities)�self�entitiesr+s �g/builddir/build/BUILD/cloudlinux-venv-1.0.7/venv/lib64/python3.11/site-packages/sqlalchemy/orm/query.py�__init__zQuery.__init__�s-��8���%'��"����8�$�$�$�$�$�c���|�t}g|_d|_d|_|dkr?t j|��D]}|||���|�|j��dSdS)NFr))�_QueryEntity� _entities�_primary_entity�_has_mapper_entitiesr �to_list�_set_entity_selectables)r.r/�entity_wrapper�ents r0r-zQuery._set_entities�s����!�)�N����#���$)��!�"�r�>�>��|�H�-�-�
*�
*����t�S�)�)�)�)��(�(���8�8�8�8�8� �>r2c ��|j���x|_}|D]�}|jD]�}||vr�t|��}|js_|jjrS|jj|jvr=|� |jtj|j|jj
����d}n|jr|j}nd}||f||<|j||�����dS�N)�_mapper_adapter_map�copyr/r�is_aliased_class�mapper�with_polymorphic�persist_selectabler,�"_mapper_loads_polymorphically_with�sql_util�
ColumnAdapter�
selectable�_equivalent_columns�_adapter�setup_entity)r.r/�dr;�entity�ext_info�aliased_adapters r0r9zQuery._set_entity_selectables�s��'+�'?�'D�'D�'F�'F�F�� �1�� -� -�C��,�
-�
-����?�?�&�v���H�$�5�/�$�O�<�/�
%�O�>�#'�#=�>�>�!�C�C� (�� (� 6�$,�$7�$,�O�$G�!"�!"����+/���!�2�/�*2�*;���*.��!)�?� ;�A�f�I� �� �!�F�)�,�,�,�3
-� -� -r2c��|jp|gD]2}||j|<|���D]}||j|j<��3dSr=)�_with_polymorphic_mappersr,�iterate_to_root�local_table)r.rA�adapter�m2�ms r0rDz(Query._mapper_loads_polymorphically_withsk���2�>�v�h� D� D�B�-4�D�&�r�*��'�'�)�)�
D�
D��<C��*�1�=�9�9�
D� D� Dr2c�D�g}d}|D]�}t|��}t|d��rM|js|jr?||_|r|jstjd���|�|j���n|j stjd���t|tj��r|�
��}|r|}|�|����t|��|_|rmt!|j��dkrUt|tj��r;|���}t'j|jd|��|_dS|r=t!|j��dkr't|d��r|jr|j|_dSdSdSdSdS)NrAzPA selectable (FromClause) instance is expected when the base alias is being set.zJargument is not a mapped class, mapper, aliased(), or FromClause instance.rr)r�hasattr� is_mapperr@�_select_from_entity�sa_exc�
ArgumentError�appendrG�
is_selectable�
isinstancer!�
SelectBase�alias�tuple� _from_obj�len�Alias�_Query__all_equivsrErF�_from_obj_aliasrI)r.�obj�set_base_alias�fa�select_from_alias�from_obj�info�equivss r0�_set_select_fromzQuery._set_select_froms���
�� ��� $� $�H��8�$�$�D��t�X�&�&�
$���
$�"&�"7�
$�,0��(�!��$�*?�� �.�E����� � �$�/�*�*�*�*��'�
$��*�9����
�h�
�(=�>�>�0�'�~�~�/�/�H�!�1�(0�%�� � �(�#�#�#�#��r�����
� 1��D�N�#�#�q�(�(��,�j�.>�?�?�)��&�&�(�(�F�#+�#9���q�!�6�$�$�D� � � �
� 1��D�N�#�#�q�(�(���h�'�'�)��%�)�$(�=�D� � � �
1� 1�(�(�(�(�(�(r2c��|jD]T}|j�|d��|���D]"}|j�|jd���#�UdSr=)rPr,�poprQrR)r.rArTrUs r0�_reset_polymorphic_adapterz Query._reset_polymorphic_adapter7s|���2� D� D�B��&�*�*�2�t�4�4�4��'�'�)�)�
D�
D���*�.�.�q�}�d�C�C�C�C�
D� D� Dr2c�h�d|jvr?|jd}|j�|d��}|r|�|��St |t
j��r|}nt|d��r|j}ndS|j�|d��}|r|�|��SdS)N�parententity�table) �_annotationsr,�get�adapt_clauser^r!�
FromClauserWrt)r.�element�searchr`s r0�_adapt_polymorphic_elementz Query._adapt_polymorphic_element=s����W�1�1�1��)�.�9�F��.�2�2�6�4�@�@�E��
3��)�)�'�2�2�2��g�z�4�5�5� ��F�F�
�W�g�
&�
&� ��]�F�F��4��*�.�.�v�t�<�<��� /��%�%�g�.�.�.� /� /r2c� ���fd�|D��S)Nc�b��g|]+}��tj|��dd����,S�T)�
_adapt_clauser!�_literal_as_label_reference)�.0�or.s �r0�
<listcomp>z)Query._adapt_col_list.<locals>.<listcomp>PsM���
�
�
��
����6�q�9�9�4��
�
�
�
�
r2r))r.�colss` r0�_adapt_col_listzQuery._adapt_col_listOs0���
�
�
�
��
�
�
�
r2c��||_dSr=)�lazy_loaded_from)r.�states r0�_set_lazyload_fromzQuery._set_lazyload_fromWs�� %����r2c��d|_dS�NF)�_orm_only_adapt�r.s r0�_adapt_all_clauseszQuery._adapt_all_clauses[s��$����r2c�^��g�|jsd}|r-|jr&|jD]}��||jf���|jr*��|jr|nd|jjf��|jr��||jf���s|S�fd�}tj |i|��S)z\Adapt incoming clauses to transformations which
have been applied within this query.Fc�f��d|jvpd|jv}�D]\}}|r|r||��}|�|cS�dS)N�
_orm_adaptrs�ru)�elem�is_orm_adapt� _orm_onlyrS�e�adapterss �r0�replacez$Query._adapt_clause.<locals>.replacesn����� 1�1�7�!�T�%6�6�
�'/�
!�
!�"� �7� �!�L�!����
�
�A��}� �����
!�
!r2)
r��_filter_aliasesr\r�rf�_orm_only_from_obj_aliasr,r{r"�replacement_traverse)r.�clause� as_filter�orm_onlyrir�r�s @r0rzQuery._adapt_clause_s������#� ��H�� 8��-� 8��*�
8�
8������2�:� 6�7�7�7�7���
�
�O�O� $� =�H�H�H�5��(�0��
�
�
��%� I��O�O�X�t�'F�G�H�H�H�� ��M� !� !� !� !� !��,�V�R��A�A�Ar2c��|jdS)zReturn the first QueryEntity.r�r5r�s r0�_query_entity_zerozQuery._query_entity_zero�s���~�a� � r2c�&�|jdjS)z8Return the Mapper associated with the first QueryEntity.r)r5rAr�s r0�_mapper_zerozQuery._mapper_zero�s���~�a� �'�'r2c�P�|j�|jn|���jS)z�Return the 'entity' (mapper or AliasedClass) associated
with the first QueryEntity, or alternatively the 'select from'
entity if specified.)rYr��entity_zeror�s r0�_entity_zerozQuery._entity_zero�s/���'�3�
�$�$��(�(�*�*�6�
r2c#�PK�|jD]}t|t��r|V��dSr=)r5r^�
_MapperEntity)r.r;s r0�_mapper_entitieszQuery._mapper_entities�s=�����>� � �C��#�}�-�-�
�� � � �� � r2c�\�|j�d|�����S)N�_joinpoint_entity)�
_joinpointrvr�r�s r0�_joinpoint_zerozQuery._joinpoint_zero�s'����"�"�#6��8I�8I�8K�8K�L�L�Lr2c�l�|���}|�t|��}|js|jSdSr=)r�r�is_clause_elementrA)r.�ezero�insps r0�_bind_mapperzQuery._bind_mapper�s<���!�!�#�#�����5�>�>�D��)�
#��{�"��tr2c�j�|j|jgkrtjd|z���|jjS)Nz4%s() can only be used against a single mapped class.)r5r6rZ�InvalidRequestErrorr�)r.�methnames r0�_only_full_mapper_zerozQuery._only_full_mapper_zero�sE���>�d�2�3�3�3��,�)�+3�4���
��#�/�/r2c��t|j��dkrtj|pd���|���S)Nrz8This operation requires a Query against a single mapper.)rcr5rZr�r�)r.� rationales r0�_only_entity_zerozQuery._only_entity_zero�sM���t�~����"�"��,��+�+���
�
� � �"�"�"r2c�\�i}|jD]!}|�|jj���"|Sr=)r��updaterArH)r.rmr;s r0�__all_equivszQuery.__all_equivs�s8�����(� :� :�C��M�M�#�*�8�9�9�9�9��
r2c�2�|�ddd���S�NrvF)�order_by�distinct)�_no_criterion_conditionr�s r0�_get_conditionzQuery._get_condition�s&���+�+��E�E�,�
�
�
r2c�6�|�ddd���dSr�)�_no_criterion_assertionr�s r0�_get_existing_conditionzQuery._get_existing_condition�s#���$�$�U�U�U�$�K�K�K�K�Kr2c���|jsdS|j�5|j�.|js'|j� |j�|js|r|js |r|jrtj
d|z���dSdS�Nz<Query.%s() being called on a Query with existing criterion. )�_enable_assertions�
_criterion�
_statementrb�_limit�_offset� _group_by� _order_by� _distinctrZr��r.�methr�r�s r0r�zQuery._no_criterion_assertion�s����&� ��F��O�'���*��~�+��{�&��|�'��~�(��(�!�^�(��(�"�^�(�
�,�2�48�9���
�(�'�'�'r2c��|�|||��d|_dx|_|_dx|_x|_|_dS)Nr)F)r�rbr�r�r�r�r�r�s r0r�zQuery._no_criterion_condition�sH���$�$�T�8�X�>�>�>����,0�0���$�/�;@�@���@���$�.�.�.r2c�~�|jsdS|jrtjd|z���|�|��dSr�)r�r�rZr�r��r.r�s r0�_no_clauseelement_conditionz!Query._no_clauseelement_condition�sZ���&� ��F��>� ��,�2�48�9���
�
�$�$�T�*�*�*�*�*r2c�T�|jsdS|j�tjd|z���dS)Nz[Query.%s() being called on a Query with an existing full statement - can't apply criterion.)r�r�rZr�r�s r0�_no_statement_conditionzQuery._no_statement_condition�sF���&� ��F��?�&��,�9�� ���
�'�&r2c�j�|jsdS|j�|j�tjd|�d|�d����dS)NzQuery.z�() being called on a Query which already has LIMIT or OFFSET applied. To modify the row-limited results of a Query, call from_self() first. Otherwise, call z*() before limit() or offset() are applied.)r�r�r�rZr�r�s r0�_no_limit_offsetzQuery._no_limit_offset�sU���&� ��F��;�"�d�l�&>��,�,�
#'�$�$���� .���
�'?�&>r2c�z�|r||_|r||_|r||_|rt|��|_|r||_|Sr=)�_populate_existing�_version_check�_refresh_state�set�_only_load_props�_refresh_identity_token)r.�populate_existing�
version_check�only_load_props�
refresh_state�identity_tokens r0�_get_optionszQuery._get_optionssa��� 8�&7�D�#�� 0�"/�D��� 0�"/�D��� 9�$'��$8�$8�D�!�� :�+9�D�(��r2c�z�|j}|�|��}|j���|_|Sr=�� __class__�__new__�__dict__r?)r.�cls�qs r0�_clonezQuery._clones4���n���K�K������]�'�'�)�)��
��r2c��|�|j���j}|jr|�|j��}|S)z�The full SELECT statement represented by this Query.
The statement by default will not have disambiguating labels
applied to the construct unless with_labels(True) is called
first.
)�labels)�_compile_context�_with_labels� statement�_params�params)r.�stmts r0r�zQuery.statement%sB���$�$�D�,=�$�>�>�H���<� -��;�;�t�|�,�,�D��r2c��|�d��}|r|���}|j}|r|���}|�|���S)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�with_labelsr��reduce_columnsr`)r.r�r�r�r�s r0�subqueryzQuery.subquery5s`��.
�"�"�5�)�)��� ��
�
���A�
�K��� #�� � �"�"�A��w�w�D�w�!�!�!r2c�`�|�d��j�||���S)aFReturn the full SELECT statement represented by this
:class:`_query.Query` represented as a common table expression (CTE).
Parameters and usage are the same as those of the
:meth:`_expression.SelectBase.cte` method; see that method for
further details.
Here is the `PostgreSQL WITH
RECURSIVE example
<http://www.postgresql.org/docs/8.4/static/queries-with.html>`_.
Note that, in this example, the ``included_parts`` cte and the
``incl_alias`` alias of it are Core selectables, which
means the columns are accessed via the ``.c.`` attribute. The
``parts_alias`` object is an :func:`_orm.aliased` instance of the
``Part`` entity, so column-mapped attributes are available
directly::
from sqlalchemy.orm import aliased
class Part(Base):
__tablename__ = 'part'
part = Column(String, primary_key=True)
sub_part = Column(String, primary_key=True)
quantity = Column(Integer)
included_parts = session.query(
Part.sub_part,
Part.part,
Part.quantity).\
filter(Part.part=="our part").\
cte(name="included_parts", recursive=True)
incl_alias = aliased(included_parts, name="pr")
parts_alias = aliased(Part, name="p")
included_parts = included_parts.union_all(
session.query(
parts_alias.sub_part,
parts_alias.part,
parts_alias.quantity).\
filter(parts_alias.part==incl_alias.c.sub_part)
)
q = session.query(
included_parts.c.sub_part,
func.sum(included_parts.c.quantity).
label('total_quantity')
).\
group_by(included_parts.c.sub_part)
.. seealso::
:meth:`_expression.HasCTE.cte`
F)r�� recursive)r�r��cte)r.r�r�s r0r�z Query.cteUs8��n�%�%�e�,�,�6�:�:���;�
�
�
r2c�\�|�d��j�|��S)z�Return the full SELECT statement represented by this
:class:`_query.Query`, converted
to a scalar subquery with a label of the given name.
Analogous to :meth:`_expression.SelectBase.label`.
F)r�r��label)r.r�s r0rzQuery.label�s)���%�%�e�,�,�6�<�<�T�B�B�Br2c�Z�|�d��j���S)z�Return the full SELECT statement represented by this
:class:`_query.Query`, converted to a scalar subquery.
Analogous to :meth:`_expression.SelectBase.as_scalar`.
F)r�r�� as_scalarr�s r0rzQuery.as_scalar�s'���%�%�e�,�,�6�@�@�B�B�Br2c�*�|���S)z�Return 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 r0rGzQuery.selectable�s���&�&�(�(�(r2c�Z�|�d�����jSr�)r�r�r�r�s r0rzQuery.__clause_element__�s%���%�%�e�,�,�8�8�:�:�D�Dr2c��||_dS)z�When 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`
N)�_only_return_tuples�r.�values r0�only_return_tupleszQuery.only_return_tuples�s��$)�� � � r2c�f�|jo)t|j��dko|jdjS)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`
rr)rrcr5�supports_single_entityr�s r0�is_single_entityzQuery.is_single_entity�s;��"�(�(�
9��D�N�#�#�q�(�
9���q�!�8�
r2c��||_dS)aControl whether or not eager joins and subqueries are
rendered.
When set to False, the returned Query will not render
eager joins regardless of :func:`~sqlalchemy.orm.joinedload`,
:func:`~sqlalchemy.orm.subqueryload` options
or mapper-level ``lazy='joined'``/``lazy='subquery'``
configurations.
This is used primarily when nesting the Query's
statement into a subquery or other
selectable, or when using :meth:`_query.Query.yield_per`.
N)�_enable_eagerloadsr s r0r�zQuery.enable_eagerloads�s�� #(����r2c�0�tjd|z���)Nz�The yield_per Query option is currently not compatible with %s eager loading. Please specify lazyload('*') or query.enable_eagerloads(False) in order to proceed with query.yield_per().)rZr�)r.�messages r0�
_no_yield_perzQuery._no_yield_per�s&���(�
.�18�
8�
�
�
r2c��d|_dS)a�Apply column labels to the return value of Query.statement.
Indicates that this Query's `statement` accessor should return
a SELECT statement that applies labels to all columns in the
form <tablename>_<columnname>; this is commonly used to
disambiguate columns from multiple tables which have the same
name.
When the `Query` actually issues SQL to load rows, it always
uses column labeling.
.. note:: The :meth:`_query.Query.with_labels` method *only* applies
the output of :attr:`_query.Query.statement`, and *not* to any of
the result-row invoking systems of :class:`_query.Query` itself,
e.g. :meth:`_query.Query.first`, :meth:`_query.Query.all`, etc.
To execute
a query using :meth:`_query.Query.with_labels`, invoke the
:attr:`_query.Query.statement` using :meth:`.Session.execute`::
result = session.execute(query.with_labels().statement)
TN)r�r�s r0r�zQuery.with_labels�s��2!����r2c��||_dS)aControl whether assertions are generated.
When set to False, the returned Query will
not assert its state before certain operations,
including that LIMIT/OFFSET has not been applied
when filter() is called, no criterion exists
when get() is called, and no "from_statement()"
exists when filter()/order_by()/group_by() etc.
is called. This more permissive mode is used by
custom Query subclasses to specify criterion or
other modifiers outside of the usual usage patterns.
Care should be taken to ensure that the usage
pattern is even possible. A statement applied
by from_statement() will override any criterion
set by filter() or order_by(), for example.
N)r�r s r0�enable_assertionszQuery.enable_assertionss��(#(����r2c��|jS)z�A readonly attribute which returns the current WHERE criterion for
this Query.
This returned value is a SQL expression construct, or ``None`` if no
criterion has been established.
)r�r�s r0�whereclausezQuery.whereclause%s����r2c��||_dS)aIndicate that this query applies to objects loaded
within a certain path.
Used by deferred loaders (see strategies.py) which transfer
query options from an originating query to a newly generated
query intended for the deferred load.
N)�
_current_path)r.�paths r0�_with_current_pathzQuery._with_current_path0s��"����r2c���|jstjd���|jd���}|g|jdd�z|_|�||||���dS)a�Load columns for inheriting classes.
:meth:`_query.Query.with_polymorphic` applies transformations
to the "main" mapped class represented by this :class:`_query.Query`.
The "main" mapped class here means the :class:`_query.Query`
object's first argument is a full class, i.e.
``session.query(SomeClass)``. These transformations allow additional
tables to be present in the FROM clause so that columns for a
joined-inheritance subclass are available in the query, both for the
purposes of load-time efficiency as well as the ability to use
these columns at query time.
See the documentation section :ref:`with_polymorphic` for
details on how this method is used.
z(No primary mapper set up for this Query.rrN)rG�polymorphic_on)r6rZr�r5r��set_with_polymorphic)r.�cls_or_mappersrGrrLs r0rBzQuery.with_polymorphic<s���*�#� ��,�:���
����"�)�)�+�+�� ��D�N�1�2�2�$6�6����#�#���!�)� $�
�
�
�
�
r2c�X�||_|j�d|d���|_dS)a�Yield only ``count`` rows at a time.
The purpose of this method is when fetching very large result sets
(> 10K rows), to batch results in sub-collections and yield them
out partially, so that the Python interpreter doesn't need to declare
very large areas of memory which is both time consuming and leads
to excessive memory use. The performance from fetching hundreds of
thousands of rows can often double when a suitable yield-per setting
(e.g. approximately 1000) is used, even with DBAPIs that buffer
rows (which are most).
The :meth:`_query.Query.yield_per` method **is not compatible
subqueryload eager loading or joinedload eager loading when
using collections**. It is potentially compatible with "select in"
eager loading, **provided the database driver supports multiple,
independent cursors** (pysqlite and psycopg2 are known to work,
MySQL and SQL Server ODBC drivers do not).
Therefore in some cases, it may be helpful to disable
eager loads, either unconditionally with
:meth:`_query.Query.enable_eagerloads`::
q = sess.query(Object).yield_per(100).enable_eagerloads(False)
Or more selectively using :func:`.lazyload`; such as with
an asterisk to specify the default loader scheme::
q = sess.query(Object).yield_per(100).\
options(lazyload('*'), joinedload(Object.some_related))
.. warning::
Use this method with caution; if the same instance is
present in more than one batch of rows, end-user changes
to attributes will be overwritten.
In particular, it's usually impossible to use this setting
with eagerly loaded collections (i.e. any lazy='joined' or
'subquery') since those collections will be cleared for a
new load when encountered in a subsequent result batch.
In the case of 'subquery' loading, the full result for all
rows is fetched which generally defeats the purpose of
:meth:`~sqlalchemy.orm.query.Query.yield_per`.
Also note that while
:meth:`~sqlalchemy.orm.query.Query.yield_per` will set the
``stream_results`` execution option to True, currently
this is only understood by
:mod:`~sqlalchemy.dialects.postgresql.psycopg2`,
:mod:`~sqlalchemy.dialects.mysql.mysqldb` and
:mod:`~sqlalchemy.dialects.mysql.pymysql` dialects
which will stream results using server side cursors
instead of pre-buffer all rows for this query. Other
DBAPIs **pre-buffer all rows** before making them
available. The memory use of raw database rows is much less
than that of an ORM-mapped object, but should still be taken into
consideration when benchmarking.
.. seealso::
:meth:`_query.Query.enable_eagerloads`
T)�stream_results�max_row_bufferN)�
_yield_per�_execution_options�union)r.�counts r0� yield_perzQuery.yield_per^s8��B ���"&�"9�"?�"?�#�u�=�=�#
�#
����r2c�B�|�|tj��S)aaReturn an instance based on the given primary key identifier,
or ``None`` if not found.
E.g.::
my_user = session.query(User).get(5)
some_object = session.query(VersionedFoo).get((5, 10))
some_object = session.query(VersionedFoo).get(
{"id": 5, "version_id": 10})
:meth:`_query.Query.get` is special in that it provides direct
access to the identity map of the owning :class:`.Session`.
If the given primary key identifier is present
in the local identity map, the object is returned
directly from this collection and no SQL is emitted,
unless the object has been marked fully expired.
If not present,
a SELECT is performed in order to locate the object.
:meth:`_query.Query.get` also will perform a check if
the object is present in the identity map and
marked as expired - a SELECT
is emitted to refresh the object as well as to
ensure that the row is still present.
If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
:meth:`_query.Query.get` is only used to return a single
mapped instance, not multiple instances or
individual column constructs, and strictly
on a single primary key value. The originating
:class:`_query.Query` must be constructed in this way,
i.e. against a single mapped entity,
with no additional filtering criterion. Loading
options via :meth:`_query.Query.options` may be applied
however, and will be used if the object is not
yet locally present.
A lazy-loading, many-to-one attribute configured
by :func:`_orm.relationship`, using a simple
foreign-key-to-primary-key criterion, will also use an
operation equivalent to :meth:`_query.Query.get` in order to retrieve
the target value from the local identity map
before querying the database. See :doc:`/orm/loading_relationships`
for further details on relationship loading.
:param ident: A scalar, tuple, or dictionary representing the
primary key. For a composite (e.g. multiple column) primary key,
a tuple or dictionary should be passed.
For a single-column primary key, the scalar calling form is typically
the most expedient. If the primary key of a row is the value "5",
the call looks like::
my_object = query.get(5)
The tuple form contains primary key values typically in
the order in which they correspond to the mapped
:class:`_schema.Table`
object's primary key columns, or if the
:paramref:`_orm.Mapper.primary_key` configuration parameter were
used, in
the order used for that parameter. For example, if the primary key
of a row is represented by the integer
digits "5, 10" the call would look like::
my_object = query.get((5, 10))
The dictionary form should include as keys the mapped attribute names
corresponding to each element of the primary key. If the mapped class
has the attributes ``id``, ``version_id`` as the attributes which
store the object's primary key value, the call would look like::
my_object = query.get({"id": 5, "version_id": 10})
.. versionadded:: 1.3 the :meth:`_query.Query.get`
method now optionally
accepts a dictionary of attribute names to values in order to
indicate a primary key identifier.
:return: The object instance, or ``None``.
)� _get_implr�load_on_pk_identity)r.�idents r0rvz Query.get�s��l�~�~�e�W�%@�A�A�Ar2c�h�|�||���}tj|j|||��S)aqLocate an object in the identity map.
Given a primary key identity, constructs an identity key and then
looks in the session's identity map. If present, the object may
be run through unexpiration rules (e.g. load unloaded attributes,
check if was deleted).
For performance reasons, while the :class:`_query.Query` must be
instantiated, it may be instantiated with no entities, and the
mapper is passed::
obj = session.query()._identity_lookup(inspect(SomeClass), (1, ))
:param mapper: mapper in use
:param primary_key_identity: the primary key we are searching for, as
a tuple.
:param identity_token: identity token that should be used to create
the identity key. Used as is, however overriding subclasses can
repurpose this in order to interpret the value in a special way,
such as if None then look among multiple target tokens.
:param passive: passive load flag passed to
:func:`.loading.get_from_identity`, which impacts the behavior if
the object is found; the object may be validated and/or unexpired
if the flag allows for SQL to be emitted.
:param lazy_loaded_from: an :class:`.InstanceState` that is
specifically asking for this identity as a related identity. Used
for sharding schemes where there is a correspondence between an object
and a related object being lazy-loaded (or otherwise
relationship-loaded).
.. versionadded:: 1.2.9
:return: None if the object is not found in the identity map, *or*
if the object was unexpired and found to have been deleted.
if passive flags disallow SQL and the object is expired, returns
PASSIVE_NO_RESULT. In all other cases the instance is returned.
.. versionadded:: 1.2.7
�r�)�identity_key_from_primary_keyr�get_from_identityr+)r.rA�primary_key_identityr��passiver��keys r0�_identity_lookupzQuery._identity_lookup�s?��b�2�2� ��3�
�
���(���v�s�G�L�L�Lr2c
���t�d��r�����|�d��}t�t��}|stj�d����t���t|j��kr9tj
dd�d�|jD����z���|r� t�fd�|j
D�����nd#t$rW}tjtj
d d�d
�|j
D����z��|���Yd}~nd}~wwxYw|jsj|jsc|j�\|�|�|���}|�2|���t+|j|j��sdS|S|t0jurdS||���S)
N�__composite_values__rvr=)�defaultzmIncorrect number of values in identifier to formulate primary key for query.get(); primary key columns are %s�,c3� K�|] }d|zV��
dS�z'%s'Nr)�r��cs r0� <genexpr>z"Query._get_impl.<locals>.<genexpr>Cs&����B�B�!�6�A�:�B�B�B�B�B�Br2c3�2�K�|]}�|jV��dSr=�r3)r��propr1s �r0r=z"Query._get_impl.<locals>.<genexpr>Hs>�����,�,��)���2�,�,�,�,�,�,r2ztIncorrect names of values in identifier to formulate primary key for query.get(); primary key attribute names are %sc3�*K�|]}d|jzV��dSr:r?)r�r@s r0r=z"Query._get_impl.<locals>.<genexpr>Ss=����#�#� $�#�T�X�-�#�#�#�#�#�#r2��replace_contextr.)rWr6r�r^�dictr r8rc�primary_keyrZr�r�list�_identity_key_props�KeyError�raise_r��always_refresh�_for_update_argr4r��
issubclassr��class_r�PASSIVE_CLASS_MISMATCH)r.r1�
db_load_fnr�rA�is_dict�err�instances ` r0r*zQuery._get_impl2sm����'�)?�@�@� O�#7�#L�#L�#N�#N� ��,�,�U�3�3���1�4�8�8��� �#'�<�$�g�$�$�$� ��#�$�$��F�,>�(?�(?�?�?��,�J��(�(�B�B�v�/A�B�B�B�B�B�C���
�� �
�'+�,�,�,�,� &� :�,�,�,�(�(�$�$��
�
�
�
����.�'��(�(�#�#�(.�(B�#�#�#������%(��������������
�����'� ��)� ��$�,��,�,��,�^�-���H��#��,�,�.�.�.�"�(�"4�f�m�D�D� ��4����Z�>�>�>��t��z�$� 4�5�5�5s� C*�*
E�4A
E�Ec���|D]c}|�!|j�dg��|_�%|j�tjt |������|_�ddS)a@Return a :class:`.Query` construct which will correlate the given
FROM clauses to that of an enclosing :class:`.Query` or
:func:`~.expression.select`.
The method here accepts mapped classes, :func:`.aliased` constructs,
and :func:`.mapper` constructs as arguments, which are resolved into
expression constructs, in addition to appropriate expression
constructs.
The correlation arguments are ultimately passed to
:meth:`_expression.Select.correlate`
after coercion to expression constructs.
The correlation arguments take effect in such cases
as when :meth:`_query.Query.from_self` is used, or when
a subquery as returned by :meth:`_query.Query.subquery` is
embedded in another :func:`_expression.select` construct.
N)�
_correlater&rE�surface_selectablesr$)r.�args�ss r0� correlatezQuery.correlateqso��,� � �A��y�"&�/�"7�"7���"?�"?����"&�/�"7�"7��0�1C�A�1F�1F�G�G�#�#���� � r2c��||_dS)a%Return a Query with a specific 'autoflush' setting.
Note that a Session with autoflush=False will
not autoflush, even if this flag is set to True at the
Query level. Therefore this flag is usually used only
to disable autoflush for a specific Query.
N)�
_autoflush)r.�settings r0� autoflushzQuery.autoflush�s��"����r2c��d|_dS)ajReturn a :class:`_query.Query`
that will expire and refresh all instances
as they are loaded, or reused from the current :class:`.Session`.
:meth:`.populate_existing` does not improve behavior when
the ORM is used normally - the :class:`.Session` object's usual
behavior of maintaining a transaction and expiring all attributes
after rollback or commit handles object state automatically.
This method is not intended for general use.
.. seealso::
:ref:`session_expire` - in the ORM :class:`_orm.Session`
documentation
TN)r�r�s r0r�zQuery.populate_existing�s��$#'����r2c��||_dS)z�Set the 'invoke all eagers' flag which causes joined- and
subquery loaders to traverse into already-loaded related objects
and collections.
Default is that of :attr:`_query.Query._invoke_all_eagers`.
N)�_invoke_all_eagersr s r0�_with_invoke_all_eagerszQuery._with_invoke_all_eagers�s��#(����r2c��|rt|��}n|���}|�yt|��}|jD].}t |t
j��r|j|jur|}n5�/tj d|jj
j�d|jj�d����|�
t|||j����S)a4Add filtering criterion that relates the given instance
to a child object or collection, using its attribute state
as well as an established :func:`_orm.relationship()`
configuration.
The method uses the :func:`.with_parent` function to generate
the clause, the result of which is passed to
:meth:`_query.Query.filter`.
Parameters are the same as :func:`.with_parent`, with the exception
that the given property can be None, in which case a search is
performed against this :class:`_query.Query` object's target mapper.
:param instance:
An instance which has some :func:`_orm.relationship`.
:param property:
String property name, or class-bound attribute, which indicates
what relationship from the instance should be used to reconcile the
parent/child relationship.
:param from_entity:
Entity in which to consider as the left side. This defaults to the
"zero" entity of the :class:`_query.Query` itself.
Nz>Could not locate a property which relates instances of class 'z' to instances of class '�')rr�r�iterate_propertiesr^r
�RelationshipPropertyrArZr�rM�__name__r��filterrrL)r.rR�property�from_entityr�rAr@s r0rzQuery.with_parent�s���8� .�!�+�.�.�K�K��+�+�-�-�K���"�8�,�,�F��1�
�
���t�Z�%D�E�E����{�'9�9�9�#�H��E���0�0�$�*�1�:�:�:� �*�3�3�3� �����{�{�;�x��;�;M�N�N�O�O�Or2c��|�t||��}t|j��|_t||��}|�|g��dS)zIadd a mapped entity to the list of result columns
to be returned.N)rrFr5r�r9)r.rLr`rUs r0�
add_entityzQuery.add_entity�sU��
���V�U�+�+�F��d�n�-�-����$��'�'���$�$�a�S�)�)�)�)�)r2c��||_dS)aReturn a :class:`_query.Query` that will use the given
:class:`.Session`.
While the :class:`_query.Query`
object is normally instantiated using the
:meth:`.Session.query` method, it is legal to build the
:class:`_query.Query`
directly without necessarily using a :class:`.Session`. Such a
:class:`_query.Query` object, or any :class:`_query.Query`
already associated
with a different :class:`.Session`, can produce a new
:class:`_query.Query`
object associated with a target session using this method::
from sqlalchemy.orm import Query
query = Query([MyClass]).filter(MyClass.id == 5)
result = query.with_session(my_session).one()
N)r+)r.r+s r0�with_sessionzQuery.with_session�s��0����r2c��|����d��j�d��}|�|��}d|_|���|_|r|�|��|S)aSreturn a Query that selects from this Query's
SELECT statement.
:meth:`_query.Query.from_self` essentially turns the SELECT statement
into a SELECT of itself. Given a query such as::
q = session.query(User).filter(User.name.like('e%'))
Given the :meth:`_query.Query.from_self` version::
q = session.query(User).filter(User.name.like('e%')).from_self()
This query renders as:
.. sourcecode:: sql
SELECT anon_1.user_id AS anon_1_user_id,
anon_1.user_name AS anon_1_user_name
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1) AS anon_1
There are lots of cases where :meth:`_query.Query.from_self`
may be useful.
A simple one is where above, we may want to apply a row LIMIT to
the set of user objects we query against, and then apply additional
joins against that row-limited set::
q = session.query(User).filter(User.name.like('e%')).\
limit(5).from_self().\
join(User.addresses).filter(Address.email.like('q%'))
The above query joins to the ``Address`` entity but only against the
first five results of the ``User`` query:
.. sourcecode:: sql
SELECT anon_1.user_id AS anon_1_user_id,
anon_1.user_name AS anon_1_user_name
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1
LIMIT :param_1) AS anon_1
JOIN address ON anon_1.user_id = address.user_id
WHERE address.email LIKE :email_1
**Automatic Aliasing**
Another key behavior of :meth:`_query.Query.from_self`
is that it applies
**automatic aliasing** to the entities inside the subquery, when
they are referenced on the outside. Above, if we continue to
refer to the ``User`` entity without any additional aliasing applied
to it, those references wil be in terms of the subquery::
q = session.query(User).filter(User.name.like('e%')).\
limit(5).from_self().\
join(User.addresses).filter(Address.email.like('q%')).\
order_by(User.name)
The ORDER BY against ``User.name`` is aliased to be in terms of the
inner subquery:
.. sourcecode:: sql
SELECT anon_1.user_id AS anon_1_user_id,
anon_1.user_name AS anon_1_user_name
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1
LIMIT :param_1) AS anon_1
JOIN address ON anon_1.user_id = address.user_id
WHERE address.email LIKE :email_1 ORDER BY anon_1.user_name
The automatic aliasing feature only works in a **limited** way,
for simple filters and orderings. More ambitious constructions
such as referring to the entity in joins should prefer to use
explicit subquery objects, typically making use of the
:meth:`_query.Query.subquery`
method to produce an explicit subquery object.
Always test the structure of queries by viewing the SQL to ensure
a particular structure does what's expected!
**Changing the Entities**
:meth:`_query.Query.from_self`
also includes the ability to modify what
columns are being queried. In our example, we want ``User.id``
to be queried by the inner query, so that we can join to the
``Address`` entity on the outside, but we only wanted the outer
query to return the ``Address.email`` column::
q = session.query(User).filter(User.name.like('e%')).\
limit(5).from_self(Address.email).\
join(User.addresses).filter(Address.email.like('q%'))
yielding:
.. sourcecode:: sql
SELECT address.email AS address_email
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1
LIMIT :param_1) AS anon_1
JOIN address ON anon_1.user_id = address.user_id
WHERE address.email LIKE :email_1
**Looking out for Inner / Outer Columns**
Keep in mind that when referring to columns that originate from
inside the subquery, we need to ensure they are present in the
columns clause of the subquery itself; this is an ordinary aspect of
SQL. For example, if we wanted to load from a joined entity inside
the subquery using :func:`.contains_eager`, we need to add those
columns. Below illustrates a join of ``Address`` to ``User``,
then a subquery, and then we'd like :func:`.contains_eager` to access
the ``User`` columns::
q = session.query(Address).join(Address.user).\
filter(User.name.like('e%'))
q = q.add_entity(User).from_self().\
options(contains_eager(Address.user))
We use :meth:`_query.Query.add_entity` above **before** we call
:meth:`_query.Query.from_self`
so that the ``User`` columns are present
in the inner subquery, so that they are available to the
:func:`.contains_eager` modifier we are using on the outside,
producing:
.. sourcecode:: sql
SELECT anon_1.address_id AS anon_1_address_id,
anon_1.address_email AS anon_1_address_email,
anon_1.address_user_id AS anon_1_address_user_id,
anon_1.user_id AS anon_1_user_id,
anon_1.user_name AS anon_1_user_name
FROM (
SELECT address.id AS address_id,
address.email AS address_email,
address.user_id AS address_user_id,
"user".id AS user_id,
"user".name AS user_name
FROM address JOIN "user" ON "user".id = address.user_id
WHERE "user".name LIKE :name_1) AS anon_1
If we didn't call ``add_entity(User)``, but still asked
:func:`.contains_eager` to load the ``User`` entity, it would be
forced to add the table on the outside without the correct
join criteria - note the ``anon1, "user"`` phrase at
the end:
.. sourcecode:: sql
-- incorrect query
SELECT anon_1.address_id AS anon_1_address_id,
anon_1.address_email AS anon_1_address_email,
anon_1.address_user_id AS anon_1_address_user_id,
"user".id AS user_id,
"user".name AS user_name
FROM (
SELECT address.id AS address_id,
address.email AS address_email,
address.user_id AS address_user_id
FROM address JOIN "user" ON "user".id = address.user_id
WHERE "user".name LIKE :name_1) AS anon_1, "user"
:param \*entities: optional list of entities which will replace
those being selected.
FN) r�r�r�rX�_from_selectable�_enable_single_critr�rYr-)r.r/�
fromclauser�s r0� from_selfzQuery.from_selfs���`
�����
�
�u�
%�
%�
�y�y���� �
�!�!�*�-�-�� %��� $� 1� 1� 3� 3���� &�
�O�O�H�%�%�%��r2c��||_dSr=)ro)r.�vals r0�_set_enable_single_critzQuery._set_enable_single_crit�s��#&�� � � r2c���dD]}|j�|d���|�|gd��d|_|j}g|_|D]#}|�||jd���$dS)N)r�r�r�r�r�r�� _joinpathr�r��_having� _prefixes� _suffixesTFr)r�rprnr�r5�adapt_to_selectablerb)r.rp�attr�old_entitiesr�s r0rnzQuery._from_selectable�s���
� *� *�D�
�M���d�D�)�)�)�)����z�l�D�1�1�1�).��%��~������ ;� ;�A�
�!�!�$���q�(9�:�:�:�:� ;� ;r2c��|std��S|���}|�|t���|jsd|_t|��S)zgReturn an iterator yielding result tuples corresponding
to the given list of columns.
r))r:�
)�iterr�r-�
_ColumnEntityr$)r.�columnsr�s r0�valueszQuery.values�sV��� ���8�8�O��K�K�M�M�� ����
��>�>�>��|� ��A�L��A�w�w�r2c�v� t|�|����dS#t$rYdSwxYw)zVReturn a scalar result corresponding to the given
column expression.
rN)�nextr��
StopIteration�r.�columns r0r
zQuery.valuesH��
�����F�+�+�,�,�Q�/�/��� � � ��4�4� ���s�'*�
8�8c�0�|�|��dS)a7Return a new :class:`_query.Query`
replacing the SELECT list with the
given entities.
e.g.::
# Users, filtered on some arbitrary criterion
# and then ordered by related email address
q = session.query(User).\
join(User.address).\
filter(User.name.like('%ed%')).\
order_by(Address.email)
# given *only* User.id==5, Address.email, and 'q', what
# would the *next* User in the result be ?
subq = q.with_entities(Address.email).\
order_by(None).\
filter(User.id==5).\
subquery()
q = q.join((subq, subq.c.email < Address.email)).\
limit(1)
N)r-)r.r/s r0�
with_entitieszQuery.with_entitiess��2
���8�$�$�$�$�$r2c���t|j��|_t|j��}|D]}t||���|�|j|d���dS)zXAdd one or more column expressions to the list
of result columns to be returned.N)rFr5rcr�r9)r.r��lr<s r0�add_columnszQuery.add_columns'sm��
�d�n�-�-���������� #� #�A��$��"�"�"�"�
�$�$�T�^�A�B�B�%7�8�8�8�8�8r2z0.7z9:meth:`.add_column` is superseded by :meth:`.add_columns`c�,�|�|��S)z�Add a column expression to the list of result columns to be
returned.
Pending deprecation: :meth:`.add_column` will be superseded by
:meth:`.add_columns`.
)r�r�s r0�
add_columnzQuery.add_column4s������'�'�'r2c��|jdg|�R�S)aLReturn a new :class:`_query.Query` object,
applying the given list of
mapper options.
Most supplied options regard changing how column- and
relationship-mapped attributes are loaded.
.. seealso::
:ref:`deferred_options`
:ref:`relationship_loader_options`
F��_options�r.rVs r0�optionsz
Query.optionsCs�� �t�}�U�*�T�*�*�*�*r2c��|jdg|�R�S�NTr�r�s r0�_conditional_optionszQuery._conditional_optionsUs���t�}�T�)�D�)�)�)�)r2c�P�|j���|_d|jvrt��|jd<tt j|����}|j|z|_|r|D]}|�|���dS|D]}|�|���dS)N�_unbound_load_dedupes) �_attributesr?r�rar �flatten_iterator�
_with_options�process_query_conditionally�
process_query)r.�conditionalrV�opts�opts r0r�zQuery._optionsXs��� �+�0�0�2�2���"�$�*:�:�:�8;���D��4�5��T�*�4�0�0�1�1��!�/�$�6���� (��
6�
6���/�/��5�5�5�5�
6�
6��
(�
(���!�!�$�'�'�'�'�
(�
(r2c��||��S)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`.
r))r.�fns r0�with_transformationzQuery.with_transformationhs��"�r�$�x�x�r2�*c�Z�|�t|��j}|xj|||ffz
c_dS)a�Add an indexing or other executional context
hint for the given entity or selectable to
this :class:`_query.Query`.
Functionality is passed straight through to
:meth:`_expression.Select.with_hint`,
with the addition that ``selectable`` can be a
:class:`_schema.Table`, :class:`_expression.Alias`,
or ORM entity / mapped class
/etc.
.. seealso::
:meth:`_query.Query.with_statement_hint`
:meth:`.Query.prefix_with` - generic SELECT prefixing which also
can suit some database-specific HINT syntaxes such as MySQL
optimizer hints
N)rrG�_with_hints)r.rG�text�dialect_names r0� with_hintzQuery.with_hint{s>��.�!� ��,�,�7�J����j�$��=�?�?����r2c�0�|�d||��S)a�Add a statement hint to this :class:`_expression.Select`.
This method is similar to :meth:`_expression.Select.with_hint`
except that
it does not require an individual table, and instead applies to the
statement as a whole.
This feature calls down into
:meth:`_expression.Select.with_statement_hint`.
.. versionadded:: 1.0.0
.. seealso::
:meth:`_query.Query.with_hint`
N)r�)r.r�r�s r0�with_statement_hintzQuery.with_statement_hint�s��$�~�~�d�D�,�7�7�7r2c��|jS)z�Get the non-SQL options which will take effect during execution.
.. versionadded:: 1.3
.. seealso::
:meth:`_query.Query.execution_options`
)r%r�s r0�get_execution_optionszQuery.get_execution_options�s
���&�&r2c�D�|j�|��|_dS)a�Set non-SQL options which take effect during execution.
The options are the same as those accepted by
:meth:`_engine.Connection.execution_options`.
Note that the ``stream_results`` execution option is enabled
automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()`
method is used.
.. seealso::
:meth:`_query.Query.get_execution_options`
N)r%r&�r.�kwargss r0�execution_optionszQuery.execution_options�s#�� #'�"9�"?�"?��"G�"G����r2z0.9z�The :meth:`_query.Query.with_lockmode` method is deprecated and will be removed in a future release. Please refer to :meth:`_query.Query.with_for_update`. c�D�t�|��|_dS)a"Return a new :class:`_query.Query`
object with the specified "locking mode",
which essentially refers to the ``FOR UPDATE`` clause.
:param mode: a string representing the desired locking mode.
Valid values are:
* ``None`` - translates to no lockmode
* ``'update'`` - translates to ``FOR UPDATE``
(standard SQL, supported by most dialects)
* ``'update_nowait'`` - translates to ``FOR UPDATE NOWAIT``
(supported by Oracle, PostgreSQL 8.1 upwards)
* ``'read'`` - translates to ``LOCK IN SHARE MODE`` (for MySQL),
and ``FOR SHARE`` (for PostgreSQL)
.. seealso::
:meth:`_query.Query.with_for_update` - improved API for
specifying the ``FOR UPDATE`` clause.
N)�LockmodeArg�parse_legacy_queryrK)r.�modes r0�
with_lockmodezQuery.with_lockmode�s!��B +�=�=�d�C�C����r2c�8�t|||||���|_dS)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
.. versionadded:: 0.9.0 :meth:`_query.Query.with_for_update`
supersedes
the :meth:`_query.Query.with_lockmode` method.
.. note:: It is generally a good idea to combine the use of the
:meth:`_orm.Query.populate_existing` method when using the
:meth:`_orm.Query.with_for_update` method. The purpose of
:meth:`_orm.Query.populate_existing` is to force all the data read
from the SELECT to be populated into the ORM objects returned,
even if these objects are already in the :term:`identity map`.
.. seealso::
:meth:`_expression.GenerativeSelect.with_for_update`
- Core level method with
full argument and behavioral description.
:meth:`_orm.Query.populate_existing` - overwrites attributes of
objects already loaded in the identity map.
)�read�nowait�of�skip_locked� key_shareN)r�rK)r.r�r�r�r�r�s r0�with_for_updatezQuery.with_for_update�s1��f +����#��
�
�
����r2c�"�t|��dkr|�|d��n't|��dkrtjd���|j���|_|j�|��dS)a�Add values for bind parameters which may have been
specified in filter().
Parameters may be specified using \**kwargs, or optionally a single
dictionary as the first positional argument. The reason for both is
that \**kwargs is convenient, however some parameter dictionaries
contain unicode keys in which case \**kwargs cannot be used.
rrzFparams() takes zero or one positional argument, which is a dictionary.N)rcr�rZr[r�r?)r.rVr�s r0r�zQuery.params&s����t�9�9��>�>��M�M�$�q�'�"�"�"�"�
��Y�Y��]�]��&�)���
��|�(�(�*�*�������F�#�#�#�#�#r2c��t|��D]K}tj|��}|�|dd��}|j�|j|z|_�D||_�LdS)a!Apply the given filtering criterion to a copy
of this :class:`_query.Query`, using SQL expressions.
e.g.::
session.query(MyClass).filter(MyClass.name == 'some name')
Multiple criteria may be specified as comma separated; the effect
is that they will be joined together using the :func:`.and_`
function::
session.query(MyClass).\
filter(MyClass.name == 'some name', MyClass.id > 5)
The criterion is any SQL expression object applicable to the
WHERE clause of a select. String expressions are coerced
into SQL expression constructs via the :func:`_expression.text`
construct.
.. seealso::
:meth:`_query.Query.filter_by` - filter on keyword expressions.
TN)rFr!�_expression_literal_as_textrr��r.� criterions r0rfzQuery.filter;sk��4�i��� ,� ,�I�"�>�y�I�I�I��*�*�9�d�D�A�A�I���*�"&�/�I�"=����"+���� ,� ,r2c����|������)tjd|���z����fd�|���D��}|j|�S)a�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.
Nz�Can't use filter_by when the first entity '%s' of a query is not a mapped class. Please use the filter method instead, or change the order of the entities in the queryc�>��g|]\}}t�|��|k��Sr)r)r�r3r
�zeros �r0r�z#Query.filter_by.<locals>.<listcomp>�s<���
�
�
���U�
�t�S�)�)�U�2�
�
�
r2)r�rZr�r��itemsrf)r.r��clausesr�s @r0� filter_byzQuery.filter_by_s����2�#�#�%�%���<��,�C��)�)�+�+�,���
�
�
�
�
�$�l�l�n�n�
�
�
���t�{�G�$�$r2c��t|��dkr-|ddurd|jvrd|_dS|d� d|_dS|�|��}|jdus|j� ||_dS|j|z|_dS)agApply one or more ORDER BY criterion to the query and return
the newly resulting :class:`_query.Query`.
All existing ORDER BY settings can be suppressed by
passing ``None`` - this will suppress any ordering configured
on the :func:`.mapper` object using the deprecated
:paramref:`.mapper.order_by` parameter.
rrFr�N)rcr�r�r�r�s r0r�zQuery.order_by�s����y�>�>�Q�����|�u�$�$��$�-�/�/�%*�D�N�����|�#�!%������(�(��3�3� ��>�U�"�"�d�n�&<�&�D�N�N�N�!�^�i�7�D�N�N�Nr2c��t|��dkr|d� d|_dSttd�|D�����}|�|��}|jdur ||_dS|j|z|_dS)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.
.. versionadded:: 1.1 GROUP BY can be cancelled by passing
``None``, in the same way as ORDER BY.
rrNFc�,�g|]}t|����Sr)rr;s r0r�z"Query.group_by.<locals>.<listcomp>�s�� D� D� D�Q��a��� D� D� Dr2)rcr�rFrr�r�s r0�group_byzQuery.group_by�s����y�>�>�Q�����|�#�!&������� D� D�)� D� D� D�E�F�F� ��(�(��3�3� ��>�U�"�"�&�D�N�N�N�!�^�i�7�D�N�N�Nr2c��tj|��}|�.t|tj��stjd���|�|dd��}|j�|j|z|_dS||_dS)aApply a HAVING criterion to the query and return the
newly resulting :class:`_query.Query`.
:meth:`_query.Query.having` is used in conjunction with
:meth:`_query.Query.group_by`.
HAVING criterion makes it possible to use filters on aggregate
functions like COUNT, SUM, AVG, MAX, and MIN, eg.::
q = session.query(User.id).\
join(User.addresses).\
group_by(User.id).\
having(func.count(Address.id) > 2)
NzHhaving() argument must be of type sqlalchemy.sql.ClauseElement or stringT) r!r�r^r�
ClauseElementrZr[rrwr�s r0�havingzQuery.having�s���$�:�9�E�E� �� ���s�(�*
�*
� ��&�9���
�
�&�&�y�$��=�=� ��<�#��<�)�3�D�L�L�L�$�D�L�L�Lr2c�z�|�||gt|��z����d��Sr�)rnrFrt)r.�expr_fnr�s r0�_set_opz
Query._set_op�s?���$�$��G�t�f�t�A�w�w�&�(�
�
�
!�
!�%�
(�
(� )r2c�2�|jtjg|�R�S)a�Produce a UNION of this Query against one or more queries.
e.g.::
q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar')
q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo')
q3 = q1.union(q2)
The method accepts multiple Query objects so as to control
the level of nesting. A series of ``union()`` calls such as::
x.union(y).union(z).all()
will nest on each ``union()``, and produces::
SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION
SELECT * FROM y) UNION SELECT * FROM Z)
Whereas::
x.union(y, z).all()
produces::
SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION
SELECT * FROM Z)
Note that many database backends do not allow ORDER BY to
be rendered on a query called within UNION, EXCEPT, etc.
To disable all ORDER BY clauses including those configured
on mappers, issue ``query.order_by(None)`` - the resulting
:class:`_query.Query` object will not render ORDER BY within
its SELECT statement.
)r�r!r&�r.r�s r0r&zQuery.union�s"��J�t�|�J�,�1�q�1�1�1�1r2c�2�|jtjg|�R�S)z�Produce a UNION ALL of this Query against one or more queries.
Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.
)r�r!� union_allr�s r0r�zQuery.union_all
�!���t�|�J�0�5�1�5�5�5�5r2c�2�|jtjg|�R�S)z�Produce an INTERSECT of this Query against one or more queries.
Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.
)r�r!� intersectr�s r0r�zQuery.intersectr�r2c�2�|jtjg|�R�S)z�Produce an INTERSECT ALL of this Query against one or more queries.
Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.
)r�r!�
intersect_allr�s r0r�zQuery.intersect_alls!���t�|�J�4�9�q�9�9�9�9r2c�2�|jtjg|�R�S)z�Produce an EXCEPT of this Query against one or more queries.
Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.
)r�r!�except_r�s r0r�z
Query.except_(s!���t�|�J�.�3��3�3�3�3r2c�2�|jtjg|�R�S)z�Produce an EXCEPT ALL of this Query against one or more queries.
Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
that method for usage examples.
)r�r!�
except_allr�s r0r�zQuery.except_all1s!���t�|�J�1�6�A�6�6�6�6r2c�T�|�dd��|�dd��|�dd��|�dd��f\}}}}|r2tdd�t|����z���|�|||||���S) aO-Create a SQL JOIN against this :class:`_query.Query`
object's criterion
and apply generatively, returning the newly resulting
:class:`_query.Query`.
**Simple Relationship Joins**
Consider a mapping between two classes ``User`` and ``Address``,
with a relationship ``User.addresses`` representing a collection
of ``Address`` objects associated with each ``User``. The most
common usage of :meth:`_query.Query.join`
is to create a JOIN along this
relationship, using the ``User.addresses`` attribute as an indicator
for how this should occur::
q = session.query(User).join(User.addresses)
Where above, the call to :meth:`_query.Query.join` along
``User.addresses`` will result in SQL approximately equivalent to::
SELECT user.id, user.name
FROM user JOIN address ON user.id = address.user_id
In the above example we refer to ``User.addresses`` as passed to
:meth:`_query.Query.join` as the "on clause", that is, it indicates
how the "ON" portion of the JOIN should be constructed.
To construct a chain of joins, multiple :meth:`_query.Query.join`
calls may be used. The relationship-bound attribute implies both
the left and right side of the join at once::
q = session.query(User).\
join(User.orders).\
join(Order.items).\
join(Item.keywords)
.. note:: as seen in the above example, **the order in which each
call to the join() method occurs is important**. Query would not,
for example, know how to join correctly if we were to specify
``User``, then ``Item``, then ``Order``, in our chain of joins; in
such a case, depending on the arguments passed, it may raise an
error that it doesn't know how to join, or it may produce invalid
SQL in which case the database will raise an error. In correct
practice, the
:meth:`_query.Query.join` method is invoked in such a way that lines
up with how we would want the JOIN clauses in SQL to be
rendered, and each call should represent a clear link from what
precedes it.
**Joins to a Target Entity or Selectable**
A second form of :meth:`_query.Query.join` allows any mapped entity or
core selectable construct as a target. In this usage,
:meth:`_query.Query.join` will attempt to create a JOIN along the
natural foreign key relationship between two entities::
q = session.query(User).join(Address)
In the above calling form, :meth:`_query.Query.join` is called upon to
create the "on clause" automatically for us. This calling form will
ultimately raise an error if either there are no foreign keys between
the two entities, or if there are multiple foreign key linkages between
the target entity and the entity or entities already present on the
left side such that creating a join requires more information. Note
that when indicating a join to a target without any ON clause, ORM
configured relationships are not taken into account.
**Joins to a Target with an ON Clause**
The third calling form allows both the target entity as well
as the ON clause to be passed explicitly. A example that includes
a SQL expression as the ON clause is as follows::
q = session.query(User).join(Address, User.id==Address.user_id)
The above form may also use a relationship-bound attribute as the
ON clause as well::
q = session.query(User).join(Address, User.addresses)
The above syntax can be useful for the case where we wish
to join to an alias of a particular target entity. If we wanted
to join to ``Address`` twice, it could be achieved using two
aliases set up using the :func:`~sqlalchemy.orm.aliased` function::
a1 = aliased(Address)
a2 = aliased(Address)
q = session.query(User).\
join(a1, User.addresses).\
join(a2, User.addresses).\
filter(a1.email_address=='ed@foo.com').\
filter(a2.email_address=='ed@bar.com')
The relationship-bound calling form can also specify a target entity
using the :meth:`_orm.PropComparator.of_type` method; a query
equivalent to the one above would be::
a1 = aliased(Address)
a2 = aliased(Address)
q = session.query(User).\
join(User.addresses.of_type(a1)).\
join(User.addresses.of_type(a2)).\
filter(a1.email_address == 'ed@foo.com').\
filter(a2.email_address == 'ed@bar.com')
**Joining to Tables and Subqueries**
The target of a join may also be any table or SELECT statement,
which may be related to a target entity or not. Use the
appropriate ``.subquery()`` method in order to make a subquery
out of a query::
subq = session.query(Address).\
filter(Address.email_address == 'ed@foo.com').\
subquery()
q = session.query(User).join(
subq, User.id == subq.c.user_id
)
Joining to a subquery in terms of a specific relationship and/or
target entity may be achieved by linking the subquery to the
entity using :func:`_orm.aliased`::
subq = session.query(Address).\
filter(Address.email_address == 'ed@foo.com').\
subquery()
address_subq = aliased(Address, subq)
q = session.query(User).join(
User.addresses.of_type(address_subq)
)
**Controlling what to Join From**
In cases where the left side of the current state of
:class:`_query.Query` is not in line with what we want to join from,
the :meth:`_query.Query.select_from` method may be used::
q = session.query(Address).select_from(User).\
join(User.addresses).\
filter(User.name == 'ed')
Which will produce SQL similar to::
SELECT address.* FROM user
JOIN address ON user.id=address.user_id
WHERE user.name = :name_1
**Legacy Features of Query.join()**
The :meth:`_query.Query.join` method currently supports several
usage patterns and arguments that are considered to be legacy
as of SQLAlchemy 1.3. A deprecation path will follow
in the 1.4 series for the following features:
* Joining on relationship names rather than attributes::
session.query(User).join("addresses")
**Why it's legacy**: the string name does not provide enough context
for :meth:`_query.Query.join` to always know what is desired,
notably in that there is no indication of what the left side
of the join should be. This gives rise to flags like
``from_joinpoint`` as well as the ability to place several
join clauses in a single :meth:`_query.Query.join` call
which don't solve the problem fully while also
adding new calling styles that are unnecessary and expensive to
accommodate internally.
**Modern calling pattern**: Use the actual relationship,
e.g. ``User.addresses`` in the above case::
session.query(User).join(User.addresses)
* Automatic aliasing with the ``aliased=True`` flag::
session.query(Node).join(Node.children, aliased=True).\
filter(Node.name == 'some name')
**Why it's legacy**: the automatic aliasing feature of
:class:`_query.Query` is intensely complicated, both in its internal
implementation as well as in its observed behavior, and is almost
never used. It is difficult to know upon inspection where and when
its aliasing of a target entity, ``Node`` in the above case, will be
applied and when it won't, and additionally the feature has to use
very elaborate heuristics to achieve this implicit behavior.
**Modern calling pattern**: Use the :func:`_orm.aliased` construct
explicitly::
from sqlalchemy.orm import aliased
n1 = aliased(Node)
session.query(Node).join(Node.children.of_type(n1)).\
filter(n1.name == 'some name')
* Multiple joins in one call::
session.query(User).join("orders", "items")
session.query(User).join(User.orders, Order.items)
session.query(User).join(
(Order, User.orders),
(Item, Item.order_id == Order.id)
)
# ... and several more forms actually
**Why it's legacy**: being able to chain multiple ON clauses in one
call to :meth:`_query.Query.join` is yet another attempt to solve
the problem of being able to specify what entity to join from,
and is the source of a large variety of potential calling patterns
that are internally expensive and complicated to parse and
accommodate.
**Modern calling pattern**: Use relationship-bound attributes
or SQL-oriented ON clauses within separate calls, so that
each call to :meth:`_query.Query.join` knows what the left
side should be::
session.query(User).join(User.orders).join(
Item, Item.order_id == Order.id)
:param \*props: Incoming arguments for :meth:`_query.Query.join`,
the props collection in modern use should be considered to be a one
or two argument form, either as a single "target" entity or ORM
attribute-bound relationship, or as a target entity plus an "on
clause" which may be a SQL expression or ORM attribute-bound
relationship.
:param isouter=False: If True, the join used will be a left outer join,
just as if the :meth:`_query.Query.outerjoin` method were called.
:param full=False: render FULL OUTER JOIN; implies ``isouter``.
.. versionadded:: 1.1
:param from_joinpoint=False: When using ``aliased=True``, a setting
of True here will cause the join to be from the most recent
joined target, rather than starting back from the original
FROM clauses of the query.
.. note:: This flag is considered legacy.
:param aliased=False: If True, indicate that the JOIN target should be
anonymously aliased. Subsequent calls to :meth:`_query.Query.filter`
and similar will adapt the incoming criterion to the target
alias, until :meth:`_query.Query.reset_joinpoint` is called.
.. note:: This flag is considered legacy.
.. seealso::
:ref:`ormtutorial_joins` in the ORM tutorial.
:ref:`inheritance_toplevel` for details on how
:meth:`_query.Query.join` is used for inheritance relationships.
:func:`_orm.join` - a standalone ORM-level join function,
used internally by :meth:`_query.Query.join`, which in previous
SQLAlchemy versions was the primary ORM-level joining interface.
rF�from_joinpoint�isouter�full�unknown arguments: %s�, �� outerjoinr��create_aliasesr��rp� TypeErrorr�sorted�_join)r.�propsr�rr�r�r�s r0rz
Query.join:s���h
�J�J�y�%�(�(��J�J�'��/�/��J�J�y�%�(�(��J�J�v�u�%�%� 2
�.����$�� ��'�$�)�)�F�6�N�N�*C�*C�C���
��z�z����"�)��
�
�
r2c�"�|�dd��|�dd��|�dd��}}}|r2tdd�t|����z���|�|d|||���S) z�Create a left outer join against this :class:`_query.Query`
object's criterion and apply generatively, returning the newly
resulting :class:`_query.Query`.
Usage is the same as the :meth:`_query.Query.join` method.
rFr�r�r�r�Tr�r�)r.r�r�rr�r�s r0r�zQuery.outerjoin_ s���
�J�J�y�%�(�(��J�J�'��/�/��J�J�v�u�%�%�"&���
� ��'�$�)�)�F�6�N�N�*C�*C�C���
��z�z����"�)��
�
�
r2c��||_d|vrC|d\}}|���}|���||<||f|d<|}d|v�C||_dS)N�prev)r�r?rv)r.�jp�fr�s r0�_update_joinpointzQuery._update_joinpointx si�������l�l���j�G�A�t��9�9�;�;�D��g�g�i�i�D��G��T��B�v�J��B���l�l�����r2c
��|s|���t|��dkrbt|dtjt
tf��r5t|dttjtj
f��r|f}tj|��}t|��D�]
\}}t|t��r|\}} nd} t|tj
tjf��r| |}}
n|| }}
|�:t!|
��}|js$t%|d��st'jd���t|tj
��rt+|dd��}
nd}
t|tj��r#t-|���|��}nl|rjt|tj
��rP|���}t!|��}t+|dd��|jurt-||j��}t|tj
���rn|
�W|
r|
}
nR|j}
|
j}
nB#t8$r5}tjt'jd|
z��|� ��Yd}~nd}~wwxYw|j}|j�|d��}t|t@��r6|j!�"|��r|j#}t+||j��}|j}t|tHj%��s|}|s�||
|jf}||j&vro|j&|�'��}||j&f|d
<|�(|��|t|��dz
krtj)d|z�����ndx}}|�*||
|||||����dS)z�Consumes arguments from :meth:`_query.Query.join` or
:meth:`_query.Query.outerjoin`, places them into a
consistent format with which to form the actual JOIN constructs.
rrrNrAz9Expected mapped entity or selectable/table as join target�_of_typez0Join target %s does not refer to a mapped entityrBr�z:Pathed join target %s has already been joined to; skipping)+�_reset_joinpointrcr^r!rx�typer�strr�r�PropComparatorr r8� enumeratera�string_typesrr]rWrZr[�getattrrr��
_parententityr3rgrL�AttributeErrorrIr,rvrrA�isa�
aliased_classr�QueryableAttributer�r?r��warn�_join_left_to_right)r.�keysr�r�r�r��keylist�idx�arg1�arg2�right�onclause�r_info�of_type�jp0rlrQ�leftr`r@�edger�s r0r�zQuery._join� sS��� $��!�!�#�#�#�
��I�I��N�N���Q��*�/��|�D���
���Q���j�.�
�0I�J���
��7�D��,�t�$�$��"�7�+�+�y �y �I�C���$��&�&�
�"�
��d�d���
��z�0�$�2C�D���
-�#'��x���"&��x���� ������+��G�F�H�4M�4M�� �.�:����
�(�J�$=�>�>�
�!�(�J��=�=������(�D�$5�6�6�
E�.�d�.B�.B�.D�.D�h�O�O��� �
E�J��*�3�%�%�
E��*�*�,�,���s�|�|���4��4�0�0�H�4J�J�J�1�#�x�|�D�D�H��(�J�$=�>�>�;
#��=��� '��� (� 1�� �$)�L�E�E��-���� �K� &� 4�%4�6;�%<�!"�!"�14������������������ �-���2�6�6�t�T�B�B���e�Z�0�0�;�U�\�5E�5E�d�5K�5K�;� �.�D�&�t�X�\�:�:�H��(��!�(�J�,I�J�J�$�#�H�%�!�!�%���2�D��t��.�.�"�_�T�2�7�7�9�9��&*�D�O�%<��6�
��.�.�r�2�2�2��#�g�,�,��"2�2�2� �I�!;�=A�!B����!��#�"��t�
�$�$��e�X�t�^�Y��
�
�
�
�oy �y s�>I�
J�+J�Jc�H�|j���|_|� |�J�|�|||��\}}} n|�J�|�|��\}} ||ur|st jd|�d|�d����|�|||||��\}
}}|�L|j|}|jd|�t|||||���fz|j|dzd�z|_dS| �|j | j
}n|}|jt|||||���fz|_dS)z�Given raw "left", "right", "onclause" parameters consumed from
a particular key within _join(), add a real ORMJoin object to
our _from_obj list (or augment an existing one)
NzCan't construct a join from z to z, they are the same entity)r�r�r)r,r?�"_join_determine_implicit_left_side�_join_place_explicit_left_siderZr�� _join_check_and_adapt_right_siderb�orm_joinr5rG)r.rr r
r@r�r�r��replace_from_obj_index�use_entity_indexr�left_clauses r0rzQuery._join_left_to_right
s���&*�%?�%D�%D�%F�%F��"��<��<�<�<�
�7�7��e�X�N�N�
��&� � ��#�#�#��3�3�D�9�9�
�&� ��5�=�=��=��,�,�)-���u�u�u�6���
�#'�"G�"G��%��4��#
�#
����x�"�-��.�)?�@�K���6� 6�6�7��#�� � )�!����� ��.�!7�!�!;�!=�!=�>�
?�
�N�N�N� �+�"�n�-=�>�I���"��!�^�����)�$����/��D�N�N�Nr2c��t|��}dx}}|jr�tj|j|j|��}t|��dkr|d}|j|}�nit|��dkrt
jd���t
jd|�d����|j�ri}t|j��D]Q\} }
|
j
}|��t|��}||ur�#t|
t��r
| |f||
j<�Ed|f||j<�Rt|�����}
tj|
|j|��}t|��dkr||
|d\}}nSt|��dkrt
jd���t
jd|�d����t
jd���|||fS)z�When join conditions don't express the left side explicitly,
determine if an existing FROM or entity in this query
can serve as the left hand side.
NrraCan't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Please use the .select_from() method to establish an explicit left side, as well as providing an explcit ON clause if not present already to help resolve the ambiguity.zDon't know how to join to z�. Please use the .select_from() method to establish an explicit left side, as well as providing an explcit ON clause if not present already to help resolve the ambiguity.zgNo entities to join from; please use select_from() to establish the left entity/selectable of this join)rrbrE�find_left_clause_to_join_fromrGrcrZr�r5r��entity_zero_or_selectabler^r�rFr)r.rr r
rrr�indexes� potential�entity_indexr;rL�ent_info�all_clausess r0rz(Query._join_determine_implicit_left_sidel
s?��"�����48�8��!1��>�O ��<���� 1�8���G��7�|�|�q� � �)0���&��~�&<�=����W����!�!��0�2�����0�0�
6;�U�U� =�����^�2 ��I�%.�t�~�%>�%>�
D�
D�!��c��6���>��"�6�?�?���v�%�%��
�c�=�1�1�D�1=�v�0F�I�c�n�-�-�6:�F�^�I�h�1�2�2��y�~�~�/�/�0�0�K��<��V�.����G��7�|�|�q� � �)2�;�w�q�z�3J�)K�&� �$�$��W����!�!��0�2�����0�0�
6;�U�U� =�����,�1���
��+�-=�=�=r2c��dx}}t|��}|jrPtj|j|j��}t|��dkrt
jd���|r|d}|�_|jrXt|d��rHt|j��D]3\}}t|t��r|�
|��r|}n�4||fS)z�When join conditions express a left side explicitly, determine
where in our existing list of FROM clauses we should join towards,
or if we need to make a new join, and if so is it from one of our
existing entities.
NrzrCan't identify which entity in which to assign the left side of this join. Please use a more specific ON clause.rrA)rrbrE�#find_left_clause_that_matches_givenrGrcrZr�r5rWr�r^r��corresponds_to)r.rrr�l_inforrr;s r0rz$Query._join_place_explicit_left_side�
s��259�8��!1�������>� 4��B���� 1���G��7�|�|�a����0�!�����
4�)0���&�
#�*���
+����)�)�
+�&�d�n�5�5�
�
���S��c�=�1�1��c�6H�6H��6N�6N��'*�$��E��%�'7�7�7r2c�L�t|��}t|��}d}|s�t|dd��} | rp| jst| jt
j��rJ|jp|jgD]:}
tj
|j|
��rtj
|
|j��rd}n�;|s|s*|j|jurtjd|jz���t|dd��|jt|dd��}}} | r6|r4| �
|j��stjd|�d|�����t|d��r|xj|fz
c_d}
|jr�|r|j} |jr|�|dd��}n�|r�|�| j��s*tjd |j�d
| jj�d����t|t
j��r|���}d}
t1| |��}n|rtjd���| o*|o'| jrt| jt
j��p|}|
s|s|rt1|d�
��}d}
|
rB| sJ�t7|| j���}|f|jz|_|s|�| |��t|t
j��r|�|dd��}|s*|r(|� ||||j!f|j"fd���n d|i|_"|t|��|fS)z�Transform the "right" side of the join as well as the onclause
according to polymorphic mapping translations, aliasing on the query
or on the join, special cases where the right and left side have
overlapping tables.
FrANTz*Can't join table/selectable '%s' to itselfr@zJoin target z9 does not correspond to the right side of join condition zSelectable 'z' is not derived from 'rbzpThe aliased=True parameter on query.join() only works with an ORM entity, not a plain selectable, as the target.)�flat)�equivalents)r�r�r�)#rr�rBr^rCr!�JoinrbrGrE�selectables_overlaprZr��
common_parentrArW�_join_entitiesr��_is_lateralr�is_derived_from�descriptionr_r`r�_with_polymorphic_selectablerdrrHr�rDr�r�r3r�)r.rr r
r@r�r#r�overlap�right_mapperrk�right_selectable�right_is_aliased�need_adapter�aliased_entityrSs r0rz&Query._join_check_and_adapt_right_sidesP��������������� �"�6�8�T�:�:�L��
��-�
��l�=�z��O�O�
�!%�� E�6�3D�2E���H��3��)�8����"�6� �&�"3����
#'�����
� �)� ���6�#4�4�4��,�<��#�$���
�
�F�H�d�+�+����F�.��6�6�)9�&��
� �� �!�.�.�t�{�;�;� �
�,�,�9>�����J���
��6�8�$�$� -����F�9�,������#�( ��
+�#�{���+�#
��*�*�5�$��>�>����
�(�7�7� �3��� �!�4�4�-�8�8�8�(�;�G�G�G������.�
�0E�F�F�(�'7�'=�'=�'?�'?�$�#'�L� ��.>�?�?����
��0�����
�
�$�$�
��-��� �=�z�?O����� �� �� �>� ��E��-�-�-�E��L�� O����<�
!��<�#C����G�%,�:��0D�#D�D� �"�
O��7�7��g�N�N�N��h�
� 8�9�9� @��)�)�(�D�$�?�?�H�� ;�$� ;��"�"�).�"�E�4�8�4�d�o�F���
�
�
�
� 3�E�:�D�O��g�e�n�n�h�.�.r2c�,�|j|_d|_dS�Nr))rvr�r�r�s r0r�zQuery._reset_joinpoint�s���.���!����r2c�.�|���dS)acReturn a new :class:`_query.Query`, where the "join point" has
been reset back to the base FROM entities of the query.
This method is usually used in conjunction with the
``aliased=True`` feature of the :meth:`_query.Query.join`
method. See the example in :meth:`_query.Query.join` for how
this is used.
N)r�r�s r0�reset_joinpointzQuery.reset_joinpoint�s��
�������r2c�2�|�|d��dS)a�Set the FROM clause of this :class:`_query.Query` explicitly.
:meth:`_query.Query.select_from` is often used in conjunction with
:meth:`_query.Query.join` in order to control which entity is selected
from on the "left" side of the join.
The entity or selectable object here effectively replaces the
"left edge" of any calls to :meth:`_query.Query.join`, when no
joinpoint is otherwise established - usually, the default "join
point" is the leftmost entity in the :class:`_query.Query` object's
list of entities to be selected.
A typical example::
q = session.query(Address).select_from(User).\
join(User.addresses).\
filter(User.name == 'ed')
Which produces SQL equivalent to::
SELECT address.* FROM user
JOIN address ON user.id=address.user_id
WHERE user.name = :name_1
:param \*from_obj: collection of one or more entities to apply
to the FROM clause. Entities can be mapped classes,
:class:`.AliasedClass` objects, :class:`_orm.Mapper` objects
as well as core :class:`_expression.FromClause`
elements like subqueries.
.. versionchanged:: 0.9
This method no longer applies the given FROM object
to be the selectable from which matching entities
select from; the :meth:`.select_entity_from` method
now accomplishes this. See that method for a description
of this behavior.
.. seealso::
:meth:`_query.Query.join`
:meth:`_query.Query.select_entity_from`
FN�rn�r.rks r0�select_fromzQuery.select_from�s!��^
���h��.�.�.�.�.r2c�4�|�|gd��dS)a�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).\
filter(User.name == 'ed')
Above, the generated SQL will show that the ``User`` entity is
adapted to our statement, even in the case of the WHERE clause:
.. sourcecode:: sql
SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name
FROM (SELECT "user".id AS id, "user".name AS name
FROM "user"
WHERE "user".id = :id_1) AS anon_1
WHERE anon_1.name = :name_1
The :meth:`_query.Query.select_entity_from` method is similar to the
:meth:`_query.Query.select_from` method,
in that it sets the FROM clause
of the query. The difference is that it additionally applies
adaptation to the other parts of the query that refer to the
primary entity. If above we had used :meth:`_query.Query.select_from`
instead, the SQL generated would have been:
.. sourcecode:: sql
-- uses plain select_from(), not select_entity_from()
SELECT "user".id AS user_id, "user".name AS user_name
FROM "user", (SELECT "user".id AS id, "user".name AS name
FROM "user"
WHERE "user".id = :id_1) AS anon_1
WHERE "user".name = :name_1
To supply textual SQL to the :meth:`_query.Query.select_entity_from`
method,
we can make use of the :func:`_expression.text` construct. However,
the
:func:`_expression.text`
construct needs to be aligned with the columns of our
entity, which is achieved by making use of the
:meth:`_expression.TextClause.columns` method::
text_stmt = text("select id, name from user").columns(
User.id, User.name)
q = session.query(User).select_entity_from(text_stmt)
:meth:`_query.Query.select_entity_from` itself accepts an
:func:`.aliased`
object, so that the special options of :func:`.aliased` such as
:paramref:`.aliased.adapt_on_names` may be used within the
scope of the :meth:`_query.Query.select_entity_from`
method's adaptation
services. Suppose
a view ``user_view`` also returns rows from ``user``. If
we reflect this view into a :class:`_schema.Table`, this view has no
relationship to the :class:`_schema.Table` to which we are mapped,
however
we can use name matching to select from it::
user_view = Table('user_view', metadata,
autoload_with=engine)
user_view_alias = aliased(
User, user_view, adapt_on_names=True)
q = session.query(User).\
select_entity_from(user_view_alias).\
order_by(User.name)
.. versionchanged:: 1.1.7 The :meth:`_query.Query.select_entity_from`
method now accepts an :func:`.aliased` object as an alternative
to a :class:`_expression.FromClause` object.
:param from_obj: a :class:`_expression.FromClause`
object that will replace
the FROM clause of this :class:`_query.Query`.
It also may be an instance
of :func:`.aliased`.
.. seealso::
:meth:`_query.Query.select_from`
TNr:r;s r0�select_entity_fromzQuery.select_entity_from�s#��b
���x�j�$�/�/�/�/�/r2c�Z�t|t��r�tj|��\}}}t|t��r t|t��r||z
dkrgSt|t��r|dkst|t��r|dkrt|��|S|�||��}|�t|��dd|j�St|��S|dkrt|��dSt|||dz���dS)Nr���r)r^�slicer �decode_slice�intrF�step)r.�item�start�stoprD�ress r0�__getitem__zQuery.__getitem__ms'���d�E�"�"� 6� $� 1�$� 7� 7��E�4���4��%�%�
(��u�c�*�*�
(��5�L�A�%�%�� ��U�C�(�(�
(�U�Q�Y�Y��4��%�%�.7�*.��(�(��D�z�z�$�'�'��*�*�U�D�)�)�C����C�y�y���t�y�!8�9�9��C�y�y� ��r�z�z��D�z�z�"�~�%��D���q���1�2�2�1�5�5r2c�P�|�8|�6|j�|jnd|_|dkr|xj|z
c_||z
|_n;|�
|�||_n/|�-|�+|j�|jnd|_|dkr|xj|z
c_t|jt��r|jdkrd|_dSdSdS)aComputes the "slice" of the :class:`_query.Query` represented by
the given indices and returns the resulting :class:`_query.Query`.
The start and stop indices behave like the argument to Python's
built-in :func:`range` function. This method provides an
alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
query.
For example, ::
session.query(User).order_by(User.id).slice(1, 3)
renders as
.. sourcecode:: sql
SELECT users.id AS users_id,
users.name AS users_name
FROM users ORDER BY users.id
LIMIT ? OFFSET ?
(2, 1)
.. seealso::
:meth:`_query.Query.limit`
:meth:`_query.Query.offset`
Nr)r�r�r^rC)r.rFrGs r0rAzQuery.slice�s���>���!1�+/�<�+C�4�<�<��D�L���z�z�����%�����,�D�K�K�
�]�t�/��D�K�K�
�
�4�<�+/�<�+C�4�<�<��D�L���z�z�����%����d�l�C�(�(� �T�\�Q�->�->��D�L�L�L� � �->�->r2c��||_dS)zfApply a ``LIMIT`` to the query and return the newly resulting
:class:`_query.Query`.
N)r�)r.�limits r0rLzQuery.limit�s������r2c��||_dS)zhApply an ``OFFSET`` to the query and return the newly resulting
:class:`_query.Query`.
N)r�)r.�offsets r0rNzQuery.offset�s������r2c��|s d|_dS|�|��}t|jt��r|xj|z
c_dS||_dS)a�Apply a ``DISTINCT`` to the query and return the newly resulting
:class:`_query.Query`.
.. note::
The :meth:`.distinct` call includes logic that will automatically
add columns from the ORDER BY of the query to the columns
clause of the SELECT statement, to satisfy the common need
of the database backend that ORDER BY columns be part of the
SELECT list when DISTINCT is used. These columns *are not*
added to the list of columns actually fetched by the
:class:`_query.Query`, however, so would not affect results.
The columns are passed through when using the
:attr:`_query.Query.statement` accessor, however.
:param \*expr: optional column expressions. When present,
the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>)``
construct.
TN)r�r�r^rF)r.�exprs r0r�zQuery.distinct�s]��.� &�!�D�N�N�N��'�'��-�-�D��$�.�$�/�/�
&����$�&�����!%����r2c�F�|jr|xj|z
c_dS||_dS)a�Apply the prefixes to the query and return the newly resulting
:class:`_query.Query`.
:param \*prefixes: optional prefixes, typically strings,
not using any commas. In particular is useful for MySQL keywords
and optimizer hints:
e.g.::
query = sess.query(User.name).\
prefix_with('HIGH_PRIORITY').\
prefix_with('SQL_SMALL_RESULT', 'ALL').\
prefix_with('/*+ BKA(user) */')
Would render::
SELECT HIGH_PRIORITY SQL_SMALL_RESULT ALL /*+ BKA(user) */
users.name AS users_name FROM users
.. seealso::
:meth:`_expression.HasPrefixes.prefix_with`
N)rx)r.�prefixess r0�prefix_withzQuery.prefix_with�s-��4�>� &��N�N�h�&�N�N�N�N�%�D�N�N�Nr2c�F�|jr|xj|z
c_dS||_dS)adApply the suffix to the query and return the newly resulting
:class:`_query.Query`.
:param \*suffixes: optional suffixes, typically strings,
not using any commas.
.. versionadded:: 1.0.0
.. seealso::
:meth:`_query.Query.prefix_with`
:meth:`_expression.HasSuffixes.suffix_with`
N)ry)r.�suffixess r0�suffix_withzQuery.suffix_with
s-��"�>� &��N�N�h�&�N�N�N�N�%�D�N�N�Nr2c� �t|��S)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`
)rFr�s r0�allz Query.all
s�� �D�z�z�r2c��tj|��}t|tjtjf��stjd���||_dS)a1Execute the given SELECT statement and return results.
This method bypasses all internal statement compilation, and the
statement is executed without modification.
The statement is typically either a :func:`_expression.text`
or :func:`_expression.select` construct, and should return the set
of columns
appropriate to the entity class represented by this
:class:`_query.Query`.
.. seealso::
:ref:`orm_tutorial_literal_sql` - usage examples in the
ORM tutorial
zBfrom_statement accepts text(), select(), and union() objects only.N)r!r�r^�
TextClauser_rZr[r�)r.r�s r0�from_statementzQuery.from_statement/
s_��&�:�9�E�E� ���
�-�z�/D�E�
�
� ��&�,���
�
$����r2c��|j�t|��dd�}nt|dd���}t|��dkr|dSdS)a7Return the first result of this ``Query`` or
None if the result doesn't contain any row.
first() applies a limit of one within the generated SQL, so that
only one primary entity row is generated on the server side
(note this may consist of multiple result rows if join-loaded
collections are present).
Calling :meth:`_query.Query.first`
results in an execution of the underlying
query.
.. seealso::
:meth:`_query.Query.one`
:meth:`_query.Query.one_or_none`
Nrr)r�rFrc�r.�rets r0�firstzQuery.firstN
sQ��(�?�&��t�*�*�Q�q�S�/�C�C��t�A�a�C�y�/�/�C��s�8�8�a�<�<��q�6�M��4r2c��t|��}t|��}|dkr|dS|dkrdStjd���)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`
rrNz*Multiple rows were found for one_or_none())rFrc�orm_exc�MultipleResultsFound)r.r^r�s r0�one_or_nonezQuery.one_or_nonek
sR��0�4�j�j����H�H����6�6��q�6�M�
�!�V�V��4��.�<���
r2c��� |���}|�tjd���|S#tj$r3}t jtjd��|���Yd}~dSd}~wwxYw)aBReturn exactly one result or raise an exception.
Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects
no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
if multiple object identities are returned, or if multiple
rows are returned for a query that returns only scalar values
as opposed to full identity-mapped entities.
Calling :meth:`.one` results in an execution of the underlying query.
.. seealso::
:meth:`_query.Query.first`
:meth:`_query.Query.one_or_none`
NzNo row was found for one()z"Multiple rows were found for one()rB)rcra�
NoResultFoundrbr rI)r.r^rQs r0�onez Query.one�
s���$ ��"�"�$�$�C��{��+�,H�I�I�I��J���+� � � ��K��,�8���!$�
�
�
�
�
�
�
�
�
�
����� ���s�.�A0�(A+�+A0c�� |���}t|t��s|S|dS#tj$rYdSwxYw)a4Return the first element of the first result or None
if no rows present. If multiple rows are returned,
raises MultipleResultsFound.
>>> session.query(Item).scalar()
<Item>
>>> session.query(Item.id).scalar()
1
>>> session.query(Item.id).filter(Item.id < 0).scalar()
None
>>> session.query(Item.id, Item.name).scalar()
1
>>> session.query(func.count(Parent.id)).scalar()
20
This results in an execution of the underlying query.
rN)rfr^rararer]s r0�scalarzQuery.scalar�
sY��& ��(�(�*�*�C��c�5�)�)�
��
��q�6�M���$� � � ��4�4� ���s�*5�5�A�Ac��|���}d|j_|jr |js|j���|�|��Sr�)r�r��
use_labelsrZr�r+�_execute_and_instances)r.�contexts r0�__iter__zQuery.__iter__�
sZ���'�'�)�)��'+���$��?� &�4�#:� &��L�#�#�%�%�%��*�*�7�3�3�3r2c��|���} |jr |�||jj��nd}n#tj$rd}YnwxYwt
|j�|����Sr=) r�r+�_get_bind_args�get_bindrZ�UnboundExecutionErrorr�r��compile)r.rl�binds r0�__str__z
Query.__str__�
s����'�'�)�)�� ��<���#�#�G�T�\�-B�C�C�C��
�D��
�+� � � ��D�D�D� �����7�$�,�,�T�2�2�3�3�3s�)A�A�Ac�\�|jjdi|��}|jr|jdi|j��}|Sr6)r+�
connectionr%r�)r.�kw�conns r0�_connection_from_sessionzQuery._connection_from_session�
sH��&�t�|�&�,�,��,�,���"� E�)�4�)�D�D�D�,C�D�D�D��r2c��|�||jd���}|�|j|j��}tj|j||��S)NT)�close_with_result)rory�executer�r�r� instances�query)r.�querycontextrx�results r0rkzQuery._execute_and_instances�
sX���"�"��$�7�4�#�
�
�����l�4�d�l�C�C��� ��!3�V�\�J�J�Jr2c�h�|�||d���}|�||j��S)NT)rAr�r{)ryr|r�)r.r�rArxs r0�
_execute_crudzQuery._execute_crud�
s;���,�,��$�$�-�
�
���|�|�D�$�,�/�/�/r2c�F�|d|���|jd�|��S)N)rAr�r))r�r�)r.rr�rws r0rozQuery._get_bind_args�
s<���r�
��$�$�&�&�|�/E�
�
�IK�
�
�
r2c�8�d�d�|jD��D��S)aReturn metadata about the columns which would be
returned by this :class:`_query.Query`.
Format is a list of dictionaries::
user_alias = aliased(User, name='user2')
q = sess.query(User, User.id, user_alias)
# this expression:
q.column_descriptions
# would return:
[
{
'name':'User',
'type':User,
'aliased':False,
'expr':User,
'entity': User
},
{
'name':'id',
'type':Integer(),
'aliased':False,
'expr':User.id,
'entity': User
},
{
'name':'user2',
'type':User,
'aliased':True,
'expr':user_alias,
'entity': user_alias
}
]
c��g|]J\}}|j|jt|dd��|j|j�|jst|dd��ndd���KS)r@FNrL)r�r�rrPrL)�_label_namer�r�rPr�r�)r�r;�insp_ents r0r�z-Query.column_descriptions.<locals>.<listcomp>s���
�
�
���X�����"�8�-?��G�G����?�.� �2�/�"�(�H�d�;�;�;��
�
�
�
�
r2c�L�g|]!}||j�t|j��ndf��"Sr=)r�r)r��_ents r0r�z-Query.column_descriptions.<locals>.<listcomp>*sP��
"�
"�
"��� �+�7� �� 0�1�1�1�!��
"�
"�
"r2r�r�s r0�column_descriptionszQuery.column_descriptions�
sA��P
�
�
"�
"�!�N�
"�
"�
"�
�
�
�
r2c�T�|}|�t|��}tj|||��S)aGiven a ResultProxy cursor as returned by connection.execute(),
return an ORM result as an iterator.
e.g.::
result = engine.execute("select * from users")
for u in session.query(User).instances(result):
print u
)r'rr})r.�cursor�_Query__contextrls r0r}zQuery.instances7s0�����?�"�4�(�(�G�� ��v�w�7�7�7r2c�.�tj|||��S)akMerge a result into this :class:`_query.Query` object's Session.
Given an iterator returned by a :class:`_query.Query`
of the same structure
as this one, return an identical iterator of results, with all mapped
instances merged into the session using :meth:`.Session.merge`. This
is an optimized method which will merge all mapped instances,
preserving the structure of the result rows and unmapped columns with
less method overhead than that of calling :meth:`.Session.merge`
explicitly for each value.
The structure of the results is determined based on the column list of
this :class:`_query.Query` - if these do not correspond,
unchecked errors
will occur.
The 'load' argument is the same as that of :meth:`.Session.merge`.
For an example of how :meth:`_query.Query.merge_result` is used, see
the source code for the example :ref:`examples_caching`, where
:meth:`_query.Query.merge_result` is used to efficiently restore state
from a cache back into a target :class:`.Session`.
)r�merge_result)r.�iterator�loads r0r�zQuery.merge_resultGs��4�#�D�(�D�9�9�9r2c�`�|j|j|j|j|j|jpd|jd�S)N)rLrNr�rRrUr�r�)r�r�r�rxryr�rwr�s r0�_select_argszQuery._select_argscs;���[��l���������.�$��l�
�
�
r2c���|j}|�d��dupB|�d��dup+|�dd��p|�dd��S)NrLrNr�Fr�)r�rvr�s r0�_should_nest_selectablezQuery._should_nest_selectableosj���"���J�J�w���t�+�
-��z�z�(�#�#�4�/�
-��z�z�*�e�,�,�
-��z�z�*�e�,�,�
r2c���tj|�d���tjd�������j�dg����S)a�A convenience method that turns a query into an EXISTS subquery
of the form EXISTS (SELECT 1 FROM ... WHERE ...).
e.g.::
q = session.query(User).filter(User.name == 'fred')
session.query(q.exists())
Producing SQL similar to::
SELECT EXISTS (
SELECT 1 FROM users WHERE users.name = :name_1
) AS anon_1
The EXISTS construct is usually used in the WHERE clause::
session.query(User.id).filter(q.exists()).scalar()
Note that some databases such as SQL Server don't allow an
EXISTS expression to be present in the columns clause of a
SELECT. To select a simple boolean value based on the exists
as a WHERE, use :func:`.literal`::
from sqlalchemy import literal
session.query(literal(True)).filter(q.exists()).scalar()
F�1r)r�existsr�r��literal_columnr�r��with_only_columnsr�s r0r�zQuery.existsys^��F�z��"�"�5�)�)�
�[��+�C�0�0�
1�
1�
�[�]�]�
�(�(�!��-�-�
�
�
r2c��tj�tjd����}|�|�����S)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)))
r�)r�funcr'r�rqrh)r.�cols r0r'zQuery.count�sA��n�h�n�n�S�/��4�4�5�5���~�~�c�"�"�)�)�+�+�+r2�evaluatec�x�tj�||��}|���|jS)afPerform a bulk delete query.
Deletes rows matched by this query from the database.
E.g.::
sess.query(User).filter(User.age == 25).\
delete(synchronize_session=False)
sess.query(User).filter(User.age == 25).\
delete(synchronize_session='evaluate')
.. warning:: The :meth:`_query.Query.delete`
method is a "bulk" operation,
which bypasses ORM unit-of-work automation in favor of greater
performance. **Please read all caveats and warnings below.**
:param synchronize_session: chooses the strategy for the removal of
matched objects from the session. Valid values are:
``False`` - don't synchronize the session. This option is the most
efficient and is reliable once the session is expired, which
typically occurs after a commit(), or explicitly using
expire_all(). Before the expiration, objects may still remain in
the session which were in fact deleted which can lead to confusing
results if they are accessed via get() or already loaded
collections.
``'fetch'`` - performs a select query before the delete to find
objects that are matched by the delete query and need to be
removed from the session. Matched objects are removed from the
session.
``'evaluate'`` - Evaluate the query's criteria in Python straight
on the objects in the session. If evaluation of the criteria isn't
implemented, an error is raised.
The expression evaluator currently doesn't account for differing
string collations between the database and Python.
:return: the count of rows matched as returned by the database's
"row count" feature.
.. warning:: **Additional Caveats for bulk query deletes**
* This method does **not work for joined
inheritance mappings**, since the **multiple table
deletes are not supported by SQL** as well as that the
**join condition of an inheritance mapper is not
automatically rendered**. Care must be taken in any
multiple-table delete to first accommodate via some other means
how the related table will be deleted, as well as to
explicitly include the joining
condition between those tables, even in mappings where
this is normally automatic. E.g. if a class ``Engineer``
subclasses ``Employee``, a DELETE against the ``Employee``
table would look like::
session.query(Engineer).\
filter(Engineer.id == Employee.id).\
filter(Employee.name == 'dilbert').\
delete()
However the above SQL will not delete from the Engineer table,
unless an ON DELETE CASCADE rule is established in the database
to handle it.
Short story, **do not use this method for joined inheritance
mappings unless you have taken the additional steps to make
this feasible**.
* The polymorphic identity WHERE criteria is **not** included
for single- or
joined- table updates - this must be added **manually** even
for single table inheritance.
* The method does **not** offer in-Python cascading of
relationships - it is assumed that ON DELETE CASCADE/SET
NULL/etc. is configured for any foreign key references
which require it, otherwise the database may emit an
integrity violation if foreign key references are being
enforced.
After the DELETE, dependent objects in the
:class:`.Session` which were impacted by an ON DELETE
may not contain the current state, or may have been
deleted. This issue is resolved once the
:class:`.Session` is expired, which normally occurs upon
:meth:`.Session.commit` or can be forced by using
:meth:`.Session.expire_all`. Accessing an expired
object whose row has been deleted will invoke a SELECT
to locate the row; when the row is not found, an
:class:`~sqlalchemy.orm.exc.ObjectDeletedError` is
raised.
* The ``'fetch'`` strategy results in an additional
SELECT statement emitted and will significantly reduce
performance.
* The ``'evaluate'`` strategy performs a scan of
all matching objects within the :class:`.Session`; if the
contents of the :class:`.Session` are expired, such as
via a proceeding :meth:`.Session.commit` call, **this will
result in SELECT queries emitted for every matching object**.
* The :meth:`.MapperEvents.before_delete` and
:meth:`.MapperEvents.after_delete`
events **are not invoked** from this method. Instead, the
:meth:`.SessionEvents.after_bulk_delete` method is provided to
act upon a mass DELETE of entity rows.
.. seealso::
:meth:`_query.Query.update`
:ref:`inserts_and_updates` - Core SQL tutorial
)r �
BulkDelete�factory�exec_�rowcount)r.�synchronize_session� delete_ops r0�deletezQuery.delete�s7��p �*�2�2�4�9L�M�M� ��������!�!r2c��|pi}tj�||||��}|���|jS)a�Perform a bulk update query.
Updates rows matched by this query in the database.
E.g.::
sess.query(User).filter(User.age == 25).\
update({User.age: User.age - 10}, synchronize_session=False)
sess.query(User).filter(User.age == 25).\
update({"age": User.age - 10}, synchronize_session='evaluate')
.. warning:: The :meth:`_query.Query.update`
method is a "bulk" operation,
which bypasses ORM unit-of-work automation in favor of greater
performance. **Please read all caveats and warnings below.**
:param values: a dictionary with attributes names, or alternatively
mapped attributes or SQL expressions, as keys, and literal
values or sql expressions as values. If :ref:`parameter-ordered
mode <updates_order_parameters>` is desired, the values can be
passed as a list of 2-tuples;
this requires that the
:paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
flag is passed to the :paramref:`.Query.update.update_args` dictionary
as well.
.. versionchanged:: 1.0.0 - string names in the values dictionary
are now resolved against the mapped entity; previously, these
strings were passed as literal column names with no mapper-level
translation.
:param synchronize_session: chooses the strategy to update the
attributes on objects in the session. Valid values are:
``False`` - don't synchronize the session. This option is the most
efficient and is reliable once the session is expired, which
typically occurs after a commit(), or explicitly using
expire_all(). Before the expiration, updated objects may still
remain in the session with stale values on their attributes, which
can lead to confusing results.
``'fetch'`` - performs a select query before the update to find
objects that are matched by the update query. The updated
attributes are expired on matched objects.
``'evaluate'`` - Evaluate the Query's criteria in Python straight
on the objects in the session. If evaluation of the criteria isn't
implemented, an exception is raised.
The expression evaluator currently doesn't account for differing
string collations between the database and Python.
:param update_args: Optional dictionary, if present will be passed
to the underlying :func:`_expression.update`
construct as the ``**kw`` for
the object. May be used to pass dialect-specific arguments such
as ``mysql_limit``, as well as other special arguments such as
:paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`.
.. versionadded:: 1.0.0
:return: the count of rows matched as returned by the database's
"row count" feature.
.. warning:: **Additional Caveats for bulk query updates**
* The method does **not** offer in-Python cascading of
relationships - it is assumed that ON UPDATE CASCADE is
configured for any foreign key references which require
it, otherwise the database may emit an integrity
violation if foreign key references are being enforced.
After the UPDATE, dependent objects in the
:class:`.Session` which were impacted by an ON UPDATE
CASCADE may not contain the current state; this issue is
resolved once the :class:`.Session` is expired, which
normally occurs upon :meth:`.Session.commit` or can be
forced by using :meth:`.Session.expire_all`.
* The ``'fetch'`` strategy results in an additional
SELECT statement emitted and will significantly reduce
performance.
* The ``'evaluate'`` strategy performs a scan of
all matching objects within the :class:`.Session`; if the
contents of the :class:`.Session` are expired, such as
via a proceeding :meth:`.Session.commit` call, **this will
result in SELECT queries emitted for every matching object**.
* The method supports multiple table updates, as detailed
in :ref:`multi_table_updates`, and this behavior does
extend to support updates of joined-inheritance and
other multiple table mappings. However, the **join
condition of an inheritance mapper is not
automatically rendered**. Care must be taken in any
multiple-table update to explicitly include the joining
condition between those tables, even in mappings where
this is normally automatic. E.g. if a class ``Engineer``
subclasses ``Employee``, an UPDATE of the ``Engineer``
local table using criteria against the ``Employee``
local table might look like::
session.query(Engineer).\
filter(Engineer.id == Employee.id).\
filter(Employee.name == 'dilbert').\
update({"engineer_type": "programmer"})
* The polymorphic identity WHERE criteria is **not** included
for single- or
joined- table updates - this must be added **manually**, even
for single table inheritance.
* The :meth:`.MapperEvents.before_update` and
:meth:`.MapperEvents.after_update`
events **are not invoked from this method**. Instead, the
:meth:`.SessionEvents.after_bulk_update` method is provided to
act upon a mass UPDATE of entity rows.
.. seealso::
:meth:`_query.Query.delete`
:ref:`inserts_and_updates` - Core SQL tutorial
)r �
BulkUpdater�r�r�)r.r�r��update_args� update_ops r0r�zQuery.updateYsL��D"�'�R���*�2�2��%�v�{�
�
� � �������!�!r2c���|jjr0|jjD]#}||��}|�||ur|}|jsd|_�$t|��}|j�|S||_|j|_|jD]}|�||���|j D]}|d}||g|dd��R��|j
rt|j
��|_|j
r|�|��|js/|jrt#jd���t#jd���|jr"|jr|�|��|_n|�|��|_|S)NFrrzyNo column-based properties specified for refresh operation. Use session.expire() to reload collections and related items.z4Query contains no columns with which to SELECT from.)�dispatch�before_compile�_bake_okr'r�r�rKr5�
setup_context�create_eager_joins�from_clauserF�fromsro�_adjust_for_single_inheritance�primary_columnsr�rZr��multi_row_eager_loadersr��_compound_eager_statement�_simple_statement)r.r�r�� new_queryrlrL�rec�strategys r0r�zQuery._compile_context�s����=�'� .��m�2�
.�
.���B�t�H�H� ��(�Y�d�-B�-B�$�D��;�.�(-��
���t�$�$����(��N����"&�"6����n� 0� 0�F�� � ��w�/�/�/�/��-� (� (�C��1�v�H��H�W�'�s�1�2�2�w�'�'�'�'�'��� 6�!��!4�5�5�G�M��#� 9��/�/��8�8�8��&�
��$�
��0�?�����0�M�����*� @�t�/K� @� $� >� >�w� G� G�G��� $� 6� 6�w� ?� ?�G���r2c�b�|jr tj|j|j��}n d|_g}t j|j|z|jf|j|j|jd�|j ��}|j
|_
|jD]}|j|�}�
|j
r|j|j
�}|���}|���}tj||��|_t j|g|jz|j���}|j
�|j
j�|j
|_
|}|j���D]}tj|||j��}�|�|��|jr'|j|j�|j���|j|j�|S)N�rkrjr�)rj)r�rE� expand_column_list_from_order_byr�r�selectrr�r�r�rKr�r�rTrXr`rerFrS�secondary_columnsr��eager_joinsr��splice_joins�stop_on�append_from�append_order_by�copy_and_process�eager_order_by) r.rl�order_by_col_expr�inner�hintrmr�r��
eager_joins r0r�zQuery._compound_eager_statements���
�� #� (� I��'��)9�!�!��� $�G�� "���
��#�&7�7���
��]��~��%�
�
���
�
��!(� 7����$� +� +�D�#�E�O�T�*�E�E��?� 6�#�E�O�T�_�5�E����
�
���"�"�$�$��"�0���?�?����J�
�G�g�/�/�G�N�
�
�
� �
�#�/��'�*�2�(/�(?�I�%���!�-�4�4�6�6� � �J�#�/��Z��);���K�K� ���k�*�*�*��� �%�I�%���1�1�'�2B�C�C�
�
� "� �!�7�#9�:�:��r2c��|jsd|_|jdur4|jr-|xjtj|j|j��z
c_|xjt
|j�����z
c_tj
|j|jz|jf|j|j
|jd�|j��}|j|_|jD]}|j|�}�
|jr|j|j�}|jr|j|j�|S)NTr�)r�r�r�rEr�r�rar�r�rr�r�rr�r�rKr�r�rTrXr�r�)r.rlr�r�s r0r�zQuery._simple_statementas?���� $�#�G���>�T�!�!�g�&6�!��#�#��9��%�w�'7�(9�(9�
9�#�#� �
�
��w�2�9�9�;�;�<�<�<�
�
��J��#�g�&?�?���
��]��~��%�
�
���
�
� �%,�$;� �!��$� 3� 3�D�+� �+�T�2�I�I��?� >�+� �+�T�_�=�I��!� ?�%�I�%�w�'=�>�>��r2c��t|j�����}|jrP|j|jvrBt |j��}|jr|j}nd}|�|j|fg��}|D]�\}}||jvr�|j j
}|�j|r|�|��}|�|dd��}tjtj�|j��|��|_��dS)amApply single-table-inheritance filtering.
For all distinct single-table-inheritance mappers represented in
the columns clause of this query, as well as the "select from entity",
add criterion to the WHERE
clause of the given QueryContext such that only the appropriate
subtypes are selected from the total results.
NF)r�r>r�rYrr@rIr&r*rA�_single_table_criterion�traverserr�and_�True_�_ifnoner)r.rlrzr�rSrM�single_crits r0r�z$Query._adjust_for_single_inheritances!���T�-�4�4�6�6�7�7���$� I��(��0H�H�H��4�3�4�4�D��$�
��-������\�\�D�$<�g�#F�"G�H�H�F�#)� � ��X�w��4�.�.�.��"�/�A�K��&��@�")�"2�"2�;�"?�"?�K�"�0�0��e�U�K�K��&)�h��I�%�%�g�&9�:�:�K�'�'��#�� � r2r=)TT)NNNNN)NFFr�)NN)r�)FFNFFr~)r�)r�N)�re�
__module__�__qualname__�__doc__rrr�r�r�r$r�r�rwr�rxryr�r�rKr�� frozensetrTr�r_r�rZr�r�r�rbr*rYr>r�rfr �
immutabledictrvr�r%r�r�r�r�ror�r��_path_registryrr7r�r�r1r-r9rDrnrqr{r�r
r�r�rr�r�r�rgr�r�r�r�r�rer�r�r�r�r�r�r�r�r�r�r�r�rrrGrrrr�rr�rrrrBr(rvr�PASSIVE_OFFr4r*rXr\r�r`rrjrlrqrtrnr��_valuesr
r�r��pending_deprecationr�r�r�r�r�r�r�r�r��
deprecatedr�r�r�rfr�r�r�r�r�r&r�r�r�r�r�rr�r�r�rrrrr�r8r<r>rIrArLrNr�rSrVrXr[r_rcrfrhrmrtryrkr�ror�r}r�r�r�r�r'r�r�r�r�r�r�r)r2r0r&r&>s�
��������, �������L��J��J��I��I��G��I��I��I��G�
�F��O��J�����J������N��J����N�"���I��N������O��O�/�T�/�1�1�1�I�
�+��+�-�-�� �d� �"�"�G�$�$�$�&�&�K��M��K����O�#��"�M� ���H���"�H%�%�%�%�@9�9�9�9�8-�-�-�>D�D�D�-1�-1�-1�^D�D�D�/�/�/�$
�
�
��[�]�]�&�&��]�&��[�]�]�%�%��]�%�+B�+B�+B�Z!�!�!�(�(�(�
�
�
�����X��
M�M�M����0�0�0�#�#�#�#����
�
�
�
L�L�L�����$A�A�A�A�+�+�+�
�
�
�
�
�
������
����(����
�
��X�
�"�"�"�"�@9
�9
�9
�9
�v C� C� C�C�C�C�� )� )��X� )�E�E�E��[�]�]�)�)��]�)��
�
��X�
�*�[�]�]�(�(��]�(�"
�
�
��[�]�]�!�!��]�!�4�[�]�]�(�(��]�(�*����X���[�]�]� "� "��]� "��[�,�-�-�>B�
�
�
�.�-�
�B�[�]�]�C
�C
��]�C
�JVB�VB�VB�x��&��
4M�4M�4M�4M�l=6�=6�=6�=6�~�[�]�]����]��:�[�]�]� "� "��]� "��[�]�]�'�'��]�'�&�[�]�]�(�(��]�(�5P�5P�5P�5P�n�[�]�]� *� *� *��]� *��[�]�]����]��2y�y�y�v�[�]�]�'�'��]�'��[�]�]�;�;��]�;�6����G�����[�]�]�%�%��]�%�4�[�]�]�
9�
9��]�
9��T��
�F�
���
(�(���
(�+�+�+�$*�*�*��[�]�]�
(�
(��]�
(����&�[�]�]�@�@�@��]�@�68�8�8�8�( '� '� '��[�]�]�H�H��]�H�"�[�]�]��T�_�
� 1���D�D����]�D�6�[�]�]������
8
�8
�8
��]�8
�t�[�]�]�$�$��]�$�(�[�(�*:�;�;�!,�!,�<�;�!,�F&%�&%�&%�P�[�(�*:�;�;�8�8�<�;�8�6�[�(�*:�;�;�8�8�<�;�8�4�[�(�*:�;�;� %� %�<�;� %�D)�)�)�
%2�%2�%2�N6�6�6�6�6�6�:�:�:�4�4�4�7�7�7�c
�c
�c
�J
�
�
�2
�
�
��[�(�*:�;�;�X�X�<�;�X�tK�K�K�Zf>�f>�f>�P@8�@8�@8�D`/�`/�`/�D"�"�"��[�(�)�)�
�
�*�)�
��[�,�-�-�./�./�.�-�./�`�[�,�-�-�p0�p0�.�-�p0�d6�6�6�:�[�(�)�)�+ �+ �*�)�+ �Z�[�(�)�)���*�)���[�(�)�)���*�)���[�(�)�)�&�&�*�)�&�>�[�]�]�&�&��]�&�<�[�]�]�&�&��]�&�*���$�[�,�-�-�$�$�.�-�$�<���:"�"�"�H���@���64�4�4�
4�
4�
4����K�K�K�0�0�0�
�
�
�
�=
�=
��X�=
�~8�8�8�8� :�:�:�:�8�
�
��X�
��
�
��X�
�(
�(
�(
�T8,�8,�8,�tz"�z"�z"�z"�xG"�G"�G"�G"�R4�4�4�4�lG�G�G�R���<"�"�"�"�"r2r&c�$�eZdZed���ZdS)r�c��|dvrdS|dkrd}d}n-|dkrdx}}n"|dkrd}d}ntjd|z���t||���S) Nr�r�TFr��
update_nowaitz"Unknown with_lockmode argument: %r)r�r�)rZr[r�)r.r�r�r�s r0r�zLockmodeArg.parse_legacy_query�s����=� � ��4��6�>�>��D��F�F�
�X�
�
�!�!�D�6�6�
�_�
$�
$��F��D�D��&�4�t�;���
���V�4�4�4�4r2N)rer�r��classmethodr�r)r2r0r�r��s-�������5�5��[�5�5�5r2r�c��eZdZdZd�Zd�ZdS)r4z:Represent an entity column returned within a Query result.c��|tur]|d}t|tj��st |��rt
}n$t|t��rt}nt}t�
|��S)Nr)r4r^r r�rr��Bundle�
_BundleEntityr��objectr�)r�rVr�rLs r0r�z_QueryEntity.__new__�sy���,����!�W�F��f�d�&7�8�8�
$�=M��>�>�
$�$����F�F�+�+�
$�#���#���~�~�c�"�"�"r2c��|j�|j��}|j���|_|Sr=r�r�s r0r�z_QueryEntity._clone�s3���N�"�"�4�>�2�2���]�'�'�)�)��
��r2N)rer�r�r�r�r�r)r2r0r4r4�s8������D�D�#�#�#�����r2r4c�|�eZdZdZd�ZdZdZd�Zd�Ze d���Z
e d���Zd�Zd �Z
d
�Zd�Zd�Zd
�ZdS)r�z mapper/class/AliasedClass entityc��|js||_|j�|��d|_|g|_||_dSr�)r6r5r\r7r/rP)r.r~rLs r0r1z_MapperEntity.__init__�sG���$� )�$(�E�!�
����t�$�$�$�%)��"����
��� � � r2Tc��|j|_||_|j|_|j|_|j|_|j|_||_|jr|jj |_
n|jjj|_
|jj
|_dSr=)rArNrGr@�with_polymorphic_mappers�_with_polymorphicr�_polymorphic_discriminatorr�r�r�rMrer�r�r.rMrNs r0rJz_MapperEntity.setup_entity�s����o���.���"�-��� (� 9���!)�!B���*2�*A��'�#����$� ;�#�/�4�D���#�{�1�:�D���$�3�� � � r2c�D�|jrtd���|�|�|j��dS|j�||��\}}||_||_||_|�|jtj
||jj����dS)z�Receive an update from a call to
:meth:`_query.Query.with_polymorphic`.
Note the newer style of using a free standing
``with_polymporphic()`` construct doesn't make use of this method.
z6Can't use with_polymorphic() against an Aliased objectN)r@�NotImplementedErrorrqrA�_with_polymorphic_argsr�r�rGrDrErFrH)r.r~r rGr�mappersrks r0rz"_MapperEntity.set_with_polymorphic�s���� � �%�K���
��!��,�,�T�[�9�9�9��F� �K�>�>��J�
�
����")���*8��'�"���
�0�0��K��"�8�T�[�-L�M�M�
�
�
�
�
r2c��|jjSr=)rArMr�s r0r�z_MapperEntity.types
���{�!�!r2c��|jSr=)r�r�s r0rz'_MapperEntity.entity_zero_or_selectables����r2c�,�t|j|��Sr=)rr��r.rLs r0r"z_MapperEntity.corresponds_tos��%�d�&6��?�?�?r2c�:�|j�|��dSr=)r5r\)r.r~�sels r0rzz!_MapperEntity.adapt_to_selectables��
����t�$�$�$�$�$r2c���d}|js(|jr |j�|jd��}n|j}|r%|jr|�|j��}n
|}n|j}|Sr=)r@r,rvrArNrf�wrap)r.r~rlrSr^s r0�_get_entity_clausesz!_MapperEntity._get_entity_clausess~�����$� +��*�
M��5�9�9�$�+�t�L�L����*�G�� (��$�
��l�l�5�#8�9�9�������'�C��
r2c
��|�||��}|jr|r|�|j��}n |s|j}|s0|jjr$tj|j|jj��}|j |ur|j
}|j}ndx}}tj
|j|||j||||j���}||jfS)N)r�r��polymorphic_discriminator)r�rSr�rA�_requires_row_aliasingrErFrGrHr6r�r�r�_instance_processorrr�r�)r.r~rlr�rSr�r�� _instances r0�
row_processorz_MapperEntity.row_processor0s����*�*�5�'�:�:���?� &�w� &��l�l�7�?�3�3�G�G�� &��o�G�
� �4�;�=� ��,�����!@���G�� �D�(�(�#�4�O�#�1�M�M�.2�2�O�m��/��K����I��+�'�&*�&E�
�
�
� ��$�*�*�*r2c��|�||��}|xj|jfz
c_|jdurP|jjrD|jj|_|r1|�t
j|j����|_tj ||j||j
||j|j|j
|j�� � dS)NF)rBr�r�)r�r�rGr�rA�
adapt_listr r8r�_setup_entity_queryrr�r�r�r�)r.r~rlrSs r0r�z_MapperEntity.setup_contextSs����*�*�5�'�:�:�� �
�
�$�/�+�+�
�
���u�$�$���)=�$�#�{�3�G���
�#*�#5�#5��L��!1�2�2�$�$�� � �#���K���I���#�!�3�!�2�&*�&E�
�
�
�
�
�
r2c�*�t|j��Sr=)r�rAr�s r0rtz_MapperEntity.__str__n����4�;���r2N)rer�r�r�r1r
�use_id_for_hashrJrrgr�rr"rzr�rr�rtr)r2r0r�r��s�������*�*����"���O�4�4�4�
�
�
�B�"�"��X�"�� � ��X� �@�@�@�%�%�%����(!+�!+�!+�F
�
�
�6 � � � � r2r�c�d�eZdZdZdZ dZdZdZd�ZdZ dZ
d�Zd�Ze
d���Zd�Zd �ZdS)
r�aMA grouping of SQL expressions that are returned by a
:class:`_query.Query` under one namespace.
The :class:`.Bundle` essentially allows nesting of the tuple-based
results returned by a column-oriented :class:`_query.Query` object.
It also
is extensible via simple subclassing, where the primary capability
to override is that of how the set of expressions should be returned,
allowing post-processing as well as custom return types, without
involving ORM identity-mapped classes.
.. versionadded:: 0.9.0
.. seealso::
:ref:`bundles`
Fc���|x|_|_||_t��x|_|_|j�d�|D����|�d|j��|_dS)aQConstruct a new :class:`.Bundle`.
e.g.::
bn = Bundle("mybundle", MyClass.x, MyClass.y)
for row in session.query(bn).filter(
bn.c.x == 5).filter(bn.c.y == 4):
print(row.mybundle.x, row.mybundle.y)
:param name: name of the bundle.
:param \*exprs: columns or SQL expressions comprising the bundle.
:param single_entity=False: if True, rows for this :class:`.Bundle`
can be returned as a "single entity" outside of any enclosing tuple
in the same manner as a mapped entity.
c3�FK�|]}t|d|j��|fV��dS)r3N)r��_label)r�r�s r0r=z"Bundle.__init__.<locals>.<genexpr>�sF����
�
�7:�W�S�%���
,�
,�c�2�
�
�
�
�
�
r2�
single_entityN) r�r
�exprsr#r<r�r�rpr)r.r�rrws r0r1zBundle.__init__�s���$#'�&�� �D�K���
� 0� 2� 2�2���������
�
�>C�
�
�
�
�
�
� �V�V�O�T�5G�H�H����r2Nc��|j�|j��}|j�|j��|Sr=)r�r�r�r�)r.�cloneds r0r�z
Bundle._clone�s6����'�'���7�7������t�}�-�-�-��
r2c�.�tj|jddi�S)N�groupF)r!�
ClauseListrr�s r0rzBundle.__clause_element__�s���$�4�:�>�5�>�>�>r2c�4�|���jSr=)rr�r�s r0r�zBundle.clauses�s���&�&�(�(�0�0r2c�<�|���}||_|S)z<Provide a copy of this :class:`.Bundle` passing a new label.)r�r�)r.r�rs r0rzBundle.label�s������������
r2c�@���tjd|�����fd�}|S)z�Produce the "row processing" function for this :class:`.Bundle`.
May be overridden by subclasses.
.. seealso::
:ref:`bundles` - includes an example of subclassing.
r�c�4�����fd��D����S)Nc�&��g|]
}|�����Sr)r))r��proc�rows �r0r�z=Bundle.create_row_processor.<locals>.proc.<locals>.<listcomp>�s!���<�<�<�d���S� � �<�<�<r2r))r�keyed_tuple�procss`��r0rz)Bundle.create_row_processor.<locals>.proc�s)�����;�<�<�<�<�e�<�<�<�=�=�=r2)r �lightweight_named_tuple)r.r~rr�rrs ` @r0�create_row_processorzBundle.create_row_processor�s=�����2�8�V�D�D�� >� >� >� >� >� >��r2)rer�r�r�rr�rXr@r1r�r<r�rrgr�rrr)r2r0r�r�rs���������&�M�<����I���I�I�I�4�G��0
�A�/����
?�?�?��1�1��X�1��������r2r�c��eZdZdZdd�Zed���Zed���Zed���Zd�Z ed���Z
d �Zd
�Zd�Z
d�Zd
S)r�FTc�J�|j�|��|x|_|_t |��|_|j|_g|_|r@|jD]8}t|t��rt||���(t||���9|jj|_
dSr=)r5r\�bundlerPr�r�r�rr^r�r�r�rr
)r.r~r�setup_entitiesrPs r0r1z_BundleEntity.__init__�s���
����t�$�$�$�"(�(���d�i���L�L�� �!�;������� .���
.�
.���d�F�+�+�.�!�$��-�-�-�-�!�$��-�-�-�-�&*�k�&?��#�#�#r2c�&�|j}|�|jSdSr=)r�rA)r.r�s r0rAz_BundleEntity.mapper�s��� �����<���4r2c�R�g}|jD]}|�|j���|Sr=)r5�extendr/)r.r/r;s r0r/z_BundleEntity.entitiess4�����>� *� *�C��O�O�C�L�)�)�)�)��r2c�4�|jD]}|j}|�|cS�dSr=)r5r��r.r;r�s r0r�z_BundleEntity.entity_zeros5���>� � �C��O�E�� �����!��4r2c��dSr�r)r�s r0r"z_BundleEntity.corresponds_tos ���ur2c�4�|jD]}|j}|�|cS�dSr=)r5rr%s r0rz'_BundleEntity.entity_zero_or_selectables6���>� � �C��1�E�� �����!��4r2c�t�t||jd���}|jD]}|�||���dS)NF)r )r�rr5rz)r.r~r�r<r;s r0rzz!_BundleEntity.adapt_to_selectable%sN���%���U�C�C�C��
�>� ,� ,�C��#�#�A�s�+�+�+�+� ,� ,r2c�F�|jD]}|�||���dSr=)r5rJ)r.rMrNr;s r0rJz_BundleEntity.setup_entity.s6���>� 8� 8�C����X��7�7�7�7� 8� 8r2c�F�|jD]}|�||���dSr=)r5r�)r.r~rlr;s r0r�z_BundleEntity.setup_context2s6���>� .� .�C����e�W�-�-�-�-� .� .r2c�����t���fd�|jD���\}}|j��||��}||jfS)Nc�>��g|]}|��������Sr))r)r�r;rlr~r�s ���r0r�z/_BundleEntity.row_processor.<locals>.<listcomp>8s;��������!�!�%��&�9�9���r2)�zipr5rrr�)r.r~rlr�rr�rs ``` r0rz_BundleEntity.row_processor6sn�������������>����
�
��v��{�/�/��u�f�E�E���T�%�%�%r2Nr~)rer�r�rr1rgrAr/r�r"rrzrJr�rr)r2r0r�r��s��������O�@�@�@�@� ����X������X������X�����
����X��,�,�,�8�8�8�.�.�.�
&�
&�
&�
&�
&r2r�c�X�eZdZdZdd�ZdZed���Zd�Zd�Z d�Z
d �Zd
�Zd�Z
dS)
r�zColumn/expression based entity.Nc�>�
�||_||_d}d}t|tj��r;tjd��t
j|��}|j|_ d}d}d}n�t|tjtj
f��r^t|dd��}|�d}|j|_ |���}d}t|t"��rt%||��dSt|tj��sLt)|d��r$|jD]}||urnt-|||����dSt/jd|�d����|st|d d��|_ d}|jx|_}|j|_|js+t|d
d��s|�|j ��}|j�|��||_ tC��|_"tG|j$��|_%tC|j%���
|sG||_&|r|g|_'|j(|_(ng|_'d|_(tC|j'��|_)dSd�tUj+|d���D��} tj,d
�| D����|_'tC�
fd�| D����|_)|j'r%|j'd|_&|j&j(|_(dS|j�|j|_&d|_(dSd|_&d|_(dS)NTFz�Plain string expression passed to Query() should be explicitly declared using literal_column(); automatic coercion of this value will be removed in SQLAlchemy 1.4r��_select_iterable)� namespacez9SQL expression, column, or mapped entity expected - got 'rbr3�
is_literalc�$�g|]
}d|jv�|��S�rsr��r�r�s r0r�z*_ColumnEntity.__init__.<locals>.<listcomp>�s4������"�T�%6�6�6� �7�6�6r2)�include_scalar_selectsc�:�g|]}d|jv�|jd��Sr4r�r5s r0r�z*_ColumnEntity.__init__.<locals>.<listcomp>�s8������%��):�:�:��%�n�5�:�:�:r2c�p��g|]2}d|jv���|j���%|jd��3Sr4)ru�intersection�
_from_objects)r�r��actual_fromss �r0r�z*_ColumnEntity.__init__.<locals>.<listcomp>�sR�������%��):�:�:�$�1�1�$�2D�E�E�;��%�n�5�:�:�:r2r)-rPr1r^r r��warn_deprecatedrr�r�r�rrrr�r�r3�_query_clause_elementr�r��
ColumnElementrWr0r�rZr�r��hashablerr
rr5r\r�r�r�rFr:r;r�r/rA�_from_entitiesrE�surface_column_elements�unique_list)r.r~r�r1�search_entities�check_column�_entityr<�type_�all_elementsr;s @r0r1z_ColumnEntity.__init__Fs������ �"��������f�d�/�0�0� �� �!�
�
�
��'��/�/�F�%�{�D��#�O��L��G�G�
��Z�2�J�4M�N�
�
� ��f�o�t�<�<�G��"�"'��%�z�D���1�1�3�3�F��L��&�&�)�)�
��e�V�,�,�,����&�#�"3�4�4� #��v�1�2�2�
� �0���A��F�{�{���!�%��f�=�=�=�=�=��F��,�,�)/���2���
�� #�&�v�u�d�;�;�D��"�O�"�K�'�� �E�#(�>�1����}� 4�W�V�\�5�%I�%I� 4��\�\�$�"2�3�3�F�
����t�$�$�$�����U�U��
�!��!5�6�6����4�,�-�-���* #�&�D���
#�!(� ��
�%�n���� "��
�"���"%�d�m�"4�"4�D������$�<��5�������L�!�,��� ,������D�M�#&����� ,����#�#�D���}�
#�#'�=��#3�� �"�.�5�������+�#'�>�� �"�����#'�� �"����r2Fc�J�|j�|jS|jr
|jdSdS)Nr)r�r;r�s r0rz'_ColumnEntity.entity_zero_or_selectable�s2����'��#�#�
�
� ��$�Q�'�'��4r2c��t||�|j����}|j|_|j|_|j|_dSr=)r��corresponding_columnr�r�r�r/)r.r~r�r<s r0rzz!_ColumnEntity.adapt_to_selectable�sB���%��!9�!9�$�+�!F�!F�G�G���(��
��(��
��]��
�
�
r2c���d|jvr|j|_t|j���|jj��r!|j�|j��dSdS)NrG)r�rGr�r;r9r:r��addr�s r0rJz_ColumnEntity.setup_entity�sn���t�}�,�,�&�1�D�O��t� �!�!�.�.���-�
�
� 0�
�J�N�N�8�.�/�/�/�/�/� 0� 0r2c��|j�dSt|��r ||juSt|j��o|�|j��Sr�)r�rr)r�s r0r"z_ColumnEntity.corresponds_to�sd����#��5�
�v�
&�
&� 9��T�-�-�-�(�� ����9��&�&�t�'7�8�8�
9r2c��d|f|jvr|jd|f}n|�|jdd��}|jr|���}|jr|jj|}|�|��}||jfS)N�fetch_columnFT) rrr�ru�_deannotaterSr��_getterr�)r.r~rlr�r��getters r0rz_ColumnEntity.row_processor�s����D�!�W�%7�7�7��'���(>�?�F�F��(�(���e�T�B�B�F��� *��'�'�)�)�F��?� 5��_�,�V�4�F�����'�'���t�'�'�'r2c��|�|jdd��}|jr|���}|xjt|j��z
c_|j�|��||jd|f<dS)NFTrO) rr�rurPr�rar�r\r)r.r~rlr�s r0r�z_ColumnEntity.setup_context�s����$�$�T�[�%��>�>���� *��'�'�)�)�F��
�
��t�z�*�*�*�
�
���&�&�v�.�.�.�5;���N�D�1�2�2�2r2c�*�t|j��Sr=)r�r�r�s r0rtz_ColumnEntity.__str__rr2r=)rer�r�r�r1r
rgrrzrJr"rr�rtr)r2r0r�r�Cs�������)�)�v#�v#�v#�v#�p#��
����X��#�#�#�0�0�0� 9� 9� 9�(�(�(�"<�<�<� � � � � r2r�c��eZdZdZd�ZdS)r')r�rSr��
for_updater~r+r\r��invoke_all_eagersr�r�r�r�r�r�r��propagate_optionsrr�r�rr�r�rK�runid�partials�post_load_pathsr�c��|j�ct|jtj��r7|jjs+|jjs|j���|_n8|j|_n+d|_|j|_ |j
|_|j|_
d|_d|_d|_d|_||_|j|_|j|_|j|_|j|_|j|_|j|_g|_g|_g|_ i|_!g|_"tGd�|j$D����|_%|j&�'��|_(|j�|j)|_*dSd|_*dS)NFr)c3�(K�|]
}|j� |V��dSr=)�propagate_to_loaders)r�r�s r0r=z(QueryContext.__init__.<locals>.<genexpr>Fs>����%
�%
��a�.D�%
�
�%
�%
�%
�%
�%
�%
r2)+r�r^r!r_�_textualrj�apply_labelsr�rbr�r�rr�r�r�rSr�rVr~r+rZr\r�r�r_rWr�r�r�r�r�r�r�r�r�r�r�rXr�r?rr�r�)r.r~s r0r1zQueryContext.__init__%s�����'��5�+�Z�-B�C�C�
2��(�1�
2��(�3�
2�
"'�!1�!>�!>�!@�!@����!&�!1����!�D�N�$��D��$�/�D��!�O�D�M�',��$������
������
��}����)���!&�!9���!&�!9���"�1���"�1���!���!#��� ������"$���!$�%
�%
��*�%
�%
�%
�"
�"
��� �+�0�0�2�2�����)�"'�"?�D����"&�D���r2N)rer�r�� __slots__r1r)r2r0r'r's*�������I�>('�('�('�('�('r2r'c��eZdZd�Zd�ZdS)�AliasOptionc��||_dS)a"Return a :class:`.MapperOption` that will indicate to the
:class:`_query.Query` that the main table has been aliased.
This is a seldom-used option to suit the
very rare case that :func:`.contains_eager`
is being used in conjunction with a user-defined SELECT
statement that aliases the parent table. E.g.::
# define an aliased UNION called 'ulist'
ulist = users.select(users.c.user_id==7).\
union(users.select(users.c.user_id>7)).\
alias('ulist')
# add on an eager load of "addresses"
statement = ulist.outerjoin(addresses).\
select().apply_labels()
# create query, indicating "ulist" will be an
# alias for the main table, "addresses"
# property should be eager loaded
query = session.query(User).options(
contains_alias(ulist),
contains_eager(User.addresses))
# then get results via the statement
results = query.from_statement(statement).all()
:param alias: is the string name of an alias, or a
:class:`_expression.Alias` object representing
the alias.
N)r`)r.r`s r0r1zAliasOption.__init__Qs��B��
�
�
r2c���t|jtj��r2|���j�|j��}n|j}t
j|��|_dSr=) r^r`r r�r�rCrErFrf)r.r~r`s r0r�zAliasOption.process_queryts_���d�j�$�"3�4�4� ��&�&�(�(�;�A�A�$�*�M�M�E�E��J�E� (� 6�u� =� =����r2N)rer�r�r1r�r)r2r0rcrcPs3������!�!�!�F>�>�>�>�>r2rcN);r�� itertoolsr�rrrarrr r
�baserr
rrrr�
path_registryrr rrrrrrrrrZrrrrr!rEr"�sql.baser#�sql.expressionr$�sql.selectabler%�__all__�rootr��_self_inspects�class_loggerr�r&r�r4r�r�r�r�r'�MapperOptionrcr)r2r0�<module>rrsl����������������������������������������������$�$�$�$�$�$�������#�#�#�#�#�#�"�"�"�"�"�"������� � � � � � �'�'�'�'�'�'�(�(�(�(�(�(�������������"�"�"�"�"�"�������������������������������������������������������������"�"�"�"�"�"�������'�'�'�'�'�'�/�/�/�/�/�/�)�)�)�)�)�)�
.�
.�
.���"������aA�aA�aA�aA�aA�F�aA�aA�����aA�HC5�5�5�5�5�,�5�5�5�,�����6����,_ �_ �_ �_ �_ �L�_ �_ �_ �D��v�v�v�v�v�^�v�v���v�rT&�T&�T&�T&�T&�L�T&�T&�T&�n � � � � �L� � � �DH'�H'�H'�H'�H'�6�H'�H'�H'�V)>�)>�)>�)>�)>�*�)�)>�)>�)>�)>�)>r2