diff options
author | Emilio Tagua <miloops@gmail.com> | 2010-06-23 11:54:48 -0300 |
---|---|---|
committer | Emilio Tagua <miloops@gmail.com> | 2010-06-23 11:54:48 -0300 |
commit | 71e92992e66f461acaabc3ac2f3ec6480167962e (patch) | |
tree | 6b5c1c8c96f17529d31a98244aa185a279dd57ca /lib/arel/engines | |
parent | f68115023ecc02d21d982661ba806acec095842d (diff) | |
download | rails-71e92992e66f461acaabc3ac2f3ec6480167962e.tar.gz rails-71e92992e66f461acaabc3ac2f3ec6480167962e.tar.bz2 rails-71e92992e66f461acaabc3ac2f3ec6480167962e.zip |
Add support for counting rows with conditions or limit using a subquery.
Diffstat (limited to 'lib/arel/engines')
-rw-r--r-- | lib/arel/engines/sql/relations/compiler.rb | 23 |
1 files changed, 17 insertions, 6 deletions
diff --git a/lib/arel/engines/sql/relations/compiler.rb b/lib/arel/engines/sql/relations/compiler.rb index 374967b7be..2c2adc42fb 100644 --- a/lib/arel/engines/sql/relations/compiler.rb +++ b/lib/arel/engines/sql/relations/compiler.rb @@ -8,17 +8,28 @@ module Arel end def select_sql - query = build_query \ - "SELECT #{select_clauses.join(', ')}", - "FROM #{from_clauses}", + if relation.projections.first.is_a?(Count) && relation.projections.size == 1 && (taken.present? || wheres.present?) + subquery = build_query("SELECT 1 FROM #{from_clauses}", build_clauses) + query = "SELECT #{select_clauses.join(', ')} FROM (#{subquery})" + else + query = build_query \ + "SELECT #{select_clauses.join(', ')}", + "FROM #{from_clauses}", + build_clauses + end + query + end + + def build_clauses + clauses = build_query "", (joins(self) unless joins(self).blank? ), ("WHERE #{where_clauses.join(' AND ')}" unless wheres.blank? ), ("GROUP BY #{group_clauses.join(', ')}" unless groupings.blank? ), ("HAVING #{having_clauses.join(' AND ')}" unless havings.blank? ), ("ORDER BY #{order_clauses.join(', ')}" unless orders.blank? ) - engine.add_limit_offset!(query,{ :limit => taken, :offset => skipped }) if taken || skipped - query << " #{locked}" unless locked.blank? - query + clauses << " #{locked}" unless locked.blank? + engine.add_limit_offset!(clauses,{ :limit => taken, :offset => skipped }) if taken || skipped + clauses unless clauses.blank? end def delete_sql |