diff options
Diffstat (limited to 'lib/sqlalchemy/orm/query.py')
-rw-r--r-- | lib/sqlalchemy/orm/query.py | 469 |
1 files changed, 234 insertions, 235 deletions
diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index ed600a2f0..f981399db 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -6,14 +6,14 @@ """The Query class and support. -Defines the :class:`.Query` class, the central +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 +: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. """ @@ -21,7 +21,7 @@ database to return iterable result sets. from itertools import chain from . import ( - attributes, interfaces, object_mapper, persistence, + attributes, interfaces, object_mapper, persistence, exc as orm_exc, loading ) from .util import ( @@ -57,15 +57,15 @@ class Query(object): """ORM-level SQL construction object. :class:`.Query` is the source of all SELECT statements generated by the - ORM, both those formulated by end-user query operations as well as by - high level internal operations such as related collection loading. It + ORM, both those formulated by end-user query operations as well as by + high level internal operations such as related collection loading. It features a generative interface whereby successive calls return a new - :class:`.Query` object, a copy of the former with additional + :class:`.Query` object, a copy of the former with additional criteria and options associated with it. - :class:`.Query` objects are normally initially generated using the - :meth:`~.Session.query` method of :class:`.Session`. For a full - walkthrough of :class:`.Query` usage, see the + :class:`.Query` objects are normally initially generated using the + :meth:`~.Session.query` method of :class:`.Session`. For a full + walkthrough of :class:`.Query` usage, see the :ref:`ormtutorial_toplevel`. """ @@ -133,16 +133,16 @@ class Query(object): if ext_info.mapper.mapped_table not in \ self._polymorphic_adapters: self._mapper_loads_polymorphically_with( - ext_info.mapper, + ext_info.mapper, sql_util.ColumnAdapter( - ext_info.selectable, + ext_info.selectable, ext_info.mapper._equivalent_columns ) ) aliased_adapter = None elif ext_info.is_aliased_class: aliased_adapter = sql_util.ColumnAdapter( - ext_info.selectable, + ext_info.selectable, ext_info.mapper._equivalent_columns ) else: @@ -199,8 +199,8 @@ class Query(object): def _adapt_col_list(self, cols): return [ self._adapt_clause( - expression._literal_as_text(o), - True, True) + expression._literal_as_text(o), + True, True) for o in cols ] @@ -209,7 +209,7 @@ class Query(object): self._orm_only_adapt = False def _adapt_clause(self, clause, as_filter, orm_only): - """Adapt incoming clauses to transformations which + """Adapt incoming clauses to transformations which have been applied within this query.""" adapters = [] @@ -228,12 +228,12 @@ class Query(object): if self._from_obj_alias: # for the "from obj" alias, apply extra rule to the - # 'ORM only' check, if this query were generated from a + # 'ORM only' check, if this query were generated from a # subquery of itself, i.e. _from_selectable(), apply adaption # to all SQL constructs. adapters.append( ( - getattr(self, '_orm_only_from_obj_alias', orm_only), + getattr(self, '_orm_only_from_obj_alias', orm_only), self._from_obj_alias.replace ) ) @@ -261,8 +261,8 @@ class Query(object): return e return visitors.replacement_traverse( - clause, - {}, + clause, + {}, replace ) @@ -297,7 +297,7 @@ class Query(object): def _only_mapper_zero(self, rationale=None): if len(self._entities) > 1: raise sa_exc.InvalidRequestError( - rationale or + rationale or "This operation requires a Query " "against a single mapper." ) @@ -318,7 +318,7 @@ class Query(object): def _only_entity_zero(self, rationale=None): if len(self._entities) > 1: raise sa_exc.InvalidRequestError( - rationale or + rationale or "This operation requires a Query " "against a single mapper." ) @@ -392,13 +392,13 @@ class Query(object): ): if getattr(self, attr) is not notset: raise sa_exc.InvalidRequestError( - "Can't call Query.%s() when %s has been called" % + "Can't call Query.%s() when %s has been called" % (meth, methname) ) - def _get_options(self, populate_existing=None, - version_check=None, - only_load_props=None, + def _get_options(self, populate_existing=None, + version_check=None, + only_load_props=None, refresh_state=None): if populate_existing: self._populate_existing = populate_existing @@ -435,17 +435,17 @@ class Query(object): return stmt._annotate({'no_replacement_traverse': True}) def subquery(self, name=None): - """return the full SELECT statement represented by + """return the full SELECT statement represented by this :class:`.Query`, embedded within an :class:`.Alias`. Eager JOIN generation within the query is disabled. The statement will not have disambiguating labels - applied to the list of selected columns unless the + applied to the list of selected columns unless the :meth:`.Query.with_labels` method is used to generate a new :class:`.Query` with the option enabled. - :param name: string name to be assigned as the alias; + :param name: string name to be assigned as the alias; this is passed through to :meth:`.FromClause.alias`. If ``None``, a name will be deterministically generated at compile time. @@ -455,23 +455,23 @@ class Query(object): return self.enable_eagerloads(False).statement.alias(name=name) def cte(self, name=None, recursive=False): - """Return the full SELECT statement represented by this + """Return the full SELECT statement represented by this :class:`.Query` represented as a common table expression (CTE). .. versionadded:: 0.7.6 - Parameters and usage are the same as those of the - :meth:`._SelectBase.cte` method; see that method for + Parameters and usage are the same as those of the + :meth:`._SelectBase.cte` method; see that method for further details. - Here is the `Postgresql WITH - RECURSIVE example + 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 + 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 + 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 @@ -483,8 +483,8 @@ class Query(object): quantity = Column(Integer) included_parts = session.query( - Part.sub_part, - Part.part, + Part.sub_part, + Part.part, Part.quantity).\\ filter(Part.part=="our part").\\ cte(name="included_parts", recursive=True) @@ -493,8 +493,8 @@ class Query(object): parts_alias = aliased(Part, name="p") included_parts = included_parts.union_all( session.query( - parts_alias.part, - parts_alias.sub_part, + parts_alias.part, + parts_alias.sub_part, parts_alias.quantity).\\ filter(parts_alias.part==incl_alias.c.sub_part) ) @@ -515,8 +515,8 @@ class Query(object): statement.cte(name=name, recursive=recursive) def label(self, name): - """Return the full SELECT statement represented by this - :class:`.Query`, converted + """Return the full SELECT statement represented by this + :class:`.Query`, converted to a scalar subquery with a label of the given name. Analogous to :meth:`sqlalchemy.sql._SelectBaseMixin.label`. @@ -529,7 +529,7 @@ class Query(object): def as_scalar(self): - """Return the full SELECT statement represented by this :class:`.Query`, converted + """Return the full SELECT statement represented by this :class:`.Query`, converted to a scalar subquery. Analogous to :meth:`sqlalchemy.sql._SelectBaseMixin.as_scalar`. @@ -546,7 +546,7 @@ class Query(object): @_generative() def enable_eagerloads(self, value): - """Control whether or not eager joins and subqueries are + """Control whether or not eager joins and subqueries are rendered. When set to False, the returned Query will not render @@ -582,17 +582,17 @@ class Query(object): def enable_assertions(self, value): """Control whether assertions are generated. - When set to False, the returned Query will - not assert its state before certain operations, + 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 + 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 + 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. @@ -604,7 +604,7 @@ class Query(object): def whereclause(self): """A readonly attribute which returns the current WHERE criterion for this Query. - This returned value is a SQL expression construct, or ``None`` if no + This returned value is a SQL expression construct, or ``None`` if no criterion has been established. """ @@ -612,39 +612,39 @@ class Query(object): @_generative() def _with_current_path(self, path): - """indicate that this query applies to objects loaded + """indicate 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 + 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. """ self._current_path = path @_generative(_no_clauseelement_condition) - def with_polymorphic(self, - cls_or_mappers, - selectable=None, + def with_polymorphic(self, + cls_or_mappers, + selectable=None, polymorphic_on=None): """Load columns for inheriting classes. - :meth:`.Query.with_polymorphic` applies transformations + :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 + 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. .. versionchanged:: 0.8 - A new and more flexible function - :func:`.orm.with_polymorphic` supersedes + A new and more flexible function + :func:`.orm.with_polymorphic` supersedes :meth:`.Query.with_polymorphic`, as it can apply the equivalent functionality to any set of columns or classes in the :class:`.Query`, not just the "zero mapper". See that @@ -657,8 +657,8 @@ class Query(object): "No primary mapper set up for this Query.") entity = self._entities[0]._clone() self._entities = [entity] + self._entities[1:] - entity.set_with_polymorphic(self, - cls_or_mappers, + entity.set_with_polymorphic(self, + cls_or_mappers, selectable=selectable, polymorphic_on=polymorphic_on) @@ -671,15 +671,15 @@ class Query(object): 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 + 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 many DBAPIs do not "stream" results, pre-buffering - all rows before making them available, including mysql-python and - psycopg2. :meth:`~sqlalchemy.orm.query.Query.yield_per` will also + all rows before making them available, including mysql-python and + psycopg2. :meth:`~sqlalchemy.orm.query.Query.yield_per` will also set the ``stream_results`` execution option to ``True``, which currently is only understood by psycopg2 and causes server side cursors to be used. @@ -690,7 +690,7 @@ class Query(object): self._execution_options['stream_results'] = True def get(self, ident): - """Return an instance based on the given primary key identifier, + """Return an instance based on the given primary key identifier, or ``None`` if not found. E.g.:: @@ -699,24 +699,24 @@ class Query(object): some_object = session.query(VersionedFoo).get((5, 10)) - :meth:`~.Query.get` is special in that it provides direct + :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, + 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 + :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 + 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, @@ -728,7 +728,7 @@ class Query(object): A lazy-loading, many-to-one attribute configured by :func:`.relationship`, using a simple - foreign-key-to-primary-key criterion, will also use an + 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 :ref:`loading_toplevel` @@ -737,10 +737,10 @@ class Query(object): :param ident: A scalar or tuple value representing the primary key. For a composite primary key, the order of identifiers corresponds in most cases - to that of the mapped :class:`.Table` object's + to that of the mapped :class:`.Table` object's primary key columns. For a :func:`.mapper` that was given the ``primary key`` argument during - construction, the order of identifiers corresponds + construction, the order of identifiers corresponds to the elements present in this collection. :return: The object instance, or ``None``. @@ -792,14 +792,14 @@ class Query(object): :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 + 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. """ self._correlate = self._correlate.union( - _orm_selectable(s) + _orm_selectable(s) for s in args) @_generative() @@ -816,11 +816,11 @@ class Query(object): @_generative() def populate_existing(self): - """Return a :class:`.Query` that will expire and refresh all instances + """Return a :class:`.Query` that will expire and refresh all instances as they are loaded, or reused from the current :class:`.Session`. - :meth:`.populate_existing` does not improve behavior when - the ORM is used normally - the :class:`.Session` object's usual + :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. @@ -841,7 +841,7 @@ class Query(object): def with_parent(self, instance, property=None): """Add filtering criterion that relates the given instance - to a child object or collection, using its attribute state + to a child object or collection, using its attribute state as well as an established :func:`.relationship()` configuration. @@ -866,7 +866,7 @@ class Query(object): else: raise sa_exc.InvalidRequestError( "Could not locate a property which relates instances " - "of class '%s' to instances of class '%s'" % + "of class '%s' to instances of class '%s'" % ( self._mapper_zero().class_.__name__, instance.__class__.__name__) @@ -876,7 +876,7 @@ class Query(object): @_generative() def add_entity(self, entity, alias=None): - """add a mapped entity to the list of result columns + """add a mapped entity to the list of result columns to be returned.""" if alias is not None: @@ -895,7 +895,7 @@ class Query(object): self.session = session def from_self(self, *entities): - """return a Query that selects from this Query's + """return a Query that selects from this Query's SELECT statement. \*entities - optional list of entities which will replace @@ -917,11 +917,11 @@ class Query(object): @_generative() def _from_selectable(self, fromclause): for attr in ( - '_statement', '_criterion', + '_statement', '_criterion', '_order_by', '_group_by', - '_limit', '_offset', - '_joinpath', '_joinpoint', - '_distinct', '_having', + '_limit', '_offset', + '_joinpath', '_joinpoint', + '_distinct', '_having', '_prefixes', ): self.__dict__.pop(attr, None) @@ -937,7 +937,7 @@ class Query(object): e.adapt_to_selectable(self, self._from_obj[0]) def values(self, *columns): - """Return an iterator yielding result tuples corresponding + """Return an iterator yielding result tuples corresponding to the given list of columns""" if not columns: @@ -950,7 +950,7 @@ class Query(object): _values = values def value(self, column): - """Return a scalar result corresponding to the given + """Return a scalar result corresponding to the given column expression.""" try: # Py3K @@ -975,7 +975,7 @@ class Query(object): filter(User.name.like('%ed%')).\\ order_by(Address.email) - # given *only* User.id==5, Address.email, and 'q', what + # 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).\\ @@ -992,7 +992,7 @@ class Query(object): @_generative() def add_columns(self, *column): - """Add one or more column expressions to the list + """Add one or more column expressions to the list of result columns to be returned.""" self._entities = list(self._entities) @@ -1003,13 +1003,13 @@ class Query(object): # given arg is a FROM clause self._set_entity_selectables(self._entities[l:]) - @util.pending_deprecation("0.7", - ":meth:`.add_column` is superseded by :meth:`.add_columns`", + @util.pending_deprecation("0.7", + ":meth:`.add_column` is superseded by :meth:`.add_columns`", False) def add_column(self, column): """Add a column expression to the list of result columns to be returned. - Pending deprecation: :meth:`.add_column` will be superseded by + Pending deprecation: :meth:`.add_column` will be superseded by :meth:`.add_columns`. """ @@ -1068,13 +1068,13 @@ class Query(object): @_generative() def with_hint(self, selectable, text, dialect_name='*'): - """Add an indexing hint for the given entity or selectable to + """Add an indexing 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 + 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. """ mapper, selectable, is_aliased_class = _entity_info(selectable) @@ -1085,7 +1085,7 @@ class Query(object): def execution_options(self, **kwargs): """ Set non-SQL options which take effect during execution. - The options are the same as those accepted by + The options are the same as those accepted by :meth:`.Connection.execution_options`. Note that the ``stream_results`` execution option is enabled @@ -1108,14 +1108,14 @@ class Query(object): ``FOR UPDATE`` (standard SQL, supported by most dialects) ``'update_nowait'`` - passes ``for_update='nowait'``, which - translates to ``FOR UPDATE NOWAIT`` (supported by Oracle, + translates to ``FOR UPDATE NOWAIT`` (supported by Oracle, PostgreSQL 8.1 upwards) ``'read'`` - passes ``for_update='read'``, which translates to - ``LOCK IN SHARE MODE`` (for MySQL), and ``FOR SHARE`` (for + ``LOCK IN SHARE MODE`` (for MySQL), and ``FOR SHARE`` (for PostgreSQL) - ``'read_nowait'`` - passes ``for_update='read_nowait'``, which + ``'read_nowait'`` - passes ``for_update='read_nowait'``, which translates to ``FOR SHARE NOWAIT`` (supported by PostgreSQL). .. versionadded:: 0.7.7 @@ -1126,7 +1126,7 @@ class Query(object): @_generative() def params(self, *args, **kwargs): - """add values for bind parameters which may have been + """add values for bind parameters which may have been specified in filter(). parameters may be specified using \**kwargs, or optionally a single @@ -1158,7 +1158,7 @@ class Query(object): session.query(MyClass).\\ filter(MyClass.name == 'some name', MyClass.id > 5) - The criterion is any SQL expression object applicable to the + 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. @@ -1200,8 +1200,8 @@ class Query(object): 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 + 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`. See also: @@ -1216,15 +1216,15 @@ class Query(object): @_generative(_no_statement_condition, _no_limit_offset) def order_by(self, *criterion): - """apply one or more ORDER BY criterion to the query and return + """apply one or more ORDER BY criterion to the query and return the newly resulting ``Query`` - All existing ORDER BY settings can be suppressed by + All existing ORDER BY settings can be suppressed by passing ``None`` - this will suppress any ORDER BY configured on mappers as well. Alternatively, an existing ORDER BY setting on the Query - object can be entirely cancelled by passing ``False`` + object can be entirely cancelled by passing ``False`` as the value - use this before calling methods where an ORDER BY is invalid. @@ -1248,11 +1248,10 @@ class Query(object): @_generative(_no_statement_condition, _no_limit_offset) def group_by(self, *criterion): - """apply one or more GROUP BY criterion to the query and return + """apply one or more GROUP BY criterion to the query and return the newly resulting :class:`.Query`""" criterion = list(chain(*[_orm_columns(c) for c in criterion])) - criterion = self._adapt_col_list(criterion) if self._group_by is False: @@ -1266,15 +1265,15 @@ class Query(object): newly resulting :class:`.Query`. :meth:`having` is used in conjunction with :meth:`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) - + """ if isinstance(criterion, basestring): @@ -1310,7 +1309,7 @@ class Query(object): will nest on each ``union()``, and produces:: - SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION + SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y) UNION SELECT * FROM Z) Whereas:: @@ -1319,14 +1318,14 @@ class Query(object): produces:: - SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION + 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 + :class:`.Query` object will not render ORDER BY within its SELECT statement. """ @@ -1397,29 +1396,29 @@ class Query(object): **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 + 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`` + 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 + 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 + ``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 + :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:: @@ -1436,17 +1435,17 @@ class Query(object): **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, + 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:`.join` will raise an error if - either there are no foreign keys between the two entities, or if + The above calling form of :meth:`.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 + 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`:: @@ -1455,11 +1454,11 @@ class Query(object): **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 + 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` + 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 + 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:: @@ -1473,13 +1472,13 @@ class Query(object): Where above, the generated SQL would be similar to:: - SELECT user.* FROM user + 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` + 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 @@ -1489,7 +1488,7 @@ class Query(object): q = session.query(User).join(Address, User.id==Address.user_id) .. versionchanged:: 0.7 - In SQLAlchemy 0.6 and earlier, the two argument form of + In SQLAlchemy 0.6 and earlier, the two argument form of :meth:`~.Query.join` requires the usage of a tuple: ``query(User).join((Address, User.id==Address.user_id))``\ . This calling form is accepted in 0.7 and further, though @@ -1500,9 +1499,9 @@ class Query(object): **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` + 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]).\\ @@ -1512,7 +1511,7 @@ class Query(object): 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:`~.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 @@ -1526,12 +1525,12 @@ class Query(object): Producing SQL similar to:: - SELECT user.* FROM user + SELECT user.* FROM user JOIN ( - SELECT address.id AS id, - address.user_id AS user_id, - address.email_address AS email_address - FROM address + 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 @@ -1548,7 +1547,7 @@ class Query(object): 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`` + the :class:`.Query` to select first from the ``User`` entity:: q = session.query(Address).select_from(User).\\ @@ -1557,8 +1556,8 @@ class Query(object): Which will produce SQL similar to:: - SELECT address.* FROM user - JOIN address ON user.id=address.user_id + SELECT address.* FROM user + JOIN address ON user.id=address.user_id WHERE user.name = :name_1 **Constructing Aliases Anonymously** @@ -1572,8 +1571,8 @@ class Query(object): 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 + 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).\\ @@ -1600,23 +1599,23 @@ class Query(object): reset_joinpoint().\\ filter(Node.name == 'parent 1) - For an example of ``aliased=True``, see the distribution + 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 + :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 + :param aliased=False: If True, indicate that the JOIN target should be anonymously aliased. Subsequent calls to :class:`~.Query.filter` - and similar will adapt the incoming criterion to the target + and similar will adapt the incoming criterion to the target alias, until :meth:`~.Query.reset_joinpoint` is called. :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 + joined target, rather than starting back from the original FROM clauses of the query. See also: @@ -1627,7 +1626,7 @@ class Query(object): is used for inheritance relationships. :func:`.orm.join` - a standalone ORM-level join function, - used internally by :meth:`.Query.join`, which in previous + used internally by :meth:`.Query.join`, which in previous SQLAlchemy versions was the primary ORM-level joining interface. """ @@ -1636,8 +1635,8 @@ class Query(object): if kwargs: raise TypeError("unknown arguments: %s" % ','.join(kwargs.iterkeys())) - return self._join(props, - outerjoin=False, create_aliases=aliased, + return self._join(props, + outerjoin=False, create_aliases=aliased, from_joinpoint=from_joinpoint) def outerjoin(self, *props, **kwargs): @@ -1652,8 +1651,8 @@ class Query(object): if kwargs: raise TypeError("unknown arguments: %s" % ','.join(kwargs.iterkeys())) - return self._join(props, - outerjoin=True, create_aliases=aliased, + return self._join(props, + outerjoin=True, create_aliases=aliased, from_joinpoint=from_joinpoint) def _update_joinpoint(self, jp): @@ -1679,9 +1678,9 @@ class Query(object): self._reset_joinpoint() if len(keys) == 2 and \ - isinstance(keys[0], (expression.FromClause, + isinstance(keys[0], (expression.FromClause, type, AliasedClass)) and \ - isinstance(keys[1], (basestring, expression.ClauseElement, + isinstance(keys[1], (basestring, expression.ClauseElement, interfaces.PropComparator)): # detect 2-arg form of join and # convert to a tuple. @@ -1691,7 +1690,7 @@ class Query(object): if isinstance(arg1, tuple): # "tuple" form of join, multiple # tuples are accepted as well. The simpler - # "2-arg" form is preferred. May deprecate + # "2-arg" form is preferred. May deprecate # the "tuple" usage. arg1, arg2 = arg1 else: @@ -1765,11 +1764,11 @@ class Query(object): raise NotImplementedError("query.join(a==b) not supported.") self._join_left_to_right( - left_entity, - right_entity, onclause, + left_entity, + right_entity, onclause, outerjoin, create_aliases, prop) - def _join_left_to_right(self, left, right, + def _join_left_to_right(self, left, right, onclause, outerjoin, create_aliases, prop): """append a JOIN to the query's from clause.""" @@ -1785,12 +1784,12 @@ class Query(object): not create_aliases: raise sa_exc.InvalidRequestError( "Can't construct a join from %s to %s, they " - "are the same entity" % + "are the same entity" % (left, right)) right, right_is_aliased, onclause = self._prepare_right_side( right, onclause, - outerjoin, create_aliases, + outerjoin, create_aliases, prop) # if joining on a MapperProperty path, @@ -1805,11 +1804,11 @@ class Query(object): '_joinpoint_entity':right } - self._join_to_left(left, right, - right_is_aliased, + self._join_to_left(left, right, + right_is_aliased, onclause, outerjoin) - def _prepare_right_side(self, right, onclause, outerjoin, + def _prepare_right_side(self, right, onclause, outerjoin, create_aliases, prop): right_mapper, right_selectable, right_is_aliased = _entity_info(right) @@ -1860,11 +1859,11 @@ class Query(object): # until reset_joinpoint() is called. if need_adapter: self._filter_aliases = ORMAdapter(right, - equivalents=right_mapper and + equivalents=right_mapper and right_mapper._equivalent_columns or {}, chain_to=self._filter_aliases) - # if the onclause is a ClauseElement, adapt it with any + # if the onclause is a ClauseElement, adapt it with any # adapters that are in place right now if isinstance(onclause, expression.ClauseElement): onclause = self._adapt_clause(onclause, True, True) @@ -1877,7 +1876,7 @@ class Query(object): self._mapper_loads_polymorphically_with( right_mapper, ORMAdapter( - right, + right, equivalents=right_mapper._equivalent_columns ) ) @@ -1887,19 +1886,19 @@ class Query(object): def _join_to_left(self, left, right, right_is_aliased, onclause, outerjoin): left_mapper, left_selectable, left_is_aliased = _entity_info(left) - # this is an overly broad assumption here, but there's a + # this is an overly broad assumption here, but there's a # very wide variety of situations where we rely upon orm.join's # adaption to glue clauses together, with joined-table inheritance's # wide array of variables taking up most of the space. # Setting the flag here is still a guess, so it is a bug - # that we don't have definitive criterion to determine when - # adaption should be enabled (or perhaps that we're even doing the + # that we don't have definitive criterion to determine when + # adaption should be enabled (or perhaps that we're even doing the # whole thing the way we are here). join_to_left = not right_is_aliased and not left_is_aliased if self._from_obj and left_selectable is not None: replace_clause_index, clause = sql_util.find_join_source( - self._from_obj, + self._from_obj, left_selectable) if clause is not None: # the entire query's FROM clause is an alias of itself (i.e. @@ -1915,9 +1914,9 @@ class Query(object): join_to_left = False try: - clause = orm_join(clause, - right, - onclause, isouter=outerjoin, + clause = orm_join(clause, + right, + onclause, isouter=outerjoin, join_to_left=join_to_left) except sa_exc.ArgumentError, ae: raise sa_exc.InvalidRequestError( @@ -1947,7 +1946,7 @@ class Query(object): "Could not find a FROM clause to join from") try: - clause = orm_join(clause, right, onclause, + clause = orm_join(clause, right, onclause, isouter=outerjoin, join_to_left=join_to_left) except sa_exc.ArgumentError, ae: raise sa_exc.InvalidRequestError( @@ -1966,7 +1965,7 @@ class Query(object): 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 + method. See the example in :meth:`~.Query.join` for how this is used. """ @@ -1977,7 +1976,7 @@ class Query(object): """Set the FROM clause of this :class:`.Query` explicitly. Sending a mapped class or entity here effectively replaces the - "left edge" of any calls to :meth:`~.Query.join`, when no + "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. @@ -1985,7 +1984,7 @@ class Query(object): Mapped entities or plain :class:`~.Table` or other selectables can be sent here which will form the default FROM clause. - See the example in :meth:`~.Query.join` for a typical + See the example in :meth:`~.Query.join` for a typical usage of :meth:`~.Query.select_from`. """ @@ -2072,21 +2071,21 @@ class Query(object): construct. """ - if not criterion: - self._distinct = True - else: + if not criterion: + self._distinct = True + else: criterion = self._adapt_col_list(criterion) if isinstance(self._distinct, list): self._distinct += criterion - else: - self._distinct = criterion + else: + self._distinct = criterion @_generative() def prefix_with(self, *prefixes): """Apply the prefixes to the query and return the newly resulting ``Query``. - :param \*prefixes: optional prefixes, typically strings, + :param \*prefixes: optional prefixes, typically strings, not using any commas. In particular is useful for MySQL keywords. e.g.:: @@ -2097,7 +2096,7 @@ class Query(object): Would render:: - SELECT HIGH_PRIORITY SQL_SMALL_RESULT ALL users.name AS users_name + SELECT HIGH_PRIORITY SQL_SMALL_RESULT ALL users.name AS users_name FROM users .. versionadded:: 0.7.7 @@ -2131,7 +2130,7 @@ class Query(object): if isinstance(statement, basestring): statement = sql.text(statement) - if not isinstance(statement, + if not isinstance(statement, (expression._TextClause, expression._SelectBase)): raise sa_exc.ArgumentError( @@ -2141,12 +2140,12 @@ class Query(object): self._statement = statement def first(self): - """Return the first result of this ``Query`` or + """Return the first result of this ``Query`` or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that - only one primary entity row is generated on the server side - (note this may consist of multiple result rows if join-loaded + 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 ``first()`` results in an execution of the underlying query. @@ -2164,22 +2163,22 @@ class Query(object): def one(self): """Return exactly one result or raise an exception. - Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects - no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound`` + 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 does not return object identities. Note that an entity query, that is, one which selects one or more mapped classes as opposed to individual column attributes, - may ultimately represent many rows but only one row of + may ultimately represent many rows but only one row of unique entity or entities - this is a successful result for one(). Calling ``one()`` results in an execution of the underlying query. .. versionchanged:: 0.6 - ``one()`` fully fetches all results instead of applying - any kind of limit, so that the "unique"-ing of entities does not + ``one()`` fully fetches all results instead of applying + any kind of limit, so that the "unique"-ing of entities does not conceal multiple object identities. """ @@ -2246,7 +2245,7 @@ class Query(object): @property def column_descriptions(self): - """Return metadata about the columns which would be + """Return metadata about the columns which would be returned by this :class:`.Query`. Format is a list of dictionaries:: @@ -2362,11 +2361,11 @@ class Query(object): .. versionchanged:: 0.7 The above scheme is newly refined as of 0.7b3. - For fine grained control over specific columns + 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` + use :attr:`~sqlalchemy.sql.expression.func` expressions in conjunction with :meth:`~.Session.query`, i.e.:: @@ -2413,7 +2412,7 @@ class Query(object): ``'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. In that case you probably + implemented, an error is raised. In that case you probably want to use the 'fetch' strategy as a fallback. The expression evaluator currently doesn't account for differing @@ -2428,7 +2427,7 @@ class Query(object): state of dependent objects subject to delete or delete-orphan cascade to be correctly represented. - Note that the :meth:`.MapperEvents.before_delete` and + Note that the :meth:`.MapperEvents.before_delete` and :meth:`.MapperEvents.after_delete` events are **not** invoked from this method. It instead invokes :meth:`.SessionEvents.after_bulk_delete`. @@ -2480,7 +2479,7 @@ class Query(object): or call expire_all()) in order for the state of dependent objects subject foreign key cascade to be correctly represented. - Note that the :meth:`.MapperEvents.before_update` and + Note that the :meth:`.MapperEvents.before_update` and :meth:`.MapperEvents.after_update` events are **not** invoked from this method. It instead invokes :meth:`.SessionEvents.after_bulk_update`. @@ -2489,7 +2488,7 @@ class Query(object): #TODO: value keys need to be mapped to corresponding sql cols and # instr.attr.s to string keys - #TODO: updates of manytoone relationships need to be converted to + #TODO: updates of manytoone relationships need to be converted to # fk assignments #TODO: cascades need handling. @@ -2529,11 +2528,11 @@ class Query(object): strategy(*rec[1:]) if context.from_clause: - # "load from explicit FROMs" mode, + # "load from explicit FROMs" mode, # i.e. when select_from() or join() is used context.froms = list(context.from_clause) else: - # "load from discrete FROMs" mode, + # "load from discrete FROMs" mode, # i.e. when each _MappedEntity has its own FROM context.froms = context.froms @@ -2558,7 +2557,7 @@ class Query(object): return context def _compound_eager_statement(self, context): - # for eager joins present and LIMIT/OFFSET/DISTINCT, + # for eager joins present and LIMIT/OFFSET/DISTINCT, # wrap the query inside a select, # then append eager joins onto that @@ -2578,7 +2577,7 @@ class Query(object): context.whereclause, from_obj=context.froms, use_labels=context.labels, - # TODO: this order_by is only needed if + # TODO: this order_by is only needed if # LIMIT/OFFSET is present in self._select_args, # else the application on the outside is enough order_by=context.order_by, @@ -2598,17 +2597,17 @@ class Query(object): context.adapter = sql_util.ColumnAdapter(inner, equivs) statement = sql.select( - [inner] + context.secondary_columns, - for_update=context.for_update, + [inner] + context.secondary_columns, + for_update=context.for_update, use_labels=context.labels) from_clause = inner for eager_join in context.eager_joins.values(): # EagerLoader places a 'stop_on' attribute on the join, - # giving us a marker as to where the "splice point" of + # giving us a marker as to where the "splice point" of # the join should be from_clause = sql_util.splice_joins( - from_clause, + from_clause, eager_join, eager_join.stop_on) statement.append_from(from_clause) @@ -2630,7 +2629,7 @@ class Query(object): if self._distinct and context.order_by: order_by_col_expr = list( chain(*[ - sql_util.unwrap_order_by(o) + sql_util.unwrap_order_by(o) for o in context.order_by ]) ) @@ -2662,12 +2661,12 @@ class Query(object): def _adjust_for_single_inheritance(self, context): """Apply single-table-inheritance filtering. - + For all distinct single-table-inheritance mappers represented in the columns clause of this query, add criterion to the WHERE clause of the given QueryContext such that only the appropriate subtypes are selected from the total results. - + """ for (ext_info, adapter) in self._mapper_adapter_map.values(): if ext_info.entity in self._join_entities: @@ -2677,7 +2676,7 @@ class Query(object): if adapter: single_crit = adapter.traverse(single_crit) single_crit = self._adapt_clause(single_crit, False, False) - context.whereclause = sql.and_(context.whereclause, + context.whereclause = sql.and_(context.whereclause, single_crit) def __str__(self): @@ -2728,7 +2727,7 @@ class _MapperEntity(_QueryEntity): self._label_name = self.mapper.class_.__name__ self.path = self.entity_zero._sa_path_registry - def set_with_polymorphic(self, query, cls_or_mappers, + def set_with_polymorphic(self, query, cls_or_mappers, selectable, polymorphic_on): if self.is_aliased_class: raise NotImplementedError( @@ -2746,8 +2745,8 @@ class _MapperEntity(_QueryEntity): self._polymorphic_discriminator = polymorphic_on self.selectable = from_obj - query._mapper_loads_polymorphically_with(self.mapper, - sql_util.ColumnAdapter(from_obj, + query._mapper_loads_polymorphically_with(self.mapper, + sql_util.ColumnAdapter(from_obj, self.mapper._equivalent_columns)) filter_fn = id @@ -2800,7 +2799,7 @@ class _MapperEntity(_QueryEntity): elif not adapter: adapter = context.adapter - # polymorphic mappers which have concrete tables in + # polymorphic mappers which have concrete tables in # their hierarchy usually # require row aliasing unconditionally. if not adapter and self.mapper._requires_row_aliasing: @@ -2811,7 +2810,7 @@ class _MapperEntity(_QueryEntity): if self.primary_entity: _instance = loading.instance_processor( self.mapper, - context, + context, self.path, adapter, only_load_props=query._only_load_props, @@ -2822,7 +2821,7 @@ class _MapperEntity(_QueryEntity): else: _instance = loading.instance_processor( self.mapper, - context, + context, self.path, adapter, polymorphic_discriminator= @@ -2967,12 +2966,12 @@ class _ColumnEntity(_QueryEntity): def adapt_to_selectable(self, query, sel): c = _ColumnEntity(query, sel.corresponding_column(self.column)) - c._label_name = self._label_name + c._label_name = self._label_name c.entity_zero = self.entity_zero c.entities = self.entities def setup_entity(self, ext_info, aliased_adapter): - if 'selectable' not in self.__dict__: + if 'selectable' not in self.__dict__: self.selectable = ext_info.selectable self.froms.add(ext_info.selectable) |