From 7aabaac0f5ba108f917af2c65a79511694393b85 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Wed, 30 Dec 2009 13:28:26 +0530 Subject: [PATCH] Organize Relation methods into separate modules --- activerecord/lib/active_record.rb | 9 +- activerecord/lib/active_record/relation.rb | 240 +----------------- .../calculation_methods.rb} | 2 +- .../active_record/relation/finder_methods.rb | 120 +++++++++ .../active_record/relation/query_methods.rb | 132 ++++++++++ 5 files changed, 262 insertions(+), 241 deletions(-) rename activerecord/lib/active_record/{relational_calculations.rb => relation/calculation_methods.rb} (99%) create mode 100644 activerecord/lib/active_record/relation/finder_methods.rb create mode 100644 activerecord/lib/active_record/relation/query_methods.rb diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 7031c67539..87de480263 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -47,8 +47,15 @@ module ActiveRecord autoload :AttributeMethods autoload :Attributes autoload :AutosaveAssociation + autoload :Relation - autoload :RelationalCalculations + + autoload_under 'relation' do + autoload :QueryMethods + autoload :FinderMethods + autoload :CalculationMethods + end + autoload :Base autoload :Batches autoload :Calculations diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 52d66dc20a..ae03e1d7e9 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -1,6 +1,6 @@ module ActiveRecord class Relation - include RelationalCalculations + include QueryMethods, FinderMethods, CalculationMethods delegate :to_sql, :to => :relation delegate :length, :collect, :map, :each, :all?, :to => :to_a @@ -32,119 +32,6 @@ module ActiveRecord alias :& :merge - def preload(*associations) - spawn.tap {|r| r.preload_associations += Array.wrap(associations) } - end - - def eager_load(*associations) - spawn.tap {|r| r.eager_load_associations += Array.wrap(associations) } - end - - def readonly(status = true) - spawn.tap {|r| r.readonly = status } - end - - def select(selects) - if selects.present? - relation = spawn(@relation.project(selects)) - relation.readonly = @relation.joins(relation).present? ? false : @readonly - relation - else - spawn - end - end - - def from(from) - from.present? ? spawn(@relation.from(from)) : spawn - end - - def having(*args) - return spawn if args.blank? - - if [String, Hash, Array].include?(args.first.class) - havings = @klass.send(:merge_conditions, args.size > 1 ? Array.wrap(args) : args.first) - else - havings = args.first - end - - spawn(@relation.having(havings)) - end - - def group(groups) - groups.present? ? spawn(@relation.group(groups)) : spawn - end - - def order(orders) - orders.present? ? spawn(@relation.order(orders)) : spawn - end - - def lock(locks = true) - case locks - when String - spawn(@relation.lock(locks)) - when TrueClass, NilClass - spawn(@relation.lock) - else - spawn - end - end - - def reverse_order - relation = spawn - relation.instance_variable_set(:@orders, nil) - - order_clause = @relation.send(:order_clauses).join(', ') - if order_clause.present? - relation.order(reverse_sql_order(order_clause)) - else - relation.order("#{@klass.table_name}.#{@klass.primary_key} DESC") - end - end - - def limit(limits) - limits.present? ? spawn(@relation.take(limits)) : spawn - end - - def offset(offsets) - offsets.present? ? spawn(@relation.skip(offsets)) : spawn - end - - def on(join) - spawn(@relation.on(join)) - end - - def joins(join, join_type = nil) - return spawn if join.blank? - - join_relation = case join - when String - @relation.join(join) - when Hash, Array, Symbol - if @klass.send(:array_of_strings?, join) - @relation.join(join.join(' ')) - else - @relation.join(@klass.send(:build_association_joins, join)) - end - else - @relation.join(join, join_type) - end - - spawn(join_relation).tap { |r| r.readonly = true } - end - - def where(*args) - return spawn if args.blank? - - if [String, Hash, Array].include?(args.first.class) - conditions = @klass.send(:merge_conditions, args.size > 1 ? Array.wrap(args) : args.first) - conditions = Arel::SqlLiteral.new(conditions) if conditions - else - conditions = args.first - end - - spawn(@relation.where(conditions)) - end - def respond_to?(method, include_private = false) return true if @relation.respond_to?(method, include_private) || Array.method_defined?(method) @@ -189,47 +76,6 @@ module ActiveRecord alias all to_a - def find(*ids, &block) - return to_a.find(&block) if block_given? - - expects_array = ids.first.kind_of?(Array) - return ids.first if expects_array && ids.first.empty? - - ids = ids.flatten.compact.uniq - - case ids.size - when 0 - raise RecordNotFound, "Couldn't find #{@klass.name} without an ID" - when 1 - result = find_one(ids.first) - expects_array ? [ result ] : result - else - find_some(ids) - end - end - - def exists?(id = nil) - relation = select("#{@klass.quoted_table_name}.#{@klass.primary_key}").limit(1) - relation = relation.where(@klass.primary_key => id) if id - relation.first ? true : false - end - - def first - if loaded? - @records.first - else - @first ||= limit(1).to_a[0] - end - end - - def last - if loaded? - @records.last - else - @last ||= reverse_order.limit(1).to_a[0] - end - end - def size loaded? ? @records.length : count end @@ -307,93 +153,9 @@ module ActiveRecord end end - def find_by_attributes(match, attributes, *args) - conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h} - result = where(conditions).send(match.finder) - - if match.bang? && result.blank? - raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}" - else - result - end - end - - def find_or_instantiator_by_attributes(match, attributes, *args) - guard_protected_attributes = false - - if args[0].is_a?(Hash) - guard_protected_attributes = true - attributes_for_create = args[0].with_indifferent_access - conditions = attributes_for_create.slice(*attributes).symbolize_keys - else - attributes_for_create = conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h} - end - - record = where(conditions).first - - unless record - record = @klass.new { |r| r.send(:attributes=, attributes_for_create, guard_protected_attributes) } - yield(record) if block_given? - record.save if match.instantiator == :create - end - - record - end - - def find_one(id) - record = where(@klass.primary_key => id).first - - unless record - conditions = where_clause(', ') - conditions = " [WHERE #{conditions}]" if conditions.present? - raise RecordNotFound, "Couldn't find #{@klass.name} with ID=#{id}#{conditions}" - end - - record - end - - def find_some(ids) - result = where(@klass.primary_key => ids).all - - expected_size = - if @relation.taken && ids.size > @relation.taken - @relation.taken - else - ids.size - end - - # 11 ids with limit 3, offset 9 should give 2 results. - if @relation.skipped && (ids.size - @relation.skipped < expected_size) - expected_size = ids.size - @relation.skipped - end - - if result.size == expected_size - result - else - conditions = where_clause(', ') - conditions = " [WHERE #{conditions}]" if conditions.present? - - error = "Couldn't find all #{@klass.name.pluralize} with IDs " - error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})" - raise RecordNotFound, error - end - end - def where_clause(join_string = "\n\tAND ") @relation.send(:where_clauses).join(join_string) end - def reverse_sql_order(order_query) - order_query.to_s.split(/,/).each { |s| - if s.match(/\s(asc|ASC)$/) - s.gsub!(/\s(asc|ASC)$/, ' DESC') - elsif s.match(/\s(desc|DESC)$/) - s.gsub!(/\s(desc|DESC)$/, ' ASC') - else - s.concat(' DESC') - end - }.join(',') - end - end end diff --git a/activerecord/lib/active_record/relational_calculations.rb b/activerecord/lib/active_record/relation/calculation_methods.rb similarity index 99% rename from activerecord/lib/active_record/relational_calculations.rb rename to activerecord/lib/active_record/relation/calculation_methods.rb index f42ffe0460..a925a99464 100644 --- a/activerecord/lib/active_record/relational_calculations.rb +++ b/activerecord/lib/active_record/relation/calculation_methods.rb @@ -1,5 +1,5 @@ module ActiveRecord - module RelationalCalculations + module CalculationMethods def count(*args) calculate(:count, *construct_count_options_from_args(*args)) diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb new file mode 100644 index 0000000000..7a1d6fc538 --- /dev/null +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -0,0 +1,120 @@ +module ActiveRecord + module FinderMethods + + def find(*ids, &block) + return to_a.find(&block) if block_given? + + expects_array = ids.first.kind_of?(Array) + return ids.first if expects_array && ids.first.empty? + + ids = ids.flatten.compact.uniq + + case ids.size + when 0 + raise RecordNotFound, "Couldn't find #{@klass.name} without an ID" + when 1 + result = find_one(ids.first) + expects_array ? [ result ] : result + else + find_some(ids) + end + end + + def exists?(id = nil) + relation = select("#{@klass.quoted_table_name}.#{@klass.primary_key}").limit(1) + relation = relation.where(@klass.primary_key => id) if id + relation.first ? true : false + end + + def first + if loaded? + @records.first + else + @first ||= limit(1).to_a[0] + end + end + + def last + if loaded? + @records.last + else + @last ||= reverse_order.limit(1).to_a[0] + end + end + + protected + + def find_by_attributes(match, attributes, *args) + conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h} + result = where(conditions).send(match.finder) + + if match.bang? && result.blank? + raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}" + else + result + end + end + + def find_or_instantiator_by_attributes(match, attributes, *args) + guard_protected_attributes = false + + if args[0].is_a?(Hash) + guard_protected_attributes = true + attributes_for_create = args[0].with_indifferent_access + conditions = attributes_for_create.slice(*attributes).symbolize_keys + else + attributes_for_create = conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h} + end + + record = where(conditions).first + + unless record + record = @klass.new { |r| r.send(:attributes=, attributes_for_create, guard_protected_attributes) } + yield(record) if block_given? + record.save if match.instantiator == :create + end + + record + end + + def find_one(id) + record = where(@klass.primary_key => id).first + + unless record + conditions = where_clause(', ') + conditions = " [WHERE #{conditions}]" if conditions.present? + raise RecordNotFound, "Couldn't find #{@klass.name} with ID=#{id}#{conditions}" + end + + record + end + + def find_some(ids) + result = where(@klass.primary_key => ids).all + + expected_size = + if @relation.taken && ids.size > @relation.taken + @relation.taken + else + ids.size + end + + # 11 ids with limit 3, offset 9 should give 2 results. + if @relation.skipped && (ids.size - @relation.skipped < expected_size) + expected_size = ids.size - @relation.skipped + end + + if result.size == expected_size + result + else + conditions = where_clause(', ') + conditions = " [WHERE #{conditions}]" if conditions.present? + + error = "Couldn't find all #{@klass.name.pluralize} with IDs " + error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})" + raise RecordNotFound, error + end + end + + end +end diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb new file mode 100644 index 0000000000..631c80da25 --- /dev/null +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -0,0 +1,132 @@ +module ActiveRecord + module QueryMethods + + def preload(*associations) + spawn.tap {|r| r.preload_associations += Array.wrap(associations) } + end + + def eager_load(*associations) + spawn.tap {|r| r.eager_load_associations += Array.wrap(associations) } + end + + def readonly(status = true) + spawn.tap {|r| r.readonly = status } + end + + def select(selects) + if selects.present? + relation = spawn(@relation.project(selects)) + relation.readonly = @relation.joins(relation).present? ? false : @readonly + relation + else + spawn + end + end + + def from(from) + from.present? ? spawn(@relation.from(from)) : spawn + end + + def having(*args) + return spawn if args.blank? + + if [String, Hash, Array].include?(args.first.class) + havings = @klass.send(:merge_conditions, args.size > 1 ? Array.wrap(args) : args.first) + else + havings = args.first + end + + spawn(@relation.having(havings)) + end + + def group(groups) + groups.present? ? spawn(@relation.group(groups)) : spawn + end + + def order(orders) + orders.present? ? spawn(@relation.order(orders)) : spawn + end + + def lock(locks = true) + case locks + when String + spawn(@relation.lock(locks)) + when TrueClass, NilClass + spawn(@relation.lock) + else + spawn + end + end + + def reverse_order + relation = spawn + relation.instance_variable_set(:@orders, nil) + + order_clause = @relation.send(:order_clauses).join(', ') + if order_clause.present? + relation.order(reverse_sql_order(order_clause)) + else + relation.order("#{@klass.table_name}.#{@klass.primary_key} DESC") + end + end + + def limit(limits) + limits.present? ? spawn(@relation.take(limits)) : spawn + end + + def offset(offsets) + offsets.present? ? spawn(@relation.skip(offsets)) : spawn + end + + def on(join) + spawn(@relation.on(join)) + end + + def joins(join, join_type = nil) + return spawn if join.blank? + + join_relation = case join + when String + @relation.join(join) + when Hash, Array, Symbol + if @klass.send(:array_of_strings?, join) + @relation.join(join.join(' ')) + else + @relation.join(@klass.send(:build_association_joins, join)) + end + else + @relation.join(join, join_type) + end + + spawn(join_relation).tap { |r| r.readonly = true } + end + + def where(*args) + return spawn if args.blank? + + if [String, Hash, Array].include?(args.first.class) + conditions = @klass.send(:merge_conditions, args.size > 1 ? Array.wrap(args) : args.first) + conditions = Arel::SqlLiteral.new(conditions) if conditions + else + conditions = args.first + end + + spawn(@relation.where(conditions)) + end + + private + + def reverse_sql_order(order_query) + order_query.to_s.split(/,/).each { |s| + if s.match(/\s(asc|ASC)$/) + s.gsub!(/\s(asc|ASC)$/, ' DESC') + elsif s.match(/\s(desc|DESC)$/) + s.gsub!(/\s(desc|DESC)$/, ' ASC') + else + s.concat(' DESC') + end + }.join(',') + end + + end +end