o znh@sFdZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd l m Z dd l m Z dd l mZdd l mZddl mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlmZddl!m"Z"ddl!mZ#ddl!m$Z$dd l%m&Z&dd!l'm(Z(dd"l)m*Z*gd#Z+ej,Z-ej.e j/Gd$d%d%e0Z1Gd&d'd'e*Z2Gd(d)d)e0Z3Gd*d+d+e3Z4ej.Gd,d-d-eZ5Gd.d/d/e3Z6Gd0d1d1e3Z7Gd2d3d3e0Z8Gd4d5d5ej9Z:d6S)7aThe Query class and support. Defines the :class:`.Query` class, the central construct used by the ORM to construct database queries. The :class:`.Query` class should not be confused with the :class:`.Select` class, which defines database SELECT operations at the SQL (non-ORM) level. ``Query`` differs from ``Select`` in that it returns ORM-mapped objects and interacts with an ORM session, whereas the ``Select`` construct interacts directly with the database to return iterable result sets. )chain) attributes)exc) interfaces)loading) persistence) properties)_entity_descriptor) _generative)_is_aliased_class)_is_mapped_class _orm_columns)InspectionAttr) PathRegistry)_entity_corresponds_to)aliased) AliasedClass)join) object_mapper) ORMAdapter) with_parent)inspect) inspection)log)sql)util) expression)visitors)ColumnCollection)_interpret_as_from) ForUpdateArg)Query QueryContextrc@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZeZdZdZdZdZdZdZdZdZdZdZiZ dZ!dZ"e#$Z%Z&e#$Z'e#$Z(e#$Z)dZ*dZ+dZ,dZ-dZ.e/Z0dZ1dZ2dZ3 dddZ4ddd Z5d d Z6d d Z7ddZ8ddZ9ddZ:ddZ;e<ddZ=e<ddZ>ddZ?ddZ@ddZAd d!ZBeCd"d#ZDd$d%ZEd&d'ZFd(d)ZGdd*d+ZHd,d-ZId.d/ZJd0d1ZKdd2d3ZLdd4d5ZMd6d7ZNd8d9ZOd:d;ZP     ddd?ZReCd@dAZSddBdCZTddDdEZUdFdGZVdHdIZWeCdJdKZXdLdMZYe<dNdOZZeCdPdQZ[e<dRdSZ\dTdUZ]e<dVdWZ^e<dXdYZ_eCdZd[Z`e<d\d]Zaer?_from_obj_aliasrB)r*objset_base_aliasfaselect_from_aliasfrom_objinfoequivsr&r&r,_set_select_fromsX          zQuery._set_select_fromcCs<|jD]}|j|d|D] }|j|jdqqdSr6)rHr(poprIrJ)r*r:rLrMr&r&r,_reset_polymorphic_adapter1s  z Query._reset_polymorphic_adaptercCsxd|jvr|jd}|j|d}|r||St|tjr!|}n t|dr*|j}ndS|j|d}|r:||SdS)N parententitytable) _annotationsr(get adapt_clauserUr FromClauserNri)r*elementsearchrWr&r&r,_adapt_polymorphic_element7s      z Query._adapt_polymorphic_elementcsfdd|DS)Ncs g|] }t|ddqST) _adapt_clauser_literal_as_label_reference.0or*r&r, Js  z)Query._adapt_col_list..r&)r*colsr&rwr,_adapt_col_listIs zQuery._adapt_col_listcC ||_dSr6)lazy_loaded_from)r*stater&r&r,_set_lazyload_fromQ zQuery._set_lazyload_fromcCs d|_dSNF)_orm_only_adaptrwr&r&r,_adapt_all_clausesUrzQuery._adapt_all_clausescsg|jsd}|r|jr|jD] }||jfq|jr+|jr$|nd|jjf|jr6||jfs:|Sfdd}t |i|S)z\Adapt incoming clauses to transformations which have been applied within this query.FcsFd|jvp d|jv}D]\}}|r|r ||}|dur |Sq dS)N _orm_adaptrhrj)elem is_orm_adapt _orm_onlyrKeadaptersr&r,replaceys  z$Query._adapt_clause..replace) r_filter_aliasesrSrr]_orm_only_from_obj_aliasr(rpr replacement_traverse)r*clause as_filterorm_onlyr`rr&rr,rrYs$     zQuery._adapt_clausecCs |jdS)zReturn the first QueryEntity.rr/rwr&r&r,_query_entity_zerorzQuery._query_entity_zerocCs |jdjS)z8return the Mapper associated with the first QueryEntity.r)r/r:rwr&r&r, _mapper_zeros zQuery._mapper_zerocCs|jdur|jS|jS)zReturn the 'entity' (mapper or AliasedClass) associated with the first QueryEntity, or alternatively the 'select from' entity if specified.N)rPr entity_zerorwr&r&r, _entity_zeros zQuery._entity_zeroccs"|jD] }t|tr|VqdSr6)r/rU _MapperEntity)r*r5r&r&r,_mapper_entitiess   zQuery._mapper_entitiescCs|jd|S)N_joinpoint_entity) _joinpointrkrrwr&r&r,_joinpoint_zerozQuery._joinpoint_zerocCs(|}|durt|}|js|jSdSr6)rris_clause_elementr:)r*ezeroinspr&r&r, _bind_mappers zQuery._bind_mappercCs$|j|jgkrtd||jjS)Nz4%s() can only be used against a single mapped class.)r/r0rQInvalidRequestErrorr)r*methnamer&r&r,_only_full_mapper_zeroszQuery._only_full_mapper_zerocCs$t|jdkrt|p d|S)Nrz8This operation requires a Query against a single mapper.)rZr/rQrr)r* rationaler&r&r,_only_entity_zeros zQuery._only_entity_zerocCs"i}|jD] }||jjq|Sr6)rupdater:rA)r*rdr5r&r&r, __all_equivss zQuery.__all_equivscCs|jddddSNrkF)order_bydistinct)_no_criterion_conditionrwr&r&r,_get_conditionszQuery._get_conditioncCs|jdddddSr)_no_criterion_assertionrwr&r&r,_get_existing_conditionszQuery._get_existing_conditioncCsh|jsdS|jdus)|jdus)|js)|jdus)|jdus)|js)|r$|js)|r0|jr2t d|dSdSNz`_. Note that, in this example, the ``included_parts`` cte and the ``incl_alias`` alias of it are Core selectables, which means the columns are accessed via the ``.c.`` attribute. The ``parts_alias`` object is an :func:`.orm.aliased` instance of the ``Part`` entity, so column-mapped attributes are available directly:: from sqlalchemy.orm import aliased class Part(Base): __tablename__ = 'part' part = Column(String, primary_key=True) sub_part = Column(String, primary_key=True) quantity = Column(Integer) included_parts = session.query( Part.sub_part, Part.part, Part.quantity).\ filter(Part.part=="our part").\ cte(name="included_parts", recursive=True) incl_alias = aliased(included_parts, name="pr") parts_alias = aliased(Part, name="p") included_parts = included_parts.union_all( session.query( parts_alias.sub_part, parts_alias.part, parts_alias.quantity).\ filter(parts_alias.part==incl_alias.c.sub_part) ) q = session.query( included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ).\ group_by(included_parts.c.sub_part) .. seealso:: :meth:`.HasCTE.cte` F)r recursive)rrcte)r*rrr&r&r,rMs 7z Query.ctecCs|dj|S)zReturn the full SELECT statement represented by this :class:`.Query`, converted to a scalar subquery with a label of the given name. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.label`. F)rrlabel)r*rr&r&r,rs z Query.labelcCs|djS)zReturn the full SELECT statement represented by this :class:`.Query`, converted to a scalar subquery. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.as_scalar`. F)rr as_scalarrwr&r&r,rszQuery.as_scalarcCs|S)zReturn the :class:`.Select` object emitted by this :class:`.Query`. Used for :func:`.inspect` compatibility, this is equivalent to:: query.enable_eagerloads(False).with_labels().statement )__clause_element__rwr&r&r,r@s zQuery.selectablecCs|djSr)rrrrwr&r&r,rzQuery.__clause_element__cC ||_dS)zWhen set to True, the query results will always be a tuple. This is specifically for single element queries. The default is False. .. versionadded:: 1.2.5 .. seealso:: :meth:`.Query.is_single_entity` N)_only_return_tuplesr*valuer&r&r,only_return_tuples zQuery.only_return_tuplescCs"|j ot|jdko|jdjS)alIndicates if this :class:`.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.only_return_tuples` rr)rrZr/supports_single_entityrwr&r&r,is_single_entitys   zQuery.is_single_entitycCr)aControl whether or not eager joins and subqueries are rendered. When set to False, the returned Query will not render eager joins regardless of :func:`~sqlalchemy.orm.joinedload`, :func:`~sqlalchemy.orm.subqueryload` options or mapper-level ``lazy='joined'``/``lazy='subquery'`` configurations. This is used primarily when nesting the Query's statement into a subquery or other selectable, or when using :meth:`.Query.yield_per`. N)_enable_eagerloadsrr&r&r,rs zQuery.enable_eagerloadscCstd|)NzThe 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().)rQr)r*messager&r&r, _no_yield_pers zQuery._no_yield_percC d|_dS)aApply column labels to the return value of Query.statement. Indicates that this Query's `statement` accessor should return a SELECT statement that applies labels to all columns in the form _; this is commonly used to disambiguate columns from multiple tables which have the same name. When the `Query` actually issues SQL to load rows, it always uses column labeling. .. note:: The :meth:`.Query.with_labels` method *only* applies the output of :attr:`.Query.statement`, and *not* to any of the result-row invoking systems of :class:`.Query` itself, e.g. :meth:`.Query.first`, :meth:`.Query.all`, etc. To execute a query using :meth:`.Query.with_labels`, invoke the :attr:`.Query.statement` using :meth:`.Session.execute`:: result = session.execute(query.with_labels().statement) TN)rrwr&r&r,rs zQuery.with_labelscCr)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)rrr&r&r,enable_assertionss zQuery.enable_assertionscC|jS)zA readonly attribute which returns the current WHERE criterion for this Query. This returned value is a SQL expression construct, or ``None`` if no criterion has been established. )rrwr&r&r, whereclause zQuery.whereclausecCr)aindicate that this query applies to objects loaded within a certain path. Used by deferred loaders (see strategies.py) which transfer query options from an originating query to a newly generated query intended for the deferred load. N) _current_path)r*pathr&r&r,_with_current_path% zQuery._with_current_pathcCsJ|jstd|jd}|g|jdd|_|j||||ddS)aLoad columns for inheriting classes. :meth:`.Query.with_polymorphic` applies transformations to the "main" mapped class represented by this :class:`.Query`. The "main" mapped class here means the :class:`.Query` object's first argument is a full class, i.e. ``session.query(SomeClass)``. These transformations allow additional tables to be present in the FROM clause so that columns for a joined-inheritance subclass are available in the query, both for the purposes of load-time efficiency as well as the ability to use these columns at query time. See the documentation section :ref:`with_polymorphic` for details on how this method is used. z(No primary mapper set up for this Query.rrN)r@polymorphic_on)r0rQrr/rset_with_polymorphic)r*cls_or_mappersr@rrEr&r&r,r;1s zQuery.with_polymorphiccCs||_|jd|d|_dS)a Yield only ``count`` rows at a time. The purpose of this method is when fetching very large result sets (> 10K rows), to batch results in sub-collections and yield them out partially, so that the Python interpreter doesn't need to declare very large areas of memory which is both time consuming and leads to excessive memory use. The performance from fetching hundreds of thousands of rows can often double when a suitable yield-per setting (e.g. approximately 1000) is used, even with DBAPIs that buffer rows (which are most). The :meth:`.Query.yield_per` method **is not compatible subqueryload eager loading or joinedload eager loading when using collections**. It is potentially compatible with "select in" eager loading, **provided the database driver supports multiple, independent cursors** (pysqlite and psycopg2 are known to work, MySQL and SQL Server ODBC drivers do not). Therefore in some cases, it may be helpful to disable eager loads, either unconditionally with :meth:`.Query.enable_eagerloads`:: q = sess.query(Object).yield_per(100).enable_eagerloads(False) Or more selectively using :func:`.lazyload`; such as with an asterisk to specify the default loader scheme:: q = sess.query(Object).yield_per(100).\ options(lazyload('*'), joinedload(Object.some_related)) .. warning:: Use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten. In particular, it's usually impossible to use this setting with eagerly loaded collections (i.e. any lazy='joined' or 'subquery') since those collections will be cleared for a new load when encountered in a subsequent result batch. In the case of 'subquery' loading, the full result for all rows is fetched which generally defeats the purpose of :meth:`~sqlalchemy.orm.query.Query.yield_per`. Also note that while :meth:`~sqlalchemy.orm.query.Query.yield_per` will set the ``stream_results`` execution option to True, currently this is only understood by :mod:`~sqlalchemy.dialects.postgresql.psycopg2`, :mod:`~sqlalchemy.dialects.mysql.mysqldb` and :mod:`~sqlalchemy.dialects.mysql.pymysql` dialects which will stream results using server side cursors instead of pre-buffer all rows for this query. Other DBAPIs **pre-buffer all rows** before making them available. The memory use of raw database rows is much less than that of an ORM-mapped object, but should still be taken into consideration when benchmarking. .. seealso:: :meth:`.Query.enable_eagerloads` T)stream_resultsmax_row_bufferN) _yield_per_execution_optionsunion)r*countr&r&r, yield_perSsA zQuery.yield_percCs||tjS)aReturn an instance based on the given primary key identifier, or ``None`` if not found. E.g.:: my_user = session.query(User).get(5) some_object = session.query(VersionedFoo).get((5, 10)) some_object = session.query(VersionedFoo).get( {"id": 5, "version_id": 10}) :meth:`~.Query.get` is special in that it provides direct access to the identity map of the owning :class:`.Session`. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object. :meth:`~.Query.get` also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. :meth:`~.Query.get` is only used to return a single mapped instance, not multiple instances or individual column constructs, and strictly on a single primary key value. The originating :class:`.Query` must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading options via :meth:`~.Query.options` may be applied however, and will be used if the object is not yet locally present. A lazy-loading, many-to-one attribute configured by :func:`.relationship`, using a simple foreign-key-to-primary-key criterion, will also use an operation equivalent to :meth:`~.Query.get` in order to retrieve the target value from the local identity map before querying the database. See :doc:`/orm/loading_relationships` for further details on relationship loading. :param ident: A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed. For a single-column primary key, the scalar calling form is typically the most expedient. If the primary key of a row is the value "5", the call looks like:: my_object = query.get(5) The tuple form contains primary key values typically in the order in which they correspond to the mapped :class:`.Table` object's primary key columns, or if the :paramref:`.Mapper.primary_key` configuration parameter were used, in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits "5, 10" the call would look like:: my_object = query.get((5, 10)) The dictionary form should include as keys the mapped attribute names corresponding to each element of the primary key. If the mapped class has the attributes ``id``, ``version_id`` as the attributes which store the object's primary key value, the call would look like:: my_object = query.get({"id": 5, "version_id": 10}) .. versionadded:: 1.3 the :meth:`.Query.get` method now optionally accepts a dictionary of attribute names to values in order to indicate a primary key identifier. :return: The object instance, or ``None``. ) _get_implrload_on_pk_identity)r*identr&r&r,rksSz Query.getcCs|j||d}t|j||S)akLocate an object in the identity map. Given a primary key identity, constructs an identity key and then looks in the session's identity map. If present, the object may be run through unexpiration rules (e.g. load unloaded attributes, check if was deleted). For performance reasons, while the :class:`.Query` must be instantiated, it may be instantiated with no entities, and the mapper is passed:: obj = session.query()._identity_lookup(inspect(SomeClass), (1, )) :param mapper: mapper in use :param primary_key_identity: the primary key we are searching for, as a tuple. :param identity_token: identity token that should be used to create the identity key. Used as is, however overriding subclasses can repurpose this in order to interpret the value in a special way, such as if None then look among multiple target tokens. :param passive: passive load flag passed to :func:`.loading.get_from_identity`, which impacts the behavior if the object is found; the object may be validated and/or unexpired if the flag allows for SQL to be emitted. :param lazy_loaded_from: an :class:`.InstanceState` that is specifically asking for this identity as a related identity. Used for sharding schemes where there is a correspondence between an object and a related object being lazy-loaded (or otherwise relationship-loaded). .. versionadded:: 1.2.9 :return: None if the object is not found in the identity map, *or* if the object was unexpired and found to have been deleted. if passive flags disallow SQL and the object is expired, returns PASSIVE_NO_RESULT. In all other cases the instance is returned. .. versionadded:: 1.2.7 r)identity_key_from_primary_keyrget_from_identityr')r*r:primary_key_identityrpassiver|keyr&r&r,_identity_lookups1zQuery._identity_lookupc stdr |d}tt}|stjddtt|jkr5t dd dd|jD|r]zt fd d|j DWnty\t d d d d|j Dw|js|js|jdur|j||d }|dur|t|j|jsdS|S||S) N__composite_values__rkr6)defaultzmIncorrect number of values in identifier to formulate primary key for query.get(); primary key columns are %s,css|]}d|VqdSz'%s'Nr&rucr&r&r, 5sz"Query._get_impl..c3s|]}|jVqdSr6r ruproprr&r,r:  ztIncorrect names of values in identifier to formulate primary key for query.get(); primary key attribute names are %scss|]}d|jVqdSrrrr&r&r,rDrr)rNr rrUdictrr2rZ primary_keyrQrrlist_identity_key_propsKeyErrorralways_refresh_for_update_argr r issubclassrclass_)r*r db_load_fnrr:is_dictinstancer&rr,r$sT         zQuery._get_implcGs@|D]}|dur|jdg|_q|jtt||_qdS)a"Return a :class:`.Query` construct which will correlate the given FROM clauses to that of an enclosing :class:`.Query` or :func:`~.expression.select`. The method here accepts mapped classes, :func:`.aliased` constructs, and :func:`.mapper` constructs as arguments, which are resolved into expression constructs, in addition to appropriate expression constructs. The correlation arguments are ultimately passed to :meth:`.Select.correlate` after coercion to expression constructs. The correlation arguments take effect in such cases as when :meth:`.Query.from_self` is used, or when a subquery as returned by :meth:`.Query.subquery` is embedded in another :func:`~.expression.select` construct. N) _correlaterr>surface_selectablesr")r*argssr&r&r, correlate^s zQuery.correlatecCr)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*settingr&r&r, autoflush{rzQuery.autoflushcCr)aReturn a :class:`.Query` that will expire and refresh all instances as they are loaded, or reused from the current :class:`.Session`. :meth:`.populate_existing` does not improve behavior when the ORM is used normally - the :class:`.Session` object's usual behavior of maintaining a transaction and expiring all attributes after rollback or commit handles object state automatically. This method is not intended for general use. TN)rrwr&r&r,rs zQuery.populate_existingcCr)zSet the 'invoke all eagers' flag which causes joined- and subquery loaders to traverse into already-loaded related objects and collections. Default is that of :attr:`.Query._invoke_all_eagers`. N)_invoke_all_eagersrr&r&r,_with_invoke_all_eagerss zQuery._with_invoke_all_eagerscCs|rt|}n|}|dur7t|}|jD]}t|tjr(|j|jur(|}nqt d|jj j |j j f| t|||jS)aAdd filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established :func:`.relationship()` configuration. The method uses the :func:`.with_parent` function to generate the clause, the result of which is passed to :meth:`.Query.filter`. Parameters are the same as :func:`.with_parent`, with the exception that the given property can be None, in which case a search is performed against this :class:`.Query` object's target mapper. :param instance: An instance which has some :func:`.relationship`. :param property: String property name, or class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship. :param from_entity: Entity in which to consider as the left side. This defaults to the "zero" entity of the :class:`.Query` itself. Nz\Could not locate a property which relates instances of class '%s' to instances of class '%s')rrriterate_propertiesrUr RelationshipPropertyr:rQrr__name__rfilterrrE)r*r"property from_entityrr:rr&r&r,rs(     zQuery.with_parentcCs8|dur t||}t|j|_t||}||gdS)zIadd a mapped entity to the list of result columns to be returned.N)rrr/rr3)r*rErWrMr&r&r, add_entitys    zQuery.add_entitycCr)aReturn a :class:`.Query` that will use the given :class:`.Session`. While the :class:`.Query` object is normally instantiated using the :meth:`.Session.query` method, it is legal to build the :class:`.Query` directly without necessarily using a :class:`.Session`. Such a :class:`.Query` object, or any :class:`.Query` already associated with a different :class:`.Session`, can produce a new :class:`.Query` object associated with a target session using this method:: from sqlalchemy.orm import Query query = Query([MyClass]).filter(MyClass.id == 5) result = query.with_session(my_session).one() N)r')r*r'r&r&r, with_sessions zQuery.with_sessioncGsB|djd}||}d|_||_|r|||S)areturn a Query that selects from this Query's SELECT statement. :meth:`.Query.from_self` essentially turns the SELECT statement into a SELECT of itself. Given a query such as:: q = session.query(User).filter(User.name.like('e%')) Given the :meth:`.Query.from_self` version:: q = session.query(User).filter(User.name.like('e%')).from_self() This query renders as: .. sourcecode:: sql SELECT anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1) AS anon_1 There are lots of cases where :meth:`.Query.from_self` may be useful. A simple one is where above, we may want to apply a row LIMIT to the set of user objects we query against, and then apply additional joins against that row-limited set:: q = session.query(User).filter(User.name.like('e%')).\ limit(5).from_self().\ join(User.addresses).filter(Address.email.like('q%')) The above query joins to the ``Address`` entity but only against the first five results of the ``User`` query: .. sourcecode:: sql SELECT anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1 LIMIT :param_1) AS anon_1 JOIN address ON anon_1.user_id = address.user_id WHERE address.email LIKE :email_1 **Automatic Aliasing** Another key behavior of :meth:`.Query.from_self` is that it applies **automatic aliasing** to the entities inside the subquery, when they are referenced on the outside. Above, if we continue to refer to the ``User`` entity without any additional aliasing applied to it, those references wil be in terms of the subquery:: q = session.query(User).filter(User.name.like('e%')).\ limit(5).from_self().\ join(User.addresses).filter(Address.email.like('q%')).\ order_by(User.name) The ORDER BY against ``User.name`` is aliased to be in terms of the inner subquery: .. sourcecode:: sql SELECT anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1 LIMIT :param_1) AS anon_1 JOIN address ON anon_1.user_id = address.user_id WHERE address.email LIKE :email_1 ORDER BY anon_1.user_name The automatic aliasing feature only works in a **limited** way, for simple filters and orderings. More ambitious constructions such as referring to the entity in joins should prefer to use explicit subquery objects, typically making use of the :meth:`.Query.subquery` method to produce an explicit subquery object. Always test the structure of queries by viewing the SQL to ensure a particular structure does what's expected! **Changing the Entities** :meth:`.Query.from_self` also includes the ability to modify what columns are being queried. In our example, we want ``User.id`` to be queried by the inner query, so that we can join to the ``Address`` entity on the outside, but we only wanted the outer query to return the ``Address.email`` column:: q = session.query(User).filter(User.name.like('e%')).\ limit(5).from_self(Address.email).\ join(User.addresses).filter(Address.email.like('q%')) yielding: .. sourcecode:: sql SELECT address.email AS address_email FROM (SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE "user".name LIKE :name_1 LIMIT :param_1) AS anon_1 JOIN address ON anon_1.user_id = address.user_id WHERE address.email LIKE :email_1 **Looking out for Inner / Outer Columns** Keep in mind that when referring to columns that originate from inside the subquery, we need to ensure they are present in the columns clause of the subquery itself; this is an ordinary aspect of SQL. For example, if we wanted to load from a joined entity inside the subquery using :func:`.contains_eager`, we need to add those columns. Below illustrates a join of ``Address`` to ``User``, then a subquery, and then we'd like :func:`.contains_eager` to access the ``User`` columns:: q = session.query(Address).join(Address.user).\ filter(User.name.like('e%')) q = q.add_entity(User).from_self().\ options(contains_eager(Address.user)) We use :meth:`.Query.add_entity` above **before** we call :meth:`.Query.from_self` so that the ``User`` columns are present in the inner subquery, so that they are available to the :func:`.contains_eager` modifier we are using on the outside, producing: .. sourcecode:: sql SELECT anon_1.address_id AS anon_1_address_id, anon_1.address_email AS anon_1_address_email, anon_1.address_user_id AS anon_1_address_user_id, anon_1.user_id AS anon_1_user_id, anon_1.user_name AS anon_1_user_name FROM ( SELECT address.id AS address_id, address.email AS address_email, address.user_id AS address_user_id, "user".id AS user_id, "user".name AS user_name FROM address JOIN "user" ON "user".id = address.user_id WHERE "user".name LIKE :name_1) AS anon_1 If we didn't call ``add_entity(User)``, but still asked :func:`.contains_eager` to load the ``User`` entity, it would be forced to add the table on the outside without the correct join criteria - note the ``anon1, "user"`` phrase at the end: .. sourcecode:: sql -- incorrect query SELECT anon_1.address_id AS anon_1_address_id, anon_1.address_email AS anon_1_address_email, anon_1.address_user_id AS anon_1_address_user_id, "user".id AS user_id, "user".name AS user_name FROM ( SELECT address.id AS address_id, address.email AS address_email, address.user_id AS address_user_id FROM address JOIN "user" ON "user".id = address.user_id WHERE "user".name LIKE :name_1) AS anon_1, "user" :param \*entities: optional list of entities which will replace those being selected. FN) rrrr'_from_selectable_enable_single_critrrPr))r*r+ fromclauserr&r&r, from_selfs+   zQuery.from_selfcCr{r6)r6)r*valr&r&r,_set_enable_single_critrzQuery._set_enable_single_critcCsXdD] }|j|dq||gdd|_|j}g|_|D] }|||jdqdS)N) rrrrrr _joinpathrr_having _prefixes _suffixesTFr)rrfrerr/adapt_to_selectablerY)r*r7attr old_entitiesrr&r&r,r5szQuery._from_selectablecGs6|stdS|}|j|td|jsd|_t|S)z\Return an iterator yielding result tuples corresponding to the given list of columnsr&)r4 )iterrr) _ColumnEntityr)r*columnsrr&r&r,valuessz Query.valuescCs*z t||dWStyYdSw)zLReturn a scalar result corresponding to the given column expression.rN)nextrF StopIterationr*columnr&r&r,rs  z Query.valuecGs||dS)a)Return a new :class:`.Query` replacing the SELECT list with the given entities. e.g.:: # Users, filtered on some arbitrary criterion # and then ordered by related email address q = session.query(User).\ join(User.address).\ filter(User.name.like('%ed%')).\ order_by(Address.email) # given *only* User.id==5, Address.email, and 'q', what # would the *next* User in the result be ? subq = q.with_entities(Address.email).\ order_by(None).\ filter(User.id==5).\ subquery() q = q.join((subq, subq.c.email < Address.email)).\ limit(1) N)r))r*r+r&r&r, with_entitieszQuery.with_entitiescGsBt|j|_t|j}|D]}t||q ||j|ddS)zXAdd one or more column expressions to the list of result columns to be returned.N)rr/rZrDr3)r*rJlrr&r&r, add_columnss   zQuery.add_columnsz0.7z9:meth:`.add_column` is superseded by :meth:`.add_columns`cCs ||S)zAdd a column expression to the list of result columns to be returned. Pending deprecation: :meth:`.add_column` will be superseded by :meth:`.add_columns`. )rNrIr&r&r, add_column rzQuery.add_columncG|jdg|RS)a>Return a new :class:`.Query` object, applying the given list of mapper options. Most supplied options regard changing how column- and relationship-mapped attributes are loaded. .. seealso:: :ref:`deferred_options` :ref:`relationship_loader_options` F_optionsr*r%r&r&r,optionssz Query.optionscGrPNTrQrSr&r&r,_conditional_options(rzQuery._conditional_optionscGsp|j|_d|jvrt|jd<tt|}|j||_|r,|D]}||q"dS|D]}||q.dS)N_unbound_load_dedupes) _attributesr8rrXrflatten_iterator _with_optionsprocess_query_conditionally process_query)r* conditionalr%optsoptr&r&r,rR+s      zQuery._optionscCs||S)aReturn a new :class:`.Query` object transformed by the given function. E.g.:: def filter_something(criterion): def transform(q): return q.filter(criterion) return transform q = q.with_transformation(filter_something(x==5)) This allows ad-hoc recipes to be created for :class:`.Query` objects. See the example at :ref:`hybrid_transformers`. r&)r*fnr&r&r,with_transformation;szQuery.with_transformation*cCs,|dur t|j}|j|||ff7_dS)a~Add an indexing or other executional context hint for the given entity or selectable to this :class:`.Query`. Functionality is passed straight through to :meth:`~sqlalchemy.sql.expression.Select.with_hint`, with the addition that ``selectable`` can be a :class:`.Table`, :class:`.Alias`, or ORM entity / mapped class /etc. .. seealso:: :meth:`.Query.with_statement_hint` :meth:.`.Query.prefix_with` - generic SELECT prefixing which also can suit some database-specific HINT syntaxes such as MySQL optimizer hints N)rr@ _with_hints)r*r@text dialect_namer&r&r, with_hintNs zQuery.with_hintcCs|d||S)aadd a statement hint to this :class:`.Select`. This method is similar to :meth:`.Select.with_hint` except that it does not require an individual table, and instead applies to the statement as a whole. This feature calls down into :meth:`.Select.with_statement_hint`. .. versionadded:: 1.0.0 .. seealso:: :meth:`.Query.with_hint` N)rf)r*rdrer&r&r,with_statement_hinthszQuery.with_statement_hintcCr)z Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`.Query.execution_options` )rrwr&r&r,get_execution_optionszrzQuery.get_execution_optionscKs|j||_dS)a Set non-SQL options which take effect during execution. The options are the same as those accepted by :meth:`.Connection.execution_options`. Note that the ``stream_results`` execution option is enabled automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()` method is used. .. seealso:: :meth:`.Query.get_execution_options` N)rrr*kwargsr&r&r,execution_optionsszQuery.execution_optionsz0.9zThe :meth:`.Query.with_lockmode` method is deprecated and will be removed in a future release. Please refer to :meth:`.Query.with_for_update`. cCst||_dS)aReturn a new :class:`.Query` object with the specified "locking mode", which essentially refers to the ``FOR UPDATE`` clause. :param mode: a string representing the desired locking mode. Valid values are: * ``None`` - translates to no lockmode * ``'update'`` - translates to ``FOR UPDATE`` (standard SQL, supported by most dialects) * ``'update_nowait'`` - translates to ``FOR UPDATE NOWAIT`` (supported by Oracle, PostgreSQL 8.1 upwards) * ``'read'`` - translates to ``LOCK IN SHARE MODE`` (for MySQL), and ``FOR SHARE`` (for PostgreSQL) .. seealso:: :meth:`.Query.with_for_update` - improved API for specifying the ``FOR UPDATE`` clause. N) LockmodeArgparse_legacy_queryr)r*moder&r&r, with_lockmodeszQuery.with_lockmodecCst|||||d|_dS)areturn a new :class:`.Query` with the specified options for the ``FOR UPDATE`` clause. The behavior of this method is identical to that of :meth:`.SelectBase.with_for_update`. When called with no arguments, the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause appended. When additional arguments are specified, backend-specific options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE`` can take effect. E.g.:: q = sess.query(User).with_for_update(nowait=True, of=User) The above query on a PostgreSQL backend will render like:: SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT .. versionadded:: 0.9.0 :meth:`.Query.with_for_update` supersedes the :meth:`.Query.with_lockmode` method. .. seealso:: :meth:`.GenerativeSelect.with_for_update` - Core level method with full argument and behavioral description. )readnowaitof skip_locked key_shareN)rlr)r*rprqrrrsrtr&r&r,with_for_updates$ zQuery.with_for_updatecOsNt|dkr||dn t|dkrtd|j|_|j|dS)aadd values for bind parameters which may have been specified in filter(). parameters may be specified using \**kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that \**kwargs is convenient, however some parameter dictionaries contain unicode keys in which case \**kwargs cannot be used. rrzFparams() takes zero or one positional argument, which is a dictionary.N)rZrrQrRrr8)r*r%rjr&r&r,rs   z Query.paramscGsHt|D]}t|}||dd}|jdur|j|@|_q||_qdS)aapply the given filtering criterion to a copy of this :class:`.Query`, using SQL expressions. e.g.:: session.query(MyClass).filter(MyClass.name == 'some name') Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the :func:`.and_` function:: session.query(MyClass).\ filter(MyClass.name == 'some name', MyClass.id > 5) The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced into SQL expression constructs via the :func:`.text` construct. .. seealso:: :meth:`.Query.filter_by` - filter on keyword expressions. TN)rr_expression_literal_as_textrrrr* criterionr&r&r,r0s   z Query.filterc s fdd|D}j|S)aapply the given filtering criterion to a copy of this :class:`.Query`, using keyword expressions. e.g.:: session.query(MyClass).filter_by(name = 'some name') Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the :func:`.and_` function:: session.query(MyClass).\ filter_by(name = 'some name', id = 5) The keyword expressions are extracted from the primary entity of the query, or the last entity that was the target of a call to :meth:`.Query.join`. .. seealso:: :meth:`.Query.filter` - filter on SQL expressions. cs"g|] \}}t||kqSr&)r r)rur rrwr&r,rx5sz#Query.filter_by..)itemsr0)r*rjclausesr&rwr, filter_bys  zQuery.filter_bycGszt|dkr!|ddurd|jvrd|_dS|ddur!d|_dS||}|jdus0|jdur5||_dS|j||_dS)aZapply one or more ORDER BY criterion to the query and return the newly resulting ``Query`` All existing ORDER BY settings can be suppressed by passing ``None`` - this will suppress any ordering configured on the :func:`.mapper` object using the deprecated :paramref:`.mapper.order_by` parameter. rrFrN)rZrrrzrwr&r&r,r;s     zQuery.order_bycGsft|dkr|ddurd|_dSttdd|D}||}|jdur+||_dS|j||_dS)aapply one or more GROUP BY criterion to the query and return the newly resulting :class:`.Query` All existing GROUP BY settings can be suppressed by passing ``None`` - this will suppress any GROUP BY configured on mappers as well. .. versionadded:: 1.1 GROUP BY can be cancelled by passing None, in the same way as ORDER BY. rrNFcSsg|]}t|qSr&rrr&r&r,rxjz"Query.group_by..)rZrrrrzrwr&r&r,group_byWs     zQuery.group_bycCsZt|}|durt|tjstd||dd}|jdur(|j|@|_dS||_dS)a apply a HAVING criterion to the query and return the newly resulting :class:`.Query`. :meth:`~.Query.having` is used in conjunction with :meth:`~.Query.group_by`. HAVING criterion makes it possible to use filters on aggregate functions like COUNT, SUM, AVG, MAX, and MIN, eg.:: q = session.query(User.id).\ join(User.addresses).\ group_by(User.id).\ having(func.count(Address.id) > 2) NzHhaving() argument must be of type sqlalchemy.sql.ClauseElement or stringT) rrvrUr ClauseElementrQrRrrr<rwr&r&r,havingrs    z Query.havingcGs|||gt|dSr)r5rr:)r*expr_fnrr&r&r,_set_ops z Query._set_opcG|jtjg|RS)aProduce a UNION of this Query against one or more queries. e.g.:: q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar') q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo') q3 = q1.union(q2) The method accepts multiple Query objects so as to control the level of nesting. A series of ``union()`` calls such as:: x.union(y).union(z).all() will nest on each ``union()``, and produces:: SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y) UNION SELECT * FROM Z) Whereas:: x.union(y, z).all() produces:: SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION SELECT * FROM Z) Note that many database backends do not allow ORDER BY to be rendered on a query called within UNION, EXCEPT, etc. To disable all ORDER BY clauses including those configured on mappers, issue ``query.order_by(None)`` - the resulting :class:`.Query` object will not render ORDER BY within its SELECT statement. )rrrr*rr&r&r,rs%z Query.unioncGr)zProduce a UNION ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr union_allrr&r&r,rzQuery.union_allcGr)zProduce an INTERSECT of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr intersectrr&r&r,rrzQuery.intersectcGr)zProduce an INTERSECT ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr intersect_allrr&r&r,rrzQuery.intersect_allcGr)zProduce an EXCEPT of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rrexcept_rr&r&r,rrz Query.except_cGr)zProduce an EXCEPT ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples. )rr except_allrr&r&r,rrzQuery.except_allcOsb|dd|dd|dd|ddf\}}}}|r'tddt||j|||||dS) a*Create a SQL JOIN against this :class:`.Query` object's criterion and apply generatively, returning the newly resulting :class:`.Query`. **Simple Relationship Joins** Consider a mapping between two classes ``User`` and ``Address``, with a relationship ``User.addresses`` representing a collection of ``Address`` objects associated with each ``User``. The most common usage of :meth:`~.Query.join` is to create a JOIN along this relationship, using the ``User.addresses`` attribute as an indicator for how this should occur:: q = session.query(User).join(User.addresses) Where above, the call to :meth:`~.Query.join` along ``User.addresses`` will result in SQL equivalent to:: SELECT user.* FROM user JOIN address ON user.id = address.user_id In the above example we refer to ``User.addresses`` as passed to :meth:`~.Query.join` as the *on clause*, that is, it indicates how the "ON" portion of the JOIN should be constructed. For a single-entity query such as the one above (i.e. we start by selecting only from ``User`` and nothing else), the relationship can also be specified by its string name:: q = session.query(User).join("addresses") :meth:`~.Query.join` can also accommodate multiple "on clause" arguments to produce a chain of joins, such as below where a join across four related entities is constructed:: q = session.query(User).join("orders", "items", "keywords") The above would be shorthand for three separate calls to :meth:`~.Query.join`, each using an explicit attribute to indicate the source entity:: q = session.query(User).\ join(User.orders).\ join(Order.items).\ join(Item.keywords) **Joins to a Target Entity or Selectable** A second form of :meth:`~.Query.join` allows any mapped entity or core selectable construct as a target. In this usage, :meth:`~.Query.join` will attempt to create a JOIN along the natural foreign key relationship between two entities:: q = session.query(User).join(Address) The above calling form of :meth:`~.Query.join` will raise an error if either there are no foreign keys between the two entities, or if there are multiple foreign key linkages between them. In the above calling form, :meth:`~.Query.join` is called upon to create the "on clause" automatically for us. The target can be any mapped entity or selectable, such as a :class:`.Table`:: q = session.query(User).join(addresses_table) **Joins to a Target with an ON Clause** The third calling form allows both the target entity as well as the ON clause to be passed explicitly. Suppose for example we wanted to join to ``Address`` twice, using an alias the second time. We use :func:`~sqlalchemy.orm.aliased` to create a distinct alias of ``Address``, and join to it using the ``target, onclause`` form, so that the alias can be specified explicitly as the target along with the relationship to instruct how the ON clause should proceed:: a_alias = aliased(Address) q = session.query(User).\ join(User.addresses).\ join(a_alias, User.addresses).\ filter(Address.email_address=='ed@foo.com').\ filter(a_alias.email_address=='ed@bar.com') Where above, the generated SQL would be similar to:: SELECT user.* FROM user JOIN address ON user.id = address.user_id JOIN address AS address_1 ON user.id=address_1.user_id WHERE address.email_address = :email_address_1 AND address_1.email_address = :email_address_2 The two-argument calling form of :meth:`~.Query.join` also allows us to construct arbitrary joins with SQL-oriented "on clause" expressions, not relying upon configured relationships at all. Any SQL expression can be passed as the ON clause when using the two-argument form, which should refer to the target entity in some way as well as an applicable source entity:: q = session.query(User).join(Address, User.id==Address.user_id) **Advanced Join Targeting and Adaption** There is a lot of flexibility in what the "target" can be when using :meth:`~.Query.join`. As noted previously, it also accepts :class:`.Table` constructs and other selectables such as :func:`.alias` and :func:`.select` constructs, with either the one or two-argument forms:: addresses_q = select([Address.user_id]).\ where(Address.email_address.endswith("@bar.com")).\ alias() q = session.query(User).\ join(addresses_q, addresses_q.c.user_id==User.id) :meth:`~.Query.join` also features the ability to *adapt* a :meth:`~sqlalchemy.orm.relationship` -driven ON clause to the target selectable. Below we construct a JOIN from ``User`` to a subquery against ``Address``, allowing the relationship denoted by ``User.addresses`` to *adapt* itself to the altered target:: address_subq = session.query(Address).\ filter(Address.email_address == 'ed@foo.com').\ subquery() q = session.query(User).join(address_subq, User.addresses) Producing SQL similar to:: SELECT user.* FROM user JOIN ( SELECT address.id AS id, address.user_id AS user_id, address.email_address AS email_address FROM address WHERE address.email_address = :email_address_1 ) AS anon_1 ON user.id = anon_1.user_id The above form allows one to fall back onto an explicit ON clause at any time:: q = session.query(User).\ join(address_subq, User.id==address_subq.c.user_id) **Controlling what to Join From** While :meth:`~.Query.join` exclusively deals with the "right" side of the JOIN, we can also control the "left" side, in those cases where it's needed, using :meth:`~.Query.select_from`. Below we construct a query against ``Address`` but can still make usage of ``User.addresses`` as our ON clause by instructing the :class:`.Query` to select first from the ``User`` entity:: q = session.query(Address).select_from(User).\ join(User.addresses).\ filter(User.name == 'ed') Which will produce SQL similar to:: SELECT address.* FROM user JOIN address ON user.id=address.user_id WHERE user.name = :name_1 **Constructing Aliases Anonymously** :meth:`~.Query.join` can construct anonymous aliases using the ``aliased=True`` flag. This feature is useful when a query is being joined algorithmically, such as when querying self-referentially to an arbitrary depth:: q = session.query(Node).\ join("children", "children", aliased=True) When ``aliased=True`` is used, the actual "alias" construct is not explicitly available. To work with it, methods such as :meth:`.Query.filter` will adapt the incoming entity to the last join point:: q = session.query(Node).\ join("children", "children", aliased=True).\ filter(Node.name == 'grandchild 1') When using automatic aliasing, the ``from_joinpoint=True`` argument can allow a multi-node join to be broken into multiple calls to :meth:`~.Query.join`, so that each path along the way can be further filtered:: q = session.query(Node).\ join("children", aliased=True).\ filter(Node.name='child 1').\ join("children", aliased=True, from_joinpoint=True).\ filter(Node.name == 'grandchild 1') The filtering aliases above can then be reset back to the original ``Node`` entity using :meth:`~.Query.reset_joinpoint`:: q = session.query(Node).\ join("children", "children", aliased=True).\ filter(Node.name == 'grandchild 1').\ reset_joinpoint().\ filter(Node.name == 'parent 1) For an example of ``aliased=True``, see the distribution example :ref:`examples_xmlpersistence` which illustrates an XPath-like query system using algorithmic joins. :param \*props: A collection of one or more join conditions, each consisting of a relationship-bound attribute or string relationship name representing an "on clause", or a single target entity, or a tuple in the form of ``(target, onclause)``. A special two-argument calling form of the form ``target, onclause`` is also accepted. :param aliased=False: If True, indicate that the JOIN target should be anonymously aliased. Subsequent calls to :meth:`~.Query.filter` and similar will adapt the incoming criterion to the target alias, until :meth:`~.Query.reset_joinpoint` is called. :param isouter=False: If True, the join used will be a left outer join, just as if the :meth:`.Query.outerjoin` method were called. This flag is here to maintain consistency with the same flag as accepted by :meth:`.FromClause.join` and other Core constructs. .. versionadded:: 1.0.0 :param full=False: render FULL OUTER JOIN; implies ``isouter``. .. versionadded:: 1.1 :param from_joinpoint=False: When using ``aliased=True``, a setting of True here will cause the join to be from the most recent joined target, rather than starting back from the original FROM clauses of the query. .. seealso:: :ref:`ormtutorial_joins` in the ORM tutorial. :ref:`inheritance_toplevel` for details on how :meth:`~.Query.join` is used for inheritance relationships. :func:`.orm.join` - a standalone ORM-level join function, used internally by :meth:`.Query.join`, which in previous SQLAlchemy versions was the primary ORM-level joining interface. rFfrom_joinpointisouterfullunknown arguments: %s,  outerjoinrcreate_aliasesrrf TypeErrorrsorted_join)r*propsrjrrrrr&r&r,rs" w    z Query.joincOsV|dd|dd|dd}}}|r!tddt||j|d|||dS) zCreate a left outer join against this ``Query`` object's criterion and apply generatively, returning the newly resulting ``Query``. Usage is the same as the ``join()`` method. rFrrrrTrr)r*rrjrrrr&r&r,rs    zQuery.outerjoincCsP||_d|vr#|d\}}|}|||<||f|d<|}d|vs||_dS)Nprev)rr8r;)r*jpfrr&r&r,_update_joinpoint s    zQuery._update_joinpointc CsN|s|t|dkr&t|dtjttfr&t|dttjt j fr&|f}t |}t |D]\}}t|tr=|\}} nd} t|t j t jfrN| |} } n|| } } | durht| } | jsht| dshtdt| t j rut| dd} nd} t| t jrt|| } n|rt| t j r|}t|}t|dd| jurt|| j} t| t j r| dur| r| } n| jj} | j}|j|d}t|tr|j |r|j!}t|| j} | j}t| t"j#s|} |s|| |jf}||j$vr|j$|%}||j$f|d<|&||t|dkrt 'd |q/nd}}|(|| | ||||q/dS) zconsumes arguments from join() or outerjoin(), places them into a consistent format with which to form the actual JOIN constructs. rrrNr:z9Expected mapped entity or selectable/table as join target_of_typerz:Pathed join target %s has already been joined to; skipping))_reset_joinpointrZrUrrmtyperstrr~rPropComparatorrr2 enumeraterX string_typesrrTrNrQrRgetattrr r _parententityr r1rEr(rkrr:isa aliased_classrQueryableAttributerr8rwarn_join_left_to_right)r*keysrrrrkeylistidxarg1arg2rightonclauser_infoof_typejp0rcleftrWredgerr&r&r,r s                 z Query._joinc Cs |j|_|dur|dusJ||||\}}} n |dus!J||\}} ||ur7|s7td||f||||||\} }}|duri|j|} |jd|t| ||||df|j|dd|_dS| durt|j | j } n|} |jt| ||||df|_dS)zgiven raw "left", "right", "onclause" parameters consumed from a particular key within _join(), add a real ORMJoin object to our _from_obj list (or augment an existing one) Nz>Can't construct a join from %s to %s, they are the same entity)rrr) r(r8"_join_determine_implicit_left_side_join_place_explicit_left_siderQr _join_check_and_adapt_right_siderYorm_joinr/r@) r*rrrrrrrreplace_from_obj_indexuse_entity_indexr left_clauser&r&r,r sZ            zQuery._join_left_to_rightcCsNt|}d}}|jr7t|j|j|}t|dkr$|d}|j|}n~t|dkr/tdtd|f|jri}t |jD])\} } | j } | durMqAt| } | |urVqAt | t rc| | f|| j<qAd| f|| j<qAt |} t| |j|}t|dkr|| |d\}}nt|dkrtdtd|ftd|||fS)zWhen join conditions don't express the left side explicitly, determine if an existing FROM or entity in this query can serve as the left hand side. NrrzCan't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Try adding an explicit ON clause to help resolve the ambiguity.zjDon't know how to join to %s; please use an ON clause to more clearly establish the left side of this joinzgNo entities to join from; please use select_from() to establish the left entity/selectable of this join)rrYr>find_left_clause_to_join_fromr@rZrQrr/rentity_zero_or_selectablerUrrr)r*rrrrrrindexes potential entity_indexr5rEent_info all_clausesr&r&r,r sb         z(Query._join_determine_implicit_left_sidecCsd}}t|}|jr$t|j|j}t|dkrtd|r$|d}|durK|jrKt |drKt |jD]\}}t |t rJ| |rJ|}||fSq5||fS)zWhen join conditions express a left side explicitly, determine where in our existing list of FROM clauses we should join towards, or if we need to make a new join, and if so is it from one of our existing entities. NrzrCan't identify which entity in which to assign the left side of this join. Please use a more specific ON clause.rr:)rrYr>#find_left_clause_that_matches_givenr@rZrQrr/rNrrUrcorresponds_to)r*rrrl_inforrr5r&r&r,rU s0  z$Query._join_place_explicit_left_sidecCsTt|}t|}d}|s:t|dd} | r:| jst| jtjr:|jp$|jgD]} t |j| r9t | |jr9d}nq%|s>|sL|j|jurLt d|jt|dd|jt|dd} } } | rp|rp| |jspt d||ft|dr}|j|f7_d} |jr|r|j} | jr||dd}n-|r| | jst d| j| jjft| tjr| } d} t| | }n|rt d | o| o| jrt| jtjp|}| s|s|rt|dd }d} | r| sJt|| jd }|f|j|_|s|| |t|tjr||dd}|s|r| ||||j!f|j"fd nd |i|_"|t||fS)ztransform the "right" side of the join as well as the onclause according to polymorphic mapping translations, aliasing on the query or on the join, special cases where the right and left side have overlapping tables. Fr:NTz*Can't join table/selectable '%s' to itselfr9zIJoin target %s does not correspond to the right side of join condition %sz(Selectable '%s' is not derived from '%s'zpThe aliased=True parameter on query.join() only works with an ORM entity, not a plain selectable, as the target.)flat) equivalents)rrr)#rrr;rUr<rJoinrYr@r>selectables_overlaprQr common_parentr:rN_join_entitiesr _is_lateralrris_derived_from descriptionrVrWr_with_polymorphic_selectabler[rrArr=r~rr r)r*rrrrrrroverlap right_mapperrbright_selectableright_is_aliased need_adapteraliased_entityrKr&r&r,r s                z&Query._join_check_and_adapt_right_sidecCs|j|_d|_dSNr&)r;rrrwr&r&r,r: s zQuery._reset_joinpointcCs |dS)aSReturn a new :class:`.Query`, where the "join point" has been reset back to the base FROM entities of the query. This method is usually used in conjunction with the ``aliased=True`` feature of the :meth:`~.Query.join` method. See the example in :meth:`~.Query.join` for how this is used. N)rrwr&r&r,reset_joinpoint> s zQuery.reset_joinpointcGs||ddS)aPSet the FROM clause of this :class:`.Query` explicitly. :meth:`.Query.select_from` is often used in conjunction with :meth:`.Query.join` in order to control which entity is selected from on the "left" side of the join. The entity or selectable object here effectively replaces the "left edge" of any calls to :meth:`~.Query.join`, when no joinpoint is otherwise established - usually, the default "join point" is the leftmost entity in the :class:`~.Query` object's list of entities to be selected. A typical example:: q = session.query(Address).select_from(User).\ join(User.addresses).\ filter(User.name == 'ed') Which produces SQL equivalent to:: SELECT address.* FROM user JOIN address ON user.id=address.user_id WHERE user.name = :name_1 :param \*from_obj: collection of one or more entities to apply to the FROM clause. Entities can be mapped classes, :class:`.AliasedClass` objects, :class:`.Mapper` objects as well as core :class:`.FromClause` elements like subqueries. .. versionchanged:: 0.9 This method no longer applies the given FROM object to be the selectable from which matching entities select from; the :meth:`.select_entity_from` method now accomplishes this. See that method for a description of this behavior. .. seealso:: :meth:`~.Query.join` :meth:`.Query.select_entity_from` FNrer*rbr&r&r, select_fromK s.zQuery.select_fromcCs||gddS)aSet the FROM clause of this :class:`.Query` to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities. The :meth:`.Query.select_entity_from` method supplies an alternative approach to the use case of applying an :func:`.aliased` construct explicitly throughout a query. Instead of referring to the :func:`.aliased` construct explicitly, :meth:`.Query.select_entity_from` automatically *adapts* all occurrences of the entity to the target selectable. Given a case for :func:`.aliased` such as selecting ``User`` objects from a SELECT statement:: select_stmt = select([User]).where(User.id == 7) user_alias = aliased(User, select_stmt) q = session.query(user_alias).\ filter(user_alias.name == 'ed') Above, we apply the ``user_alias`` object explicitly throughout the query. When it's not feasible for ``user_alias`` to be referenced explicitly in many places, :meth:`.Query.select_entity_from` may be used at the start of the query to adapt the existing ``User`` entity:: q = session.query(User).\ select_entity_from(select_stmt).\ filter(User.name == 'ed') Above, the generated SQL will show that the ``User`` entity is adapted to our statement, even in the case of the WHERE clause: .. sourcecode:: sql SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name FROM (SELECT "user".id AS id, "user".name AS name FROM "user" WHERE "user".id = :id_1) AS anon_1 WHERE anon_1.name = :name_1 The :meth:`.Query.select_entity_from` method is similar to the :meth:`.Query.select_from` method, in that it sets the FROM clause of the query. The difference is that it additionally applies adaptation to the other parts of the query that refer to the primary entity. If above we had used :meth:`.Query.select_from` instead, the SQL generated would have been: .. sourcecode:: sql -- uses plain select_from(), not select_entity_from() SELECT "user".id AS user_id, "user".name AS user_name FROM "user", (SELECT "user".id AS id, "user".name AS name FROM "user" WHERE "user".id = :id_1) AS anon_1 WHERE "user".name = :name_1 To supply textual SQL to the :meth:`.Query.select_entity_from` method, we can make use of the :func:`.text` construct. However, the :func:`.text` construct needs to be aligned with the columns of our entity, which is achieved by making use of the :meth:`.TextClause.columns` method:: text_stmt = text("select id, name from user").columns( User.id, User.name) q = session.query(User).select_entity_from(text_stmt) :meth:`.Query.select_entity_from` itself accepts an :func:`.aliased` object, so that the special options of :func:`.aliased` such as :paramref:`.aliased.adapt_on_names` may be used within the scope of the :meth:`.Query.select_entity_from` method's adaptation services. Suppose a view ``user_view`` also returns rows from ``user``. If we reflect this view into a :class:`.Table`, this view has no relationship to the :class:`.Table` to which we are mapped, however we can use name matching to select from it:: user_view = Table('user_view', metadata, autoload_with=engine) user_view_alias = aliased( User, user_view, adapt_on_names=True) q = session.query(User).\ select_entity_from(user_view_alias).\ order_by(User.name) .. versionchanged:: 1.1.7 The :meth:`.Query.select_entity_from` method now accepts an :func:`.aliased` object as an alternative to a :class:`.FromClause` object. :param from_obj: a :class:`.FromClause` object that will replace the FROM clause of this :class:`.Query`. It also may be an instance of :func:`.aliased`. .. seealso:: :meth:`.Query.select_from` TNrrr&r&r,select_entity_from{ sfzQuery.select_entity_fromcCst|trOt|\}}}t|trt|tr||dkrgSt|tr(|dks1t|tr7|dkr7t||S|||}|durKt|dd|jSt|S|dkrYt|dSt|||ddS)Nrr)rUslicer decode_sliceintrstep)r*itemstartstoprresr&r&r, __getitem__ s(     zQuery.__getitem__cCs|dur$|dur$|jdur|jnd|_|dkr|j|7_|||_n*|dur0|dur0||_n|durN|durN|jdur@|jnd|_|dkrN|j|7_t|jtr^|jdkr`d|_dSdSdS)aComputes the "slice" of the :class:`.Query` represented by the given indices and returns the resulting :class:`.Query`. The start and stop indices behave like the argument to Python's built-in :func:`range` function. This method provides an alternative to using ``LIMIT``/``OFFSET`` to get a slice of the query. For example, :: session.query(User).order_by(User.id).slice(1, 3) renders as .. sourcecode:: sql SELECT users.id AS users_id, users.name AS users_name FROM users ORDER BY users.id LIMIT ? OFFSET ? (2, 1) .. seealso:: :meth:`.Query.limit` :meth:`.Query.offset` Nr)rrrUr)r*rrr&r&r,r s  z Query.slicecCr)zZApply a ``LIMIT`` to the query and return the newly resulting ``Query``. N)r)r*limitr&r&r,r.  z Query.limitcCr)z\Apply an ``OFFSET`` to the query and return the newly resulting ``Query``. N)r)r*offsetr&r&r,r6 rz Query.offsetcGs@|sd|_dS||}t|jtr|j|7_dS||_dS)a{Apply a ``DISTINCT`` to the query and return the newly resulting ``Query``. .. note:: The :meth:`.distinct` call includes logic that will automatically add columns from the ORDER BY of the query to the columns clause of the SELECT statement, to satisfy the common need of the database backend that ORDER BY columns be part of the SELECT list when DISTINCT is used. These columns *are not* added to the list of columns actually fetched by the :class:`.Query`, however, so would not affect results. The columns are passed through when using the :attr:`.Query.statement` accessor, however. :param \*expr: optional column expressions. When present, the PostgreSQL dialect will render a ``DISTINCT ON ()`` construct. TN)rrzrUr)r*exprr&r&r,r> s     zQuery.distinctcG"|jr |j|7_dS||_dS)aApply the prefixes to the query and return the newly resulting ``Query``. :param \*prefixes: optional prefixes, typically strings, not using any commas. In particular is useful for MySQL keywords and optimizer hints: e.g.:: query = sess.query(User.name).\ prefix_with('HIGH_PRIORITY').\ prefix_with('SQL_SMALL_RESULT', 'ALL').\ prefix_with('/*+ BKA(user) */') Would render:: SELECT HIGH_PRIORITY SQL_SMALL_RESULT ALL /*+ BKA(user) */ users.name AS users_name FROM users .. seealso:: :meth:`.HasPrefixes.prefix_with` N)r=)r*prefixesr&r&r, prefix_with^ s zQuery.prefix_withcGr)aGApply the suffix to the query and return the newly resulting ``Query``. :param \*suffixes: optional suffixes, typically strings, not using any commas. .. versionadded:: 1.0.0 .. seealso:: :meth:`.Query.prefix_with` :meth:`.HasSuffixes.suffix_with` N)r>)r*suffixesr&r&r, suffix_with} s zQuery.suffix_withcCst|S)aReturn the results represented by this :class:`.Query` as a list. This results in an execution of the underlying SQL statement. .. warning:: The :class:`.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` )rrwr&r&r,all sz Query.allcCs0t|}t|tjtjfstd||_dS)a%Execute the given SELECT statement and return results. This method bypasses all internal statement compilation, and the statement is executed without modification. The statement is typically either a :func:`~.expression.text` or :func:`~.expression.select` construct, and should return the set of columns appropriate to the entity class represented by this :class:`.Query`. .. seealso:: :ref:`orm_tutorial_literal_sql` - usage examples in the ORM tutorial zBfrom_statement accepts text(), select(), and union() objects only.N)rrvrU TextClauserVrQrRr)r*rr&r&r,from_statement s   zQuery.from_statementcCsD|jdurt|dd}nt|dd}t|dkr |dSdS)aReturn the first result of this ``Query`` or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present). Calling :meth:`.Query.first` results in an execution of the underlying query. .. seealso:: :meth:`.Query.one` :meth:`.Query.one_or_none` Nrr)rrrZr*retr&r&r,first s  z Query.firstcCs6t|}t|}|dkr|dS|dkrdStd)axReturn at most one result or raise an exception. Returns ``None`` if the query selects no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound`` if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities. Calling :meth:`.Query.one_or_none` results in an execution of the underlying query. .. versionadded:: 1.0.9 Added :meth:`.Query.one_or_none` .. seealso:: :meth:`.Query.first` :meth:`.Query.one` rrNz*Multiple rows were found for one_or_none())rrZorm_excMultipleResultsFound)r*rrMr&r&r, one_or_none szQuery.one_or_nonecCs>z|}Wn tjytdw|durtd|S)a6Return exactly one result or raise an exception. Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound`` if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities. Calling :meth:`.one` results in an execution of the underlying query. .. seealso:: :meth:`.Query.first` :meth:`.Query.one_or_none` z"Multiple rows were found for one()NzNo row was found for one())rrr NoResultFoundrr&r&r,one s  z Query.onecCs:z|}t|ts |WS|dWStjyYdSw)a4Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound. >>> session.query(Item).scalar() >>> session.query(Item.id).scalar() 1 >>> session.query(Item.id).filter(Item.id < 0).scalar() None >>> session.query(Item.id, Item.name).scalar() 1 >>> session.query(func.count(Parent.id)).scalar() 20 This results in an execution of the underlying query. rN)rrUrXrrrr&r&r,scalar s  z Query.scalarcCs0|}d|j_|jr|js|j||SrU)rr use_labelsr(rr'_execute_and_instances)r*contextr&r&r,__iter__8 s    zQuery.__iter__cCsP|}z|jr|||jjnd}Wn tjyd}Ynwt|j|Sr6) rr'_get_bind_argsget_bindrQUnboundExecutionErrorrrcompile)r*rbindr&r&r,__str__? sz Query.__str__cKs.|jjdi|}|jr|jdi|j}|Sr)r' connectionrrk)r*kwconnr&r&r,_connection_from_sessionK szQuery._connection_from_sessioncCs2|j||jdd}||j|j}t|j||S)NT)close_with_result)rrexecuterrr instancesquery)r* querycontextrresultr&r&r,rQ s zQuery._execute_and_instancescCs|j||dd}|||jS)NT)r:rr )rr r)r*rr:rr&r&r, _execute_crudY szQuery._execute_crudcKs|d||jd|S)N)r:rr&)rr)r*r r`rr&r&r,r` s  zQuery._get_bind_argscCsdddd|jDDS)aReturn metadata about the columns which would be returned by this :class:`.Query`. Format is a list of dictionaries:: user_alias = aliased(User, name='user2') q = sess.query(User, User.id, user_alias) # this expression: q.column_descriptions # would return: [ { 'name':'User', 'type':User, 'aliased':False, 'expr':User, 'entity': User }, { 'name':'id', 'type':Integer(), 'aliased':False, 'expr':User.id, 'entity': User }, { 'name':'user2', 'type':User, 'aliased':True, 'expr':user_alias, 'entity': user_alias } ] c SsJg|]!\}}|j|jt|dd|j|jdur|jst|ddnddqS)r9FNrE)rrrrrE) _label_namerrrrr)rur5insp_entr&r&r,rx s    z-Query.column_descriptions..cSs(g|]}||jdurt|jndfqSr6)rr)ru_entr&r&r,rx s   rrwr&r&r,column_descriptionse s (  zQuery.column_descriptionscCs"|}|dur t|}t|||S)aGiven a ResultProxy cursor as returned by connection.execute(), return an ORM result as an iterator. e.g.:: result = engine.execute("select * from users") for u in session.query(User).instances(result): print u N)r%rr )r*cursor_Query__contextrr&r&r,r  s zQuery.instancescCst|||S)a?Merge a result into this :class:`.Query` object's Session. Given an iterator returned by a :class:`.Query` of the same structure as this one, return an identical iterator of results, with all mapped instances merged into the session using :meth:`.Session.merge`. This is an optimized method which will merge all mapped instances, preserving the structure of the result rows and unmapped columns with less method overhead than that of calling :meth:`.Session.merge` explicitly for each value. The structure of the results is determined based on the column list of this :class:`.Query` - if these do not correspond, unchecked errors will occur. The 'load' argument is the same as that of :meth:`.Session.merge`. For an example of how :meth:`~.Query.merge_result` is used, see the source code for the example :ref:`examples_caching`, where :meth:`~.Query.merge_result` is used to efficiently restore state from a cache back into a target :class:`.Session`. )r merge_result)r*iteratorloadr&r&r,r rLzQuery.merge_resultcCs&|j|j|j|j|j|jpd|jdS)N)rrrrrr}r)rrrr=r>rr<rwr&r&r, _select_args szQuery._select_argscCs:|j}|ddup|ddup|ddp|ddS)NrrrFr})rrkrir&r&r,_should_nest_selectable s   zQuery._should_nest_selectablecCs*t|dtdjdgS)aA convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...). e.g.:: q = session.query(User).filter(User.name == 'fred') session.query(q.exists()) Producing SQL similar to:: SELECT EXISTS ( SELECT 1 FROM users WHERE users.name = :name_1 ) AS anon_1 The EXISTS construct is usually used in the WHERE clause:: session.query(User.id).filter(q.exists()).scalar() Note that some databases such as SQL Server don't allow an EXISTS expression to be present in the columns clause of a SELECT. To select a simple boolean value based on the exists as a WHERE, use :func:`.literal`:: from sqlalchemy import literal session.query(literal(True)).filter(q.exists()).scalar() F1r)rexistsrrNliteral_columnrrwith_only_columnsrwr&r&r,r s #  z Query.existscCs tjtd}||S)aReturn a count of rows this the SQL formed by this :class:`Query` would return. This generates the SQL for this Query as follows:: SELECT count(1) AS count_1 FROM ( SELECT ) AS anon_1 The above SQL returns a single row, which is the aggregate value of the count function; the :meth:`.Query.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` 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))) rb)rfuncrrr8r)r*colr&r&r,rs5z Query.countevaluatecCstj||}||jS)aOPerform a bulk delete query. Deletes rows matched by this query from the database. E.g.:: sess.query(User).filter(User.age == 25).\ delete(synchronize_session=False) sess.query(User).filter(User.age == 25).\ delete(synchronize_session='evaluate') .. warning:: The :meth:`.Query.delete` method is a "bulk" operation, which bypasses ORM unit-of-work automation in favor of greater performance. **Please read all caveats and warnings below.** :param synchronize_session: chooses the strategy for the removal of matched objects from the session. Valid values are: ``False`` - don't synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, objects may still remain in the session which were in fact deleted which can lead to confusing results if they are accessed via get() or already loaded collections. ``'fetch'`` - performs a select query before the delete to find objects that are matched by the delete query and need to be removed from the session. Matched objects are removed from the session. ``'evaluate'`` - Evaluate the query's criteria in Python straight on the objects in the session. If evaluation of the criteria isn't implemented, an error is raised. The expression evaluator currently doesn't account for differing string collations between the database and Python. :return: the count of rows matched as returned by the database's "row count" feature. .. warning:: **Additional Caveats for bulk query deletes** * This method does **not work for joined inheritance mappings**, since the **multiple table deletes are not supported by SQL** as well as that the **join condition of an inheritance mapper is not automatically rendered**. Care must be taken in any multiple-table delete to first accommodate via some other means how the related table will be deleted, as well as to explicitly include the joining condition between those tables, even in mappings where this is normally automatic. E.g. if a class ``Engineer`` subclasses ``Employee``, a DELETE against the ``Employee`` table would look like:: session.query(Engineer).\ filter(Engineer.id == Employee.id).\ filter(Employee.name == 'dilbert').\ delete() However the above SQL will not delete from the Engineer table, unless an ON DELETE CASCADE rule is established in the database to handle it. Short story, **do not use this method for joined inheritance mappings unless you have taken the additional steps to make this feasible**. * The polymorphic identity WHERE criteria is **not** included for single- or joined- table updates - this must be added **manually** even for single table inheritance. * The method does **not** offer in-Python cascading of relationships - it is assumed that ON DELETE CASCADE/SET NULL/etc. is configured for any foreign key references which require it, otherwise the database may emit an integrity violation if foreign key references are being enforced. After the DELETE, dependent objects in the :class:`.Session` which were impacted by an ON DELETE may not contain the current state, or may have been deleted. This issue is resolved once the :class:`.Session` is expired, which normally occurs upon :meth:`.Session.commit` or can be forced by using :meth:`.Session.expire_all`. Accessing an expired object whose row has been deleted will invoke a SELECT to locate the row; when the row is not found, an :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. * The ``'fetch'`` strategy results in an additional SELECT statement emitted and will significantly reduce performance. * The ``'evaluate'`` strategy performs a scan of all matching objects within the :class:`.Session`; if the contents of the :class:`.Session` are expired, such as via a proceeding :meth:`.Session.commit` call, **this will result in SELECT queries emitted for every matching object**. * The :meth:`.MapperEvents.before_delete` and :meth:`.MapperEvents.after_delete` events **are not invoked** from this method. Instead, the :meth:`.SessionEvents.after_bulk_delete` method is provided to act upon a mass DELETE of entity rows. .. seealso:: :meth:`.Query.update` :ref:`inserts_and_updates` - Core SQL tutorial )r BulkDeletefactoryexec_rowcount)r*synchronize_session delete_opr&r&r,deleteGswz Query.deletecCs(|pi}tj||||}||jS)auPerform a bulk update query. Updates rows matched by this query in the database. E.g.:: sess.query(User).filter(User.age == 25).\ update({User.age: User.age - 10}, synchronize_session=False) sess.query(User).filter(User.age == 25).\ update({"age": User.age - 10}, synchronize_session='evaluate') .. warning:: The :meth:`.Query.update` method is a "bulk" operation, which bypasses ORM unit-of-work automation in favor of greater performance. **Please read all caveats and warnings below.** :param values: a dictionary with attributes names, or alternatively mapped attributes or SQL expressions, as keys, and literal values or sql expressions as values. If :ref:`parameter-ordered mode ` is desired, the values can be passed as a list of 2-tuples; this requires that the :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order` flag is passed to the :paramref:`.Query.update.update_args` dictionary as well. .. versionchanged:: 1.0.0 - string names in the values dictionary are now resolved against the mapped entity; previously, these strings were passed as literal column names with no mapper-level translation. :param synchronize_session: chooses the strategy to update the attributes on objects in the session. Valid values are: ``False`` - don't synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, updated objects may still remain in the session with stale values on their attributes, which can lead to confusing results. ``'fetch'`` - performs a select query before the update to find objects that are matched by the update query. The updated attributes are expired on matched objects. ``'evaluate'`` - Evaluate the Query's criteria in Python straight on the objects in the session. If evaluation of the criteria isn't implemented, an exception is raised. The expression evaluator currently doesn't account for differing string collations between the database and Python. :param update_args: Optional dictionary, if present will be passed to the underlying :func:`.update` construct as the ``**kw`` for the object. May be used to pass dialect-specific arguments such as ``mysql_limit``, as well as other special arguments such as :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`. .. versionadded:: 1.0.0 :return: the count of rows matched as returned by the database's "row count" feature. .. warning:: **Additional Caveats for bulk query updates** * The method does **not** offer in-Python cascading of relationships - it is assumed that ON UPDATE CASCADE is configured for any foreign key references which require it, otherwise the database may emit an integrity violation if foreign key references are being enforced. After the UPDATE, dependent objects in the :class:`.Session` which were impacted by an ON UPDATE CASCADE may not contain the current state; this issue is resolved once the :class:`.Session` is expired, which normally occurs upon :meth:`.Session.commit` or can be forced by using :meth:`.Session.expire_all`. * The ``'fetch'`` strategy results in an additional SELECT statement emitted and will significantly reduce performance. * The ``'evaluate'`` strategy performs a scan of all matching objects within the :class:`.Session`; if the contents of the :class:`.Session` are expired, such as via a proceeding :meth:`.Session.commit` call, **this will result in SELECT queries emitted for every matching object**. * The method supports multiple table updates, as detailed in :ref:`multi_table_updates`, and this behavior does extend to support updates of joined-inheritance and other multiple table mappings. However, the **join condition of an inheritance mapper is not automatically rendered**. Care must be taken in any multiple-table update to explicitly include the joining condition between those tables, even in mappings where this is normally automatic. E.g. if a class ``Engineer`` subclasses ``Employee``, an UPDATE of the ``Engineer`` local table using criteria against the ``Employee`` local table might look like:: session.query(Engineer).\ filter(Engineer.id == Employee.id).\ filter(Employee.name == 'dilbert').\ update({"engineer_type": "programmer"}) * The polymorphic identity WHERE criteria is **not** included for single- or joined- table updates - this must be added **manually**, even for single table inheritance. * The :meth:`.MapperEvents.before_update` and :meth:`.MapperEvents.after_update` events **are not invoked from this method**. Instead, the :meth:`.SessionEvents.after_bulk_update` method is provided to act upon a mass UPDATE of entity rows. .. seealso:: :meth:`.Query.delete` :ref:`inserts_and_updates` - Core SQL tutorial )r BulkUpdater#r$r%)r*rFr& update_args update_opr&r&r,rsz Query.updatecCs|jjr|jjD]}||}|dur||ur|}|jsd|_qt|}|jdur*|S||_|j|_|jD]}|||q4|j D]}|d}||g|ddRq@|j r\t |j |_ |j rd|||jst|jrotdtd|jr|jr|||_|S|||_|S)NFrrzyNo column-based properties specified for refresh operation. Use session.expire() to reload collections and related items.z4Query contains no columns with which to SELECT from.)dispatchbefore_compile_bake_okr%rrrr/ setup_contextcreate_eager_joins from_clauserfromsr6_adjust_for_single_inheritanceprimary_columnsrrQrmulti_row_eager_loadersr_compound_eager_statement_simple_statement)r*rr` new_queryrrErecstrategyr&r&r,rIsF         zQuery._compile_contextc Cs*|jr t|j|j}nd|_g}tj|j||jf|j|j|jd|j }|j |_ |j D]}|j |}q.|j r?|j|j }|}|}t|||_tj|g|j|jd}|j duri|j jduri|j |_ |}|jD] }t|||j}qp|||jr|j|j|j|j|j|S)Nrbrr)r)rr> expand_column_list_from_order_byr4rselectrr2rrrrcrfr#r'rWr\r?rKsecondary_columnsrr eager_joinsrF splice_joinsstop_on append_fromappend_order_bycopy_and_processeager_order_by) r*rorder_by_col_exprinnerhintrdrr1 eager_joinr&r&r,r6sT        zQuery._compound_eager_statementcCs|jsd|_|jdur|jr|jt|j|j7_|jt|j7_t j |j|j |j f|j|j |jd|j}|j|_|jD]}|j|}qE|jrV|j|j}|jr_|j|j|S)NTr;)rrr4r>r<r2rXr?rFrr=r>rrrrrcrfr#r'rErC)r*rrrHr&r&r,r7s6     zQuery._simple_statementcCst|j}|jr'|j|jvr't|j}|jr|j}nd}||j|fg}|D],\}}||jvr3q)|j j }|durU|rB| |}| |dd}t t j|j||_q)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)rr7rFrPrr9rBrrr:_single_table_criteriontraverserrrand_True__ifnoner)r*rrorrKrF single_critr&r&r,r3s,      z$Query._adjust_for_single_inheritancer6)TT)NNNNN)NFFr)NN)rb)FFNFFrq)r!)r!N)r/ __module__ __qualname____doc__rrrrrrrrr<rr=r>rrrr frozensetr#rr+rr(rrrrYrrPr7rr]r immutabledictr;rrrrXrZrcr6rr_path_registryrr1r.r|r-r)r3r=rergrprzr r~rrrrrrr1rrrrrr\rrrrrrrrrrrrrrr@rrrrrrrrrr;rrkr PASSIVE_OFFr rr'r*rr,rr3r4r8r:r5rF_valuesrrKrNpending_deprecationrOrTrVrRrarfrgrhrk deprecatedrorurr0r{rr}rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrrrrr(rrr6r7r3r&r&r&r,r$@s  ! /  -           ;           ! EY 6:     6 6            +  "   "'       M`B$  / g -      #   ?    *8{ 6 Ir$c@seZdZeddZdS)rlcCs\|dvrdS|dkrd}d}n|dkrd}}n|dkr!d}d}ntd|t||dS) NrrpTFr update_nowaitz"Unknown with_lockmode argument: %r)rprq)rQrRrl)r*rnrprqr&r&r,rm s  zLockmodeArg.parse_legacy_queryN)r/rPrQ classmethodrmr&r&r&r,rl srlc@s eZdZdZddZddZdS)r.z:represent an entity column returned within a Query result.cOsH|tur|d}t|tjst|rt}n t|trt}nt}t |S)Nr) r.rUrrr rBundle _BundleEntityrDobjectr)rr%rjrEr&r&r,r$s  z_QueryEntity.__new__cCs|j|j}|j|_|Sr6rrr&r&r,r1s z_QueryEntity._cloneN)r/rPrQrRrrr&r&r&r,r.!s r.c@sxeZdZdZddZdZdZddZddZe d d Z e d d Z d dZ ddZ ddZddZddZddZdS)rz mapper/class/AliasedClass entitycCs0|js||_|j|d|_|g|_||_dSrU)r0r/rSr1r+r)r*r rEr&r&r,r-:s   z_MapperEntity.__init__TcCs`|j|_||_|j|_|j|_|j|_|j|_||_|jr#|jj |_ n|jj j |_ |jj |_dSr6)r:rGr@r9with_polymorphic_mappers_with_polymorphicr_polymorphic_discriminatorrrrrr/rUrr*rFrGr&r&r,rCFs  z_MapperEntity.setup_entitycCsh|jrtd|dur||jdS|j||\}}||_||_||_||jt ||jj dS)zReceive an update from a call to query.with_polymorphic(). Note the newer style of using a free standing with_polymporphic() construct doesn't make use of this method. z6Can't use with_polymorphic() against an Aliased objectN) r9NotImplementedErrorrgr:_with_polymorphic_argsr`rar@r=r>r?rA)r*r rr@rmappersrbr&r&r,rTs"  z"_MapperEntity.set_with_polymorphiccCs|jjSr6)r:rrwr&r&r,rtsz_MapperEntity.typecCrr6)rrwr&r&r,rxsz'_MapperEntity.entity_zero_or_selectablecCs t|j|Sr6)rrr*rEr&r&r,r|s z_MapperEntity.corresponds_tocCs|j|dSr6)r/rS)r*r selr&r&r,r?rz!_MapperEntity.adapt_to_selectablecCsTd}|js|jr|j|jd}n|j}|r%|jr!||j}|S|}|S|j}|Sr6)r9r(rkr:rGr]wrap)r*r rrKrr&r&r,_get_entity_clausess z!_MapperEntity._get_entity_clausesc Cs|||}|jr|r||j}n|s|j}|s&|jjr&t|j|jj}|j |ur2|j }|j }nd}}t j |j|||j||||jd}||jfS)N)rrpolymorphic_discriminator)rirKrhr:_requires_row_aliasingr>r?r@rAr0rrr_instance_processorrrar)r*r rrrKrr _instancer&r&r, row_processors0      z_MapperEntity.row_processorc Cs~|||}|j|jf7_|jdur)|jjr)|jj|_|r)|t|j|_tj ||j||j ||j |j |j |jd dS)NF)r;rrj)rir2r@rr: adapt_listrr2r_setup_entity_queryrr4r`rra)r*r rrKr&r&r,r/s&    z_MapperEntity.setup_contextcC t|jSr6)rr:rwr&r&r,r z_MapperEntity.__str__N)r/rPrQrRr-ruse_id_for_hashrCrr1rrrr?rirnr/rr&r&r&r,r7s"  # rc@sbeZdZdZdZ dZdZdZddZdZ dZ ddZ dd Z e d d Zd d ZddZdS)r\a>A grouping of SQL expressions that are returned by a :class:`.Query` under one namespace. The :class:`.Bundle` essentially allows nesting of the tuple-based results returned by a column-oriented :class:`.Query` object. It also is extensible via simple subclassing, where the primary capability to override is that of how the set of expressions should be returned, allowing post-processing as well as custom return types, without involving ORM identity-mapped classes. .. versionadded:: 0.9.0 .. seealso:: :ref:`bundles` FcOsJ||_|_||_t|_|_|jdd|D|d|j|_dS)aQConstruct a new :class:`.Bundle`. e.g.:: bn = Bundle("mybundle", MyClass.x, MyClass.y) for row in session.query(bn).filter( bn.c.x == 5).filter(bn.c.y == 4): print(row.mybundle.x, row.mybundle.y) :param name: name of the bundle. :param \*exprs: columns or SQL expressions comprising the bundle. :param single_entity=False: if True, rows for this :class:`.Bundle` can be returned as a "single entity" outside of any enclosing tuple in the same manner as a mapped entity. css"|] }t|d|j|fVqdS)r N)r_label)rur r&r&r,r s z"Bundle.__init__.. single_entityN) rrtexprsr!rrErrfru)r*rrvrr&r&r,r-s  zBundle.__init__NcCs |j|j}|j|j|Sr6)rrrr)r*clonedr&r&r,r,sz Bundle._clonecCstj|jddiS)NgroupF)r ClauseListrvrwr&r&r,r1rzBundle.__clause_element__cCs |jSr6)rrzrwr&r&r,rz4rzBundle.clausescCs|}||_|S)z.proc..r&r{ keyed_tupleprocsr{r,rzKsz)Bundle.create_row_processor..proc)rlightweight_named_tuple)r*r rrrzr&r}r,create_row_processor?s zBundle.create_row_processor)r/rPrQrRrurrOr9r-rErrrr1rzrrr&r&r&r,r\s$  r\c@sreZdZdZdddZeddZeddZed d Zd d Z ed dZ ddZ ddZ ddZ ddZdS)r]FTcCsn|j|||_|_t||_|j|_g|_|r0|jD]}t|t r*t ||qt ||q|jj |_ dSr6)r/rSbundlerrrrrvrUr\r]rDrur)r*r rsetup_entitiesrr&r&r,r-Ts       z_BundleEntity.__init__cCs|j}|dur |jSdSr6)rr:)r*rr&r&r,r:dsz_BundleEntity.mappercCs g}|jD]}||jq|Sr6)r/extendr+)r*r+r5r&r&r,r+ls z_BundleEntity.entitiescC&|jD] }|j}|dur|SqdSr6)r/rr*r5rr&r&r,rs z_BundleEntity.entity_zerocCsdSrr&rfr&r&r,r|sz_BundleEntity.corresponds_tocCrr6)r/rrr&r&r,rrz'_BundleEntity.entity_zero_or_selectablecCs,t||jdd}|jD]}|||q dS)NF)r)r]rr/r?)r*r rgrr5r&r&r,r?s z!_BundleEntity.adapt_to_selectablecC|jD]}|||qdSr6)r/rC)r*rFrGr5r&r&r,rC z_BundleEntity.setup_entitycCrr6)r/r/)r*r rr5r&r&r,r/rz_BundleEntity.setup_contextcs:tfdd|jD\}}|j||}||jfS)Ncsg|] }|qSr&)rn)rur5rr rr&r,rxs z/_BundleEntity.row_processor..)zipr/rrr)r*r rrrrrzr&rr,rns z_BundleEntity.row_processorNrq)r/rPrQrsr-r1r:r+rrrr?rCr/rnr&r&r&r,r]Qs        r]c@sZeZdZdZdddZdZeddZdd Zd d Z d d Z ddZ ddZ ddZ dS)rDzColumn/expression based entity.Nc s6||_||_d}d}t|tjr%tdt|}|j|_ d}d}d}n+t|t j t j frPt|dd}|dur:d}|j|_ |}d}t|trPt||dSt|tjsxt|drp|jD]}||urfn t|||dq^dStd|f|st|dd|_ d}|j|_}|j |_|jst|d ds||j }|j|||_ t!|_"t!|j#|_$|s||_%|r|g|_&|j'|_'ng|_&d|_'t!|j&|_(dSd d t)j*|dd D} t+d d | D|_&t!fdd | D|_(|j&r|j&d|_%|j%j'|_'dS|jdur|j|_%d|_'dSd|_%d|_'dS)NTFzPlain string expression passed to Query() should be explicitly declared using literal_column(); automatic coercion of this value will be removed in SQLAlchemy 1.4r_select_iterable) namespacez.)include_scalar_selectscSs g|] }d|jvr|jdqSrrrr&r&r,rx s  cs,g|]}d|jvr|jr|jdqSr)rj intersection _from_objectsr actual_fromsr&r,rxs  r),rrrUrrwarn_deprecatedrrrrrrrrrr _query_clause_elementr\r] ColumnElementrNrrDrQrrhashablersrtrr/rSrJrr2rrrr+r:_from_entitiesr>surface_column_elements unique_list) r*r rJrsearch_entities check_column_entityrtype_ all_elementsr&rr,r-s                   z_ColumnEntity.__init__FcCs(|jdur|jS|jrt|jdSdS)Nr)rrrrwr&r&r,r$s z'_ColumnEntity.entity_zero_or_selectablecCs.t|||j}|j|_|j|_|j|_dSr6)rDcorresponding_columnrJrrr+)r*r rgrr&r&r,r?-s z!_ColumnEntity.adapt_to_selectablecCs8d|jvr |j|_|j|jjr|j|jdSdS)Nr@)rr@rrrr2addrbr&r&r,rC3s z_ColumnEntity.setup_entitycCs8|jdurdSt|r||juSt|j o||jSr)rr rrfr&r&r,r:s   z_ColumnEntity.corresponds_tocCsbd|f|jvr|jd|f}n||jdd}|jr|}|jr'|jj|}||}||jfS)N fetch_columnFT) rrrrJrj _deannotaterKrE_getterr)r*r rrrJgetterr&r&r,rnEs   z_ColumnEntity.row_processorcCsP||jdd}|jr|}|jt|j7_|j|||jd|f<dS)NFTr) rrrJrjrr2rXr4rSr)r*r rrJr&r&r,r/Vs  z_ColumnEntity.setup_contextcCrqr6)rrJrwr&r&r,rcrrz_ColumnEntity.__str__r6)r/rPrQrRr-rr1rr?rCrrnr/rr&r&r&r,rDs w   rDc@seZdZdZddZdS)r%)r5rKr2 for_updater r'r*rinvoke_all_eagersrrr4r>rEr?r0propagate_optionsrrr1rrrrrunidpartialspost_load_pathsrcCs |jdur t|jtjr|jjs|jjs|j|_n|j|_nd|_|j|_ |j |_ |j |_ d|_d|_d|_d|_||_|j|_|j|_|j|_|j|_|j|_|j|_g|_g|_g|_ i|_!g|_"t#dd|j$D|_%|j&'|_(|jdur|j)|_*dSd|_*dS)NFr&css|]}|jr|VqdSr6)propagate_to_loadersrtr&r&r,rs  z(QueryContext.__init__..)+rrUrrV_textualr apply_labelsrrYr1rrrrr5rKr2rr r'r(r*rrr+rrrrrr4r>rEr?r0rrZrrXr8rrr)r*r r&r&r,r-sH       zQueryContext.__init__N)r/rPrQ __slots__r-r&r&r&r,r%gs r%c@seZdZddZddZdS) AliasOptioncCr)a!Return a :class:`.MapperOption` that will indicate to the :class:`.Query` that the main table has been aliased. This is a seldom-used option to suit the very rare case that :func:`.contains_eager` is being used in conjunction with a user-defined SELECT statement that aliases the parent table. E.g.:: # define an aliased UNION called 'ulist' ulist = users.select(users.c.user_id==7).\ union(users.select(users.c.user_id>7)).\ alias('ulist') # add on an eager load of "addresses" statement = ulist.outerjoin(addresses).\ select().apply_labels() # create query, indicating "ulist" will be an # alias for the main table, "addresses" # property should be eager loaded query = session.query(User).options( contains_alias(ulist), contains_eager(User.addresses)) # then get results via the statement results = query.from_statement(statement).all() :param alias: is the string name of an alias, or a :class:`~.sql.expression.Alias` object representing the alias. N)rW)r*rWr&r&r,r-s !zAliasOption.__init__cCs8t|jtjr|j|j}n|j}t||_dSr6) rUrWrrrr<r>r?r])r*r rWr&r&r,r\szAliasOption.process_queryN)r/rPrQr-r\r&r&r&r,rs #rN);rR itertoolsrrrrrrrr baser r r r rr path_registryrrrrrrrrrrrQrrrrrr>r sql.baser!sql.expressionr"sql.selectabler#__all__rootrU_self_inspects class_loggerr^r$rlr.rr\r]rDr% MapperOptionrr&r&r&r,s                                 h"xW@K