1 module CompositePrimaryKeys
4 def self.append_features(base)
6 base.send(:extend, ClassMethods)
10 def construct_calculation_sql(operation, column_name, options) #:nodoc:
11 operation = operation.to_s.downcase
12 options = options.symbolize_keys
15 merged_includes = merge_includes(scope ? scope[:include] : [], options[:include])
16 aggregate_alias = column_alias_for(operation, column_name)
17 use_workaround = !connection.supports_count_distinct? && options[:distinct] && operation.to_s.downcase == 'count'
20 if merged_includes.any? && operation.to_s.downcase == 'count'
21 options[:distinct] = true
22 use_workaround = !connection.supports_count_distinct?
23 column_name = options[:select] || primary_key.map{ |part| "#{quoted_table_name}.#{connection.quote_column_name(part)}"}.join(',')
26 sql = "SELECT #{operation}(#{'DISTINCT ' if options[:distinct]}#{column_name}) AS #{aggregate_alias}"
28 # A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
29 sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround
31 sql << ", #{connection.quote_column_name(options[:group_field])} AS #{options[:group_alias]}" if options[:group]
32 sql << " FROM (SELECT DISTINCT #{column_name}" if use_workaround
33 sql << " FROM #{quoted_table_name} "
34 if merged_includes.any?
35 join_dependency = ::ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, options[:joins])
36 sql << join_dependency.join_associations.collect{|join| join.association_join }.join
38 add_joins!(sql, options, scope)
39 add_conditions!(sql, options[:conditions], scope)
40 add_limited_ids_condition!(sql, options, join_dependency) if \
42 !using_limitable_reflections?(join_dependency.reflections) &&
43 ((scope && scope[:limit]) || options[:limit])
46 group_key = connection.adapter_name == 'FrontBase' ? :group_alias : :group_field
47 sql << " GROUP BY #{connection.quote_column_name(options[group_key])} "
50 if options[:group] && options[:having]
51 # FrontBase requires identifiers in the HAVING clause and chokes on function calls
52 if connection.adapter_name == 'FrontBase'
53 options[:having].downcase!
54 options[:having].gsub!(/#{operation}\s*\(\s*#{column_name}\s*\)/, aggregate_alias)
57 sql << " HAVING #{options[:having]} "
60 sql << " ORDER BY #{options[:order]} " if options[:order]
61 add_limit!(sql, options, scope)
62 sql << ') w1' if use_workaround # assign a dummy table name as required for postgresql