Class: ActiveRecord::PredicateBuilder
Constant Summary
-
NO_MATCH =
# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 5Arel.sql("1=0", retryable: true).freeze
Class Method Summary
- .new(table) ⇒ PredicateBuilder constructor
-
.references(attributes)
Returns the tables referenced by normalized attributes, or nil for none.
Instance Attribute Summary
- #table=(value) rw protected
- #table rw private
Instance Method Summary
- #[](attr_name, value, operator = nil)
- #build(attribute, value, operator = nil)
- #build_bind_attribute(attribute, value)
- #build_from_hash(attributes, &block)
-
#convert_dot_notation_to_hash(attributes)
Normalizes "topics.title" => "Rails" into "topics" => { "title" => "Rails" }, returning attributes itself when there is nothing to normalize.
- #expand_from_hash(attributes, &block)
- #predicate_attribute(attribute, type = attribute.type_caster)
- #predicate_value(attribute, value)
-
#register_handler(klass, handler)
Define how a class is converted to
::Arelnodes when passed towhere. - #resolve_arel_attribute(table_name, column_name, &block)
- #with(table)
- #register_handlers protected
- #aggregate_attribute_value(object, attribute) private
- #grouping_queries(queries) private
- #handler_for(object) private
Constructor Details
.new(table) ⇒ PredicateBuilder
# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 15
def initialize(table) @table = table @handlers = [] register_handlers ActiveSupport::Ractors.make_shareable(self) end
Class Method Details
.references(attributes)
Returns the tables referenced by normalized attributes, or nil for none. Tuple keys are normalized only when expanded, so parse their dot notation here.
# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 56
def self.references(attributes) references = nil attributes.each do |key, value| if value.is_a?(Hash) (references ||= []) << Arel.sql(key, retryable: true) elsif key.is_a?(Array) key.each do |column| if (idx = column.rindex(".")) (references ||= []) << Arel.sql(column[0, idx], retryable: true) end end end end references end
Instance Attribute Details
#table (rw, private)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 232
attr_reader :table
#table=(value) (rw, protected)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 221
attr_writer :table
Instance Method Details
#[](attr_name, value, operator = nil)
[ GitHub ]#aggregate_attribute_value(object, attribute) (private)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 254
def aggregate_attribute_value(object, attribute) object.respond_to?(attribute) ? object.public_send(attribute) : object end
#build(attribute, value, operator = nil)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 100
def build(attribute, value, operator = nil) value = value.id if value.respond_to?(:id) type = attribute.type_caster attribute = predicate_attribute(attribute, type) if operator ||= type.force_equality?(value) && :eq attribute.public_send(operator, predicate_value(attribute, value)) else handler_for(value).call(attribute, value) end end
#build_bind_attribute(attribute, value)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 128
def build_bind_attribute(attribute, value) bind = Relation::QueryAttribute.new(attribute.name, value, attribute.type_caster) attribute.is_a?(ComparisonAttribute) ? ComparisonValue.new(bind) : bind end
#build_from_hash(attributes, &block)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 24
def build_from_hash(attributes, &block) (convert_dot_notation_to_hash(attributes), &block) end
#convert_dot_notation_to_hash(attributes)
Normalizes "topics.title" => "Rails" into "topics" => { "title" => "Rails" }, returning attributes itself when there is nothing to normalize.
# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 30
def convert_dot_notation_to_hash(attributes) return attributes unless attributes.any? { |key, value| value.is_a?(Hash) || (key.is_a?(String) && key.include?(".")) } attributes.each_with_object({}) do |(key, value), converted| if value.is_a?(Hash) if (existing = converted[key]) existing.merge!(value) else converted[key] = value.dup end elsif (idx = key.rindex(".")) table_name, column_name = key[0, idx], key[idx + 1, key.length] if (existing = converted[table_name]) existing[column_name] = value else converted[table_name] = { column_name => value } end else converted[key] = value end end end
#expand_from_hash(attributes, &block)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 143
def (attributes, &block) return [NO_MATCH] if attributes.empty? attributes.flat_map do |key, value| if key.is_a?(Array) && key.size == 1 key = key.first value = value.flatten end if key.is_a?(Array) queries = Array(value).map do |ids_set| ids_set = ids_set.id if ids_set.respond_to?(:id) raise ArgumentError, "Expected corresponding value for #{key} to be an Array" unless ids_set.is_a?(Array) build_from_hash(key.zip(ids_set).to_h, &block) end grouping_queries(queries) elsif value.is_a?(Hash) && !table.has_column?(key) table.associated_table(key, &block) .predicate_builder.(value.stringify_keys, &block) elsif (associated_reflection = table.associated_with(key)) # Find the foreign key when using queries such as: # Post.where(author: author) # # For polymorphic relationships, find the foreign key and type: # PriceEstimate.where(estimate_of: treasure) if associated_reflection.polymorphic? value = [value] unless value.is_a?(Array) query_value = PolymorphicArrayValue.new(associated_reflection, value, table.model) elsif associated_reflection.through_reflection? associated_table = table.associated_table(key) next associated_table.predicate_builder.( associated_table.primary_key => value ) end query_value ||= AssociationQueryValue.new(associated_reflection, value, table.model) queries = query_value.queries.map! do |query| # If the query produced is identical to attributes don't go any deeper. # Prevents stack level too deep errors when association and foreign_key are identical. query == attributes ? self[key, value] : (query) end grouping_queries(queries) elsif table.aggregated_with?(key) mapping = table.reflect_on_aggregation(key).mapping values = value.nil? ? [nil] : Array.wrap(value) if mapping.length == 1 || values.empty? column_name, aggr_attr = mapping.first values = values.map do |object| if object.is_a?(Range) range_begin = aggregate_attribute_value(object.begin, aggr_attr) range_end = aggregate_attribute_value(object.end, aggr_attr) Range.new(range_begin, range_end, object.exclude_end?) else aggregate_attribute_value(object, aggr_attr) end end self[column_name, values] else queries = values.map do |object| mapping.map do |field_attr, aggregate_attr| self[field_attr, object.try!(aggregate_attr)] end end grouping_queries(queries) end else self[key, value] end end end
#grouping_queries(queries) (private)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 234
def grouping_queries(queries) if queries.one? queries.first else queries.map! { |query| if query.one? query else Arel::Nodes::And.new(query) end } queries = Arel::Nodes::Or.new(queries) Arel::Nodes::Grouping.new(queries) end end
#handler_for(object) (private)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 250
def handler_for(object) @handlers.detect { |klass, _| klass === object }.last end
#predicate_attribute(attribute, type = attribute.type_caster)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 112
def predicate_attribute(attribute, type = attribute.type_caster) if !attribute.is_a?(ComparisonAttribute) && Type::QueryPredicates.type?(type) ComparisonAttribute.new(attribute, type) else attribute end end
#predicate_value(attribute, value)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 120
def predicate_value(attribute, value) if Arel.arel_node?(value) attribute.is_a?(ComparisonAttribute) ? attribute.comparison_expression(value) : value else build_bind_attribute(attribute, value) end end
#register_handler(klass, handler)
Define how a class is converted to ::Arel nodes when passed to where.
The handler can be any object that responds to call, and will be used
for any value that === the class given. For example:
MyCustomDateRange = {Struct.new}(:start, :end)
handler = proc do |column, range|
Arel::Nodes::Between.new(column,
Arel::Nodes::And.new([range.start, range.end])
)
end
{ActiveRecord::PredicateBuilder.new}("users").register_handler(MyCustomDateRange, handler)
The column exposes its effective type through type_caster. Call
fetch_attribute { |attribute| ... } to access the underlying
logical Arel attribute when a type supplies a comparison expression. The
handler is responsible for constructing its right-hand side.
# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 92
def register_handler(klass, handler) @handlers.unshift([klass, handler]) end
#register_handlers (protected)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 223
def register_handlers register_handler(BasicObject, BasicObjectHandler.new(self)) register_handler(Range, RangeHandler.new(self)) register_handler(Relation, RelationHandler.new) register_handler(Array, ArrayHandler.new(self)) register_handler(Set, ArrayHandler.new(self)) end
#resolve_arel_attribute(table_name, column_name, &block)
[ GitHub ]# File 'activerecord/lib/active_record/relation/predicate_builder.rb', line 133
def resolve_arel_attribute(table_name, column_name, &block) table.associated_table(table_name, &block).arel_table[column_name] end