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,
lib/squeel/adapters/active_record/3.2/relation_extensions.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#join_dependencyObject

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!



16
17
18
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 16

def join_dependency
  @join_dependency ||= (build_join_dependency(table.from(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 is defined on the ActiveRecord::Relation class, itself.

Since it’s defined there, but I would very much like to modify its behavior, I have three choices:

  1. 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().

  2. Submit a patch to Rails core, breaking this method off into another module, all for my own selfish desire to use super() while mucking about in Rails internals.

  3. 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/



377
378
379
380
381
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 377

def self.included(base)
  base.class_eval do
    alias_method_chain :where_values_hash, :squeel
  end
end

Instance Method Details

#attrs_to_orderings(order) ⇒ Object

reverse_sql_order will reverse the order of strings or Orderings, but not attributes



64
65
66
67
68
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 64

def attrs_to_orderings(order)
  order.map do |o|
    Arel::Attribute === o ? o.asc : o
  end
end

#build_arelObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 17

def build_arel
  arel = table

  arel = build_join_dependency(arel, @joins_values) unless @joins_values.empty?

  arel = collapse_wheres(arel, where_visit((@where_values - ['']).uniq))

  arel = arel.having(*having_visit(@having_values.uniq.reject{|h| h.blank?})) unless @having_values.empty?

  arel = arel.take(connection.sanitize_limit(@limit_value)) if @limit_value
  arel = arel.skip(@offset_value) if @offset_value

  arel = arel.group(*group_visit(@group_values.uniq.reject{|g| g.blank?})) unless @group_values.empty?

  arel = arel.order(*order_visit(@order_values.uniq.reject{|o| o.blank?})) unless @order_values.empty?

  arel = build_select(arel, select_visit(@select_values.uniq))

  arel = arel.from(from_visit(@from_value)) if @from_value
  arel = arel.lock(@lock_value) if @lock_value

  arel
end

#build_join_dependency(relation, joins) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 99

def build_join_dependency(manager, joins)
  buckets = joins.group_by do |join|
    case join
    when String
      'string_join'
    when Hash, Symbol, Array, Nodes::Stub, Nodes::Join, Nodes::KeyPath
      'association_join'
    when JoinAssociation
      'stashed_join'
    when Arel::Nodes::Join
      'join_node'
    else
      raise 'unknown class: %s' % join.class.name
    end
  end

  association_joins         = buckets['association_join'] || []
  stashed_association_joins = buckets['stashed_join'] || []
  join_nodes                = (buckets['join_node'] || []).uniq
  string_joins              = (buckets['string_join'] || []).map { |x|
    x.strip
  }.uniq

  join_list = join_nodes + custom_join_ast(manager, string_joins)

  # All of that duplication just to do this...
  self.join_dependency = JoinDependency.new(
    @klass,
    association_joins,
    join_list
  )

  join_dependency.graft(*stashed_association_joins)

  @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?

  join_dependency.join_associations.each do |association|
    association.join_to(manager)
  end

  manager.join_sources.concat join_list

  manager
end

#build_where(opts, other = []) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 238

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



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 256

def collapse_wheres(arel, wheres)
  wheres = Array(wheres)
  binaries = wheres.grep(Arel::Nodes::Binary)

  groups = binaries.group_by {|b| [b.class, b.left]}

  groups.each do |_, bins|
    arel.where(Arel::Nodes::And.new(bins))
  end

  (wheres - binaries).each do |where|
    where = Arel.sql(where) if String === where
    arel.where(Arel::Nodes::Grouping.new(where))
  end
end

#debug_sqlObject

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.



336
337
338
339
340
341
342
343
344
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 336

def debug_sql
  if eager_loading?
    including = (@eager_load_values + @includes_values).uniq
    join_dependency = JoinDependency.new(@klass, including, [])
    construct_relation_for_association_find(join_dependency).to_sql
  else
    arel.to_sql
  end
end

#eager_load(*args) ⇒ Object



160
161
162
163
164
165
166
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 160

def eager_load(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#find_equality_predicates(nodes) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 272

def find_equality_predicates(nodes)
  nodes.map { |node|
    case node
    when Arel::Nodes::Equality
      if node.left.respond_to?(:relation) &&
        node.left.relation.name == table_name
        node
      end
    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



290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 290

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

#from(*args) ⇒ Object



230
231
232
233
234
235
236
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 230

def from(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#group(*args) ⇒ Object



182
183
184
185
186
187
188
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 182

def group(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#having(*args) ⇒ Object



222
223
224
225
226
227
228
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 222

def having(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#includes(*args) ⇒ Object



144
145
146
147
148
149
150
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 144

def includes(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#joins(*args) ⇒ Object



206
207
208
209
210
211
212
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 206

def joins(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#merge(r, equalities_resolved = false) ⇒ Object

We need to be able to support merging two relations without having to get our hooks too deeply into ActiveRecord. That proves to be easier said than done. I hate Relation#merge. If Squeel has a nemesis, Relation#merge would be it.

Whatever code you see here currently is my current best attempt at coexisting peacefully with said nemesis.



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 35

def merge(r, equalities_resolved = false)
  if ::ActiveRecord::Relation === r && !equalities_resolved
    if self.table_name != r.table_name
      super(r.visited)
    else
      merge_resolving_duplicate_squeel_equalities(r)
    end
  else
    super(r)
  end
end

#merge_resolving_duplicate_squeel_equalities(r) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 305

def merge_resolving_duplicate_squeel_equalities(r)
  left = clone
  right = r.clone
  left.where_values = flatten_nodes(left.where_values)
  right.where_values = flatten_nodes(right.where_values)
  right_equalities = right.where_values.select do |obj|
    Nodes::Predicate === obj && obj.method_name == :eq
  end
  right.where_values -= right_equalities
  left.where_values = resolve_duplicate_squeel_equalities(
    left.where_values + right_equalities
  )
  left.merge(right, true)
end

#order(*args) ⇒ Object



190
191
192
193
194
195
196
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 190

def order(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#preload(*args) ⇒ Object



152
153
154
155
156
157
158
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 152

def preload(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#reorder(*args) ⇒ Object



198
199
200
201
202
203
204
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 198

def reorder(*args)
  if block_given? && args.empty?
    super(DSL.eval &Proc.new)
  else
    super
  end
end

#resolve_duplicate_squeel_equalities(wheres) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 320

def resolve_duplicate_squeel_equalities(wheres)
  seen = {}
  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

#select(value = Proc.new) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 168

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_countObject

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.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 81

def select_for_count
  visited_values = select_visit(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



51
52
53
54
55
56
57
58
59
60
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 51

def visit!
  @where_values = where_visit((@where_values - ['']).uniq)
  @having_values = having_visit(@having_values.uniq.reject{|h| h.blank?})
  # FIXME: AR barfs on ARel attributes in group_values. Workaround?
  # @group_values = group_visit(@group_values.uniq.reject{|g| g.blank?})
  @order_values = order_visit(@order_values.uniq.reject{|o| o.blank?})
  @select_values = select_visit(@select_values.uniq)

  self
end

#visitedObject



47
48
49
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 47

def visited
  clone.visit!
end

#where(opts = Proc.new, *rest) ⇒ Object



214
215
216
217
218
219
220
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 214

def where(opts = Proc.new, *rest)
  if block_given? && Proc === opts
    super(DSL.eval &opts)
  else
    super
  end
end

#where_values_hash_with_squeelObject

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.



388
389
390
391
392
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 388

def where_values_hash_with_squeel
  equalities = find_equality_predicates(where_visit(with_default_scope.where_values))

  Hash[equalities.map { |where| [where.left.name, where.right] }]
end