From 7252ccd7c988d2fe2f218401a0a81738e19fa239 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Sun, 27 Aug 2006 21:22:28 +0000 Subject: - fix to using query.count() with distinct, **kwargs with SelectResults count() [ticket:287] --- lib/sqlalchemy/ext/selectresults.py | 2 +- lib/sqlalchemy/orm/query.py | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) (limited to 'lib/sqlalchemy') diff --git a/lib/sqlalchemy/ext/selectresults.py b/lib/sqlalchemy/ext/selectresults.py index 79d56ec67..a35cdfa7e 100644 --- a/lib/sqlalchemy/ext/selectresults.py +++ b/lib/sqlalchemy/ext/selectresults.py @@ -28,7 +28,7 @@ class SelectResults(object): def count(self): """executes the SQL count() function against the SelectResults criterion.""" - return self._query.count(self._clause) + return self._query.count(self._clause, **self._ops) def _col_aggregate(self, col, func): """executes func() function against the given column diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index 1e9d40c75..29cc56761 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -232,7 +232,10 @@ class Query(object): return self._select_statement(statement, params=params) def count(self, whereclause=None, params=None, **kwargs): - s = self.table.count(whereclause) + if self._nestable(**kwargs): + s = self.table.select(whereclause, **kwargs).alias('getcount').count() + else: + s = self.table.count(whereclause) return self.session.scalar(self.mapper, s, params=params) def select_statement(self, statement, **params): @@ -302,14 +305,18 @@ class Query(object): return self.instances(statement, params=params, **kwargs) def _should_nest(self, **kwargs): - """returns True if the given statement options indicate that we should "nest" the + """return True if the given statement options indicate that we should "nest" the generated query as a subquery inside of a larger eager-loading query. this is used with keywords like distinct, limit and offset and the mapper defines eager loads.""" return ( self.mapper.has_eager() - and (kwargs.has_key('limit') or kwargs.has_key('offset') or kwargs.get('distinct', False)) + and self._nestable(**kwargs) ) + def _nestable(self, **kwargs): + """return true if the given statement options imply it should be nested.""" + return (kwargs.has_key('limit') or kwargs.has_key('offset') or kwargs.get('distinct', False)) + def compile(self, whereclause = None, **kwargs): order_by = kwargs.pop('order_by', False) from_obj = kwargs.pop('from_obj', []) -- cgit v1.2.1