Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 4264

Show
Ignore:
Timestamp:
04/25/06 05:25:04 (4 years ago)
Author:
rick
Message:

Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activerecord/CHANGELOG

    r4249 r4264  
    11*SVN* 
     2 
     3* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick] 
    24 
    35* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com] 
  • trunk/activerecord/lib/active_record/associations.rb

    r4232 r4264  
    967967        end 
    968968         
    969         def count_with_associations(options = {}) 
    970           catch :invalid_query do 
    971             join_dependency = JoinDependency.new(self, merge_includes(scope(:find, :include), options[:include]), options[:joins]) 
    972             return count_by_sql(construct_counter_sql_with_included_associations(options, join_dependency)) 
    973           end 
    974           0 
    975         end 
    976  
    977969        def find_with_associations(options = {}) 
    978970          catch :invalid_query do 
     
    11171109            "#{name} Load Including Associations" 
    11181110          ) 
    1119         end 
    1120          
    1121         def construct_counter_sql_with_included_associations(options, join_dependency) 
    1122           scope = scope(:find) 
    1123           sql = "SELECT COUNT(DISTINCT #{table_name}.#{primary_key})" 
    1124            
    1125           # A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT. 
    1126           if !Base.connection.supports_count_distinct? 
    1127             sql = "SELECT COUNT(*) FROM (SELECT DISTINCT #{table_name}.#{primary_key}" 
    1128           end 
    1129            
    1130           sql << " FROM #{table_name} " 
    1131           sql << join_dependency.join_associations.collect{|join| join.association_join }.join 
    1132            
    1133           add_joins!(sql, options, scope) 
    1134           add_conditions!(sql, options[:conditions], scope) 
    1135           add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit]) 
    1136  
    1137           add_limit!(sql, options, scope) if using_limitable_reflections?(join_dependency.reflections) 
    1138  
    1139           if !Base.connection.supports_count_distinct? 
    1140             sql << ")" 
    1141           end 
    1142  
    1143           return sanitize_sql(sql)           
    11441111        end 
    11451112 
  • trunk/activerecord/lib/active_record/calculations.rb

    r4237 r4264  
    11module ActiveRecord 
    22  module Calculations #:nodoc: 
    3     CALCULATIONS_OPTIONS = [:conditions, :joins, :order, :select, :group, :having, :distinct, :limit, :offset
     3    CALCULATIONS_OPTIONS = [:conditions, :joins, :order, :select, :group, :having, :distinct, :limit, :offset, :include
    44    def self.included(base) 
    55      base.extend(ClassMethods) 
     
    4343      # Note: Person.count(:all) will not work because it will use :all as the condition.  Use Person.count instead. 
    4444      def count(*args) 
    45         column_name, options = construct_count_options_from_legacy_args(*args) 
    46  
    47         if options[:include] || scope(:find, :include) 
    48           count_with_associations(options) 
    49         else 
    50           calculate(:count, column_name, options) 
    51         end 
     45        calculate(:count, *construct_count_options_from_legacy_args(*args)) 
    5246      end 
    5347 
     
    121115        column_name     = '*' if column_name == :all 
    122116        column          = column_for column_name 
    123         aggregate       = select_aggregate(operation, column_name, options) 
    124         aggregate_alias = column_alias_for(operation, column_name) 
    125         if options[:group] 
    126           execute_grouped_calculation(operation, column_name, column, aggregate, aggregate_alias, options) 
    127         else 
    128           execute_simple_calculation(operation, column_name, column, aggregate, aggregate_alias, options) 
    129         end 
     117        catch :invalid_query do 
     118          if options[:group] 
     119            return execute_grouped_calculation(operation, column_name, column, options) 
     120          else 
     121            return execute_simple_calculation(operation, column_name, column, options) 
     122          end 
     123        end 
     124        0 
    130125      end 
    131126 
     
    144139              # Handle legacy paramter options: def count(conditions=nil, joins=nil) 
    145140              options.merge!(:conditions => args[0]) if args.length > 0 
    146               options.merge!(:joins => args[1])      if args.length > 1 
     141              options.merge!(:joins      => args[1]) if args.length > 1 
    147142            end 
    148143          else 
     
    152147        end 
    153148       
    154         def construct_calculation_sql(aggregate, aggregate_alias, options) #:nodoc: 
    155           scope = scope(:find) 
    156           sql  = "SELECT #{aggregate} AS #{aggregate_alias}" 
     149        def construct_calculation_sql(operation, column_name, options) #:nodoc: 
     150          scope           = scope(:find) 
     151          merged_includes = merge_includes(scope ? scope[:include] : [], options[:include]) 
     152          aggregate_alias = column_alias_for(operation, column_name) 
     153          use_workaround  = !Base.connection.supports_count_distinct? && options[:distinct] && operation.to_s.downcase == 'count' 
     154          join_dependency = nil 
     155 
     156          if merged_includes.any? && operation.to_s.downcase == 'count' 
     157            options[:distinct] = true 
     158            column_name = [table_name, primary_key] * '.' 
     159          end 
     160 
     161          sql  = "SELECT #{operation}(#{'DISTINCT ' if options[:distinct]}#{column_name}) AS #{aggregate_alias}" 
     162 
     163          # A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT. 
     164          sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround 
     165           
    157166          sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group] 
     167          sql << " FROM (SELECT DISTINCT #{column_name}" if use_workaround 
    158168          sql << " FROM #{table_name} " 
     169          if merged_includes.any? 
     170            join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, options[:joins]) 
     171            sql << join_dependency.join_associations.collect{|join| join.association_join }.join 
     172          end 
    159173          add_joins!(sql, options, scope) 
    160174          add_conditions!(sql, options[:conditions], scope) 
    161175          sql << " GROUP BY #{options[:group_field]}" if options[:group] 
    162           sql << " HAVING #{options[:having]}" if options[:group] && options[:having] 
    163           sql << " ORDER BY #{options[:order]}" if options[:order] 
    164           add_limit!(sql, options) 
     176          sql << " HAVING #{options[:having]}"        if options[:group] && options[:having] 
     177          sql << " ORDER BY #{options[:order]}"       if options[:order] 
     178          add_limited_ids_condition!(sql, options, join_dependency) if join_dependency && !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit]) 
     179          add_limit!(sql, options, scope) 
     180          sql << ')' if use_workaround 
    165181          sql 
    166182        end 
    167183 
    168         def execute_simple_calculation(operation, column_name, column, aggregate, aggregate_alias, options) #:nodoc: 
    169           value     = connection.select_value(construct_calculation_sql(aggregate, aggregate_alias, options)) 
     184        def execute_simple_calculation(operation, column_name, column, options) #:nodoc: 
     185          value = connection.select_value(construct_calculation_sql(operation, column_name, options)) 
    170186          type_cast_calculated_value(value, column, operation) 
    171187        end 
    172188 
    173         def execute_grouped_calculation(operation, column_name, column, aggregate, aggregate_alias, options) #:nodoc: 
     189        def execute_grouped_calculation(operation, column_name, column, options) #:nodoc: 
    174190          group_attr      = options[:group].to_s 
    175191          association     = reflect_on_association(group_attr.to_sym) 
     
    178194          group_alias     = column_alias_for(group_field) 
    179195          group_column    = column_for group_field 
    180           sql             = construct_calculation_sql(aggregate, aggregate_alias, options.merge(:group_field => group_field, :group_alias => group_alias)) 
     196          sql             = construct_calculation_sql(operation, column_name, options.merge(:group_field => group_field, :group_alias => group_alias)) 
    181197          calculated_data = connection.select_all(sql) 
     198          aggregate_alias = column_alias_for(operation, column_name) 
    182199 
    183200          if association 
     
    196213      private 
    197214        def validate_calculation_options(operation, options = {}) 
    198           if operation.to_s == 'count' 
    199             options.assert_valid_keys(CALCULATIONS_OPTIONS + [:include]) 
    200           else 
    201             options.assert_valid_keys(CALCULATIONS_OPTIONS) 
    202           end 
    203         end 
    204  
    205         def select_aggregate(operation, column_name, options) 
    206           "#{operation}(#{'DISTINCT ' if options[:distinct]}#{column_name})" 
     215          options.assert_valid_keys(CALCULATIONS_OPTIONS) 
    207216        end 
    208217 
  • trunk/activerecord/test/calculations_test.rb

    r4185 r4264  
    2020  def test_should_get_maximum_of_field 
    2121    assert_equal 60, Account.maximum(:credit_limit) 
     22  end 
     23 
     24  def test_should_get_maximum_of_field_with_include 
     25    assert_equal 50, Account.maximum(:credit_limit, :include => :firm, :conditions => "companies.name != 'Summit'") 
     26  end 
     27 
     28  def test_should_get_maximum_of_field_with_scoped_include 
     29    Account.with_scope :find => { :include => :firm, :conditions => "companies.name != 'Summit'" } do 
     30      assert_equal 50, Account.maximum(:credit_limit) 
     31    end 
    2232  end 
    2333 
     
    175185    end 
    176186     
    177     assert_raises(ArgumentError) { Company.send(:validate_calculation_options, :sum,   :include => :posts) } 
    178187    assert_raises(ArgumentError) { Company.send(:validate_calculation_options, :sum,   :foo => :bar) } 
    179188    assert_raises(ArgumentError) { Company.send(:validate_calculation_options, :count, :foo => :bar) }