Module: Squeel::Adapters::ActiveRecord::RelationExtensions
- Defined in:
- lib/squeel/adapters/active_record/relation_extensions.rb,
lib/squeel/adapters/active_record/3.0/relation_extensions.rb,
lib/squeel/adapters/active_record/3.1/relation_extensions.rb
Constant Summary collapse
- JoinAssociation =
::ActiveRecord::Associations::JoinDependency::JoinAssociation
- JoinDependency =
::ActiveRecord::Associations::JoinDependency
Instance Attribute Summary collapse
-
#join_dependency ⇒ Object
Returns a JoinDependency for the current relation.
Class Method Summary collapse
-
.included(base) ⇒ Object
ZOMG ALIAS_METHOD_CHAIN IS BELOW.
Instance Method Summary collapse
- #attribute_visitor ⇒ Object
-
#attrs_to_orderings(order) ⇒ Object
reverse_sql_order will reverse the order of strings or Orderings, but not attributes.
- #build_arel ⇒ Object
- #build_join_dependency(manager, joins) ⇒ Object
- #build_where(opts, other = []) ⇒ Object
- #collapse_wheres(arel, wheres) ⇒ Object
-
#debug_sql ⇒ Object
Simulate the logic that occurs in #to_a.
- #eager_load(*args) ⇒ Object
- #find_equality_predicates(nodes) ⇒ Object
- #flatten_nodes(nodes) ⇒ Object
- #group(*args) ⇒ Object
- #having(*args) ⇒ Object
- #includes(*args) ⇒ Object
- #joins(*args) ⇒ Object
-
#merge(r, skip_visit = false) ⇒ Object
We need to be able to support merging two relations without having to get our hooks too deeply into ActiveRecord.
- #order(*args) ⇒ Object
- #overwrite_squeel_equalities(wheres) ⇒ Object
- #predicate_visitor ⇒ Object
- #preload(*args) ⇒ Object
- #reorder(*args) ⇒ Object
- #select(value = Proc.new) ⇒ Object
-
#select_for_count ⇒ Object
So, building a select for a count query in ActiveRecord is pretty heavily dependent on select_values containing strings.
- #visit! ⇒ Object
- #visited ⇒ Object
- #where(opts = Proc.new, *rest) ⇒ Object
-
#where_values_hash_with_squeel ⇒ Object
where_values_hash is used in scope_for_create.
-
#with_default_scope_with_squeel ⇒ Object
with_default_scope was added to ActiveRecord ~> 3.1 in order to address github.com/rails/rails/issues/1233.
Instance Attribute Details
#join_dependency ⇒ Object
Returns a JoinDependency for the current relation.
We don’t need to clear out @join_dependency by overriding #reset, because the default #reset already does this, despite never setting it anywhere that I can find. Serendipity, I say!
19 20 21 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 19 def join_dependency @join_dependency ||= (build_join_dependency(table, @joins_values) && @join_dependency) end |
Class Method Details
.included(base) ⇒ Object
ZOMG ALIAS_METHOD_CHAIN IS BELOW. HIDE YOUR EYES! … … … Since you’re still looking, let me explain this horrible transgression you see before you.
You see, Relation#where_values_hash and with_default_scope are defined on the ActiveRecord::Relation class, itself. ActiveRecord::Relation class. Since they’re defined there, but I would very much like to modify their behavior, I have three choices.
-
Inherit from ActiveRecord::Relation in a Squeel::Relation class, and make an attempt to usurp all of the various calls to methods on ActiveRecord::Relation by doing some really evil stuff with constant reassignment, all for the sake of being able to use super().
-
Submit a patch to Rails core, breaking these methods off into another module, all for my own selfish desire to use super() while mucking about in Rails internals.
-
Use alias_method_chain, and say 10 hail Hanssons as penance.
I opted to go with #3. Except for the hail Hansson thing. Unless you’re DHH, in which case, I totally said them.
If you’d like to read more about alias_method_chain, see erniemiller.org/2011/02/03/when-to-use-alias_method_chain/
339 340 341 342 343 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 339 def self.included(base) base.class_eval do alias_method_chain :where_values_hash, :squeel end end |
Instance Method Details
#attribute_visitor ⇒ Object
29 30 31 32 33 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 29 def attribute_visitor Visitors::AttributeVisitor.new( Context.new(join_dependency) ) end |
#attrs_to_orderings(order) ⇒ Object
reverse_sql_order will reverse the order of strings or Orderings, but not attributes
100 101 102 103 104 |
# File 'lib/squeel/adapters/active_record/3.1/relation_extensions.rb', line 100 def attrs_to_orderings(order) order.map do |o| Arel::Attribute === o ? o.asc : o end end |
#build_arel ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 8 def build_arel arel = table.from table build_join_dependency(arel, @joins_values) unless @joins_values.empty? predicate_viz = predicate_visitor attribute_viz = attribute_visitor collapse_wheres(arel, predicate_viz.accept((@where_values - ['']).uniq)) arel.having(*predicate_viz.accept(@having_values.uniq.reject{|h| h.blank?})) unless @having_values.empty? arel.take(connection.sanitize_limit(@limit_value)) if @limit_value arel.skip(@offset_value) if @offset_value arel.group(*attribute_viz.accept(@group_values.uniq.reject{|g| g.blank?})) unless @group_values.empty? order = attribute_viz.accept(@order_values) order = reverse_sql_order(attrs_to_orderings(order)) if @reverse_order_value arel.order(*order.uniq.reject{|o| o.blank?}) unless order.empty? build_select(arel, attribute_viz.accept(@select_values.uniq)) arel.distinct(@uniq_value) arel.from(@from_value) if @from_value arel.lock(@lock_value) if @lock_value arel end |
#build_join_dependency(manager, joins) ⇒ Object
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 124 def build_join_dependency(relation, joins) association_joins = [] joins = joins.map {|j| j.respond_to?(:strip) ? j.strip : j}.uniq joins.each do |join| association_joins << join if [Hash, Array, Symbol, Nodes::Stub, Nodes::Join, Nodes::KeyPath].include?(join.class) && !array_of_strings?(join) end stashed_association_joins = joins.grep(::ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation) non_association_joins = (joins - association_joins - stashed_association_joins) custom_joins = custom_join_sql(*non_association_joins) self.join_dependency = JoinDependency.new(@klass, association_joins, custom_joins) join_dependency.graft(*stashed_association_joins) @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty? to_join = [] join_dependency.join_associations.each do |association| if (association_relation = association.relation).is_a?(Array) to_join << [association_relation.first, association.join_type, association.association_join.first] to_join << [association_relation.last, association.join_type, association.association_join.last] else to_join << [association_relation, association.join_type, association.association_join] end end to_join.uniq.each do |left, join_type, right| relation = relation.join(left, join_type).on(*right) end relation = relation.join(custom_joins) end |
#build_where(opts, other = []) ⇒ Object
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 248 def build_where(opts, other = []) case opts when String, Array super else # Let's prevent PredicateBuilder from doing its thing [opts, *other].map do |arg| case arg when Array # Just in case there's an array in there somewhere @klass.send(:sanitize_sql, arg) when Hash @klass.send(:expand_hash_conditions_for_aggregates, arg) else arg end end end end |
#collapse_wheres(arel, wheres) ⇒ Object
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 266 def collapse_wheres(arel, wheres) wheres = [wheres] unless Array === wheres binaries = wheres.grep(Arel::Nodes::Binary) groups = binaries.group_by {|b| [b.class, b.left]} groups.each do |_, bins| arel = arel.where(bins.inject(&:and)) end (wheres - binaries).each do |where| where = Arel.sql(where) if String === where arel = arel.where(Arel::Nodes::Grouping.new(where)) end arel end |
#debug_sql ⇒ Object
Simulate the logic that occurs in #to_a
This will let us get a dump of the SQL that will be run against the DB for debug purposes without actually running the query.
303 304 305 306 307 308 309 310 311 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 303 def debug_sql if eager_loading? including = (@eager_load_values + @includes_values).uniq join_dependency = JoinDependency.new(@klass, including, nil) construct_relation_for_association_find(join_dependency).to_sql else arel.to_sql end end |
#eager_load(*args) ⇒ Object
178 179 180 181 182 183 184 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 178 def eager_load(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#find_equality_predicates(nodes) ⇒ Object
284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 284 def find_equality_predicates(nodes) nodes.map { |node| case node when Arel::Nodes::Equality node if node.left.relation.name == table_name when Arel::Nodes::Grouping find_equality_predicates([node.expr]) when Arel::Nodes::And find_equality_predicates(node.children) else nil end }.compact.flatten end |
#flatten_nodes(nodes) ⇒ Object
315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/squeel/adapters/active_record/3.1/relation_extensions.rb', line 315 def flatten_nodes(nodes) nodes.map { |node| case node when Array flatten_nodes(node) when Nodes::And flatten_nodes(node.children) when Nodes::Grouping flatten_nodes(node.expr) else node end }.flatten end |
#group(*args) ⇒ Object
200 201 202 203 204 205 206 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 200 def group(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#having(*args) ⇒ Object
240 241 242 243 244 245 246 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 240 def having(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#includes(*args) ⇒ Object
162 163 164 165 166 167 168 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 162 def includes(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#joins(*args) ⇒ Object
224 225 226 227 228 229 230 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 224 def joins(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#merge(r, skip_visit = false) ⇒ Object
We need to be able to support merging two relations without having to get our hooks too deeply into ActiveRecord. AR’s relation merge functionality is very cool, but relatively complex, to handle the various edge cases. Our best shot at avoiding strange behavior with Squeel loaded is to visit the *_values arrays in the relations we’re merging, and then use the default AR merge code on the result.
42 43 44 45 46 47 48 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 42 def merge(r, skip_visit = false) if skip_visit or not ::ActiveRecord::Relation === r super(r) else visited.merge(r.visited, true) end end |
#order(*args) ⇒ Object
208 209 210 211 212 213 214 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 208 def order(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#overwrite_squeel_equalities(wheres) ⇒ Object
330 331 332 333 334 335 336 337 338 339 340 |
# File 'lib/squeel/adapters/active_record/3.1/relation_extensions.rb', line 330 def overwrite_squeel_equalities(wheres) seen = {} flatten_nodes(wheres).reverse.reject { |n| nuke = false if Nodes::Predicate === n && n.method_name == :eq nuke = seen[n.expr] seen[n.expr] = true end nuke }.reverse end |
#predicate_visitor ⇒ Object
23 24 25 26 27 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 23 def predicate_visitor Visitors::PredicateVisitor.new( Context.new(join_dependency) ) end |
#preload(*args) ⇒ Object
170 171 172 173 174 175 176 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 170 def preload(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#reorder(*args) ⇒ Object
216 217 218 219 220 221 222 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 216 def reorder(*args) if block_given? && args.empty? super(DSL.eval &Proc.new) else super end end |
#select(value = Proc.new) ⇒ Object
186 187 188 189 190 191 192 193 194 195 196 197 198 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 186 def select(value = Proc.new) if block_given? && Proc === value if value.arity > 0 to_a.select {|*block_args| value.call(*block_args)} else relation = clone relation.select_values += Array.wrap(DSL.eval &value) relation end else super end end |
#select_for_count ⇒ Object
So, building a select for a count query in ActiveRecord is pretty heavily dependent on select_values containing strings. I’d initially expected that I could just hack together a fix to select_for_count and everything would fall in line, but unfortunately, pretty much everything from that point on in ActiveRecord::Calculations#perform_calculation expects the column to be a string, or at worst, a symbol.
In the long term, I would like to refactor the code in Rails core, but for now, I’m going to settle for this hack that tries really hard to coerce things to a string.
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 106 def select_for_count visited_values = attribute_visitor.accept(select_values.uniq) if visited_values.size == 1 select = visited_values.first str_select = case select when String select when Symbol select.to_s else select.to_sql if select.respond_to?(:to_sql) end str_select if str_select && str_select !~ /[,*]/ end end |
#visit! ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 54 def visit! predicate_viz = predicate_visitor attribute_viz = attribute_visitor @where_values = predicate_viz.accept((@where_values - ['']).uniq) @having_values = predicate_viz.accept(@having_values.uniq.reject{|h| h.blank?}) # FIXME: AR barfs on ARel attributes in group_values. Workaround? # @group_values = attribute_viz.accept(@group_values.uniq.reject{|g| g.blank?}) @order_values = attribute_viz.accept(@order_values.uniq.reject{|o| o.blank?}) @select_values = attribute_viz.accept(@select_values.uniq) self end |
#visited ⇒ Object
50 51 52 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 50 def visited clone.visit! end |
#where(opts = Proc.new, *rest) ⇒ Object
232 233 234 235 236 237 238 |
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 232 def where(opts = Proc.new, *rest) if block_given? && Proc === opts super(DSL.eval &opts) else super end end |
#where_values_hash_with_squeel ⇒ Object
where_values_hash is used in scope_for_create. It’s what allows new records to be created with any equality values that exist in your model’s default scope. We hijack it in order to dig down into And and Grouping nodes, which are equivalent to seeing top-level Equality nodes in stock AR terms.
399 400 401 402 403 |
# File 'lib/squeel/adapters/active_record/3.1/relation_extensions.rb', line 399 def where_values_hash_with_squeel equalities = find_equality_predicates(predicate_visitor.accept(@where_values)) Hash[equalities.map { |where| [where.left.name, where.right] }] end |
#with_default_scope_with_squeel ⇒ Object
with_default_scope was added to ActiveRecord ~> 3.1 in order to address github.com/rails/rails/issues/1233. Unfortunately, it plays havoc with Squeel’s approach of visiting both sides of a relation merge. Thankfully, when merging with a relation from the same AR::Base, it’s unnecessary to visit…
Except, of course, this means we have to handle the edge case where equalities are duplicated on both sides of the merge, in which case, unlike all other chained relation calls, the latter equality overwrites the former.
The workaround using overwrite_squeel_equalities works as long as you stick to the Squeel DSL, but breaks down if you throw hash conditions into the mix. If anyone’s got any suggestions, I’m all ears. Otherwise, just stick to the Squeel DSL.
Or, don’t use default scopes. They’re the devil, anyway. I can’t remember the last time I used one and didn’t find myself regretting the decision later.
424 425 426 427 428 429 430 431 432 433 434 435 436 |
# File 'lib/squeel/adapters/active_record/3.1/relation_extensions.rb', line 424 def with_default_scope_with_squeel if default_scoped? && default_scope = klass.build_default_scope_with_squeel default_scope = default_scope.merge(self, true) default_scope.default_scoped = false default_scope.where_values = overwrite_squeel_equalities( default_scope.where_values + self.where_values ) default_scope else self end end |