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 | |
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.
-rw-r--r-- | lib/arel/engines/sql/relations/compiler.rb | 23 | ||||
-rw-r--r-- | spec/engines/sql/unit/relations/take_spec.rb | 18 |
2 files changed, 35 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 diff --git a/spec/engines/sql/unit/relations/take_spec.rb b/spec/engines/sql/unit/relations/take_spec.rb index cc3c3dbbf5..1e0d3e3cfe 100644 --- a/spec/engines/sql/unit/relations/take_spec.rb +++ b/spec/engines/sql/unit/relations/take_spec.rb @@ -52,6 +52,24 @@ module Arel }) end end + + it "manufactures count sql with limit" do + sql = Take.new(@relation.project(@relation[:id].count), @taken).to_sql + + adapter_is :mysql do + sql.should be_like(%Q{ + SELECT COUNT(`users`.`id`) AS count_id + FROM (SELECT 1 FROM `users` LIMIT 4) + }) + end + + adapter_is_not :mysql, :oracle do + sql.should be_like(%Q{ + SELECT COUNT("users"."id") AS count_id + FROM (SELECT 1 FROM "users" LIMIT 4) + }) + end + end end end end |