From 71e92992e66f461acaabc3ac2f3ec6480167962e Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 23 Jun 2010 11:54:48 -0300 Subject: Add support for counting rows with conditions or limit using a subquery. --- lib/arel/engines/sql/relations/compiler.rb | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'lib/arel/engines') 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 -- cgit v1.2.3