]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
SelectResults will use a subselect, when calling an aggregate (i.e.
authorMike Bayer <mike_mp@zzzcomputing.com>
Fri, 11 Aug 2006 21:43:55 +0000 (21:43 +0000)
committerMike Bayer <mike_mp@zzzcomputing.com>
Fri, 11 Aug 2006 21:43:55 +0000 (21:43 +0000)
max, min, etc.) on a SelectResults that has an ORDER BY clause
[ticket:252]

CHANGES
lib/sqlalchemy/ext/selectresults.py

diff --git a/CHANGES b/CHANGES
index 3628b70c23824efd5985d0156e5cae62ba041e1c..450af4d58570500949ede05ed77c180d3417b3a0 100644 (file)
--- a/CHANGES
+++ b/CHANGES
@@ -34,6 +34,9 @@ return an array instead of string for SHOW CREATE TABLE call
 - inheritance check uses issubclass() instead of direct __mro__ check
 to make sure class A inherits from B, allowing mapper inheritance to more 
 flexibly correspond to class inheritance [ticket:271]
+- SelectResults will use a subselect, when calling an aggregate (i.e.
+max, min, etc.) on a SelectResults that has an ORDER BY clause
+[ticket:252]
 
 0.2.6
 - big overhaul to schema to allow truly composite primary and foreign
index 2ad52c8f0a91b35162710322187b2a3036d51e33..79d56ec675b05412512354fba7eee7ec1ea5d0ad 100644 (file)
@@ -29,22 +29,34 @@ class SelectResults(object):
     def count(self):
         """executes the SQL count() function against the SelectResults criterion."""
         return self._query.count(self._clause)
-    
+
+    def _col_aggregate(self, col, func):
+        """executes func() function against the given column
+
+        For performance, only use subselect if order_by attribute is set.
+        
+        """
+        if self._ops.get('order_by'):
+            s1 = sql.select([col], self._clause, **self._ops).alias('u')
+            return sql.select([func(s1.corresponding_column(col))]).scalar()
+        else:
+            return sql.select([func(col)], self._clause, **self._ops).scalar()
+
     def min(self, col):
         """executes the SQL min() function against the given column"""
-        return sql.select([sql.func.min(col)], self._clause, **self._ops).scalar()
+        return self._col_aggregate(col, sql.func.min)
 
     def max(self, col):
         """executes the SQL max() function against the given column"""
-        return sql.select([sql.func.max(col)], self._clause, **self._ops).scalar()
+        return self._col_aggregate(col, sql.func.max)
 
     def sum(self, col):
         """executes the SQL sum() function against the given column"""
-        return sql.select([sql.func.sum(col)], self._clause, **self._ops).scalar()
+        return self._col_aggregate(col, sql.func.sum)
 
     def avg(self, col):
         """executes the SQL avg() function against the given column"""
-        return sql.select([sql.func.avg(col)], self._clause, **self._ops).scalar()
+        return self._col_aggregate(col, sql.func.avg)
 
     def clone(self):
         """creates a copy of this SelectResults."""