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

Defined Under Namespace

Modules: WhereChainCompatibility

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
19
20
21
22
23
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 16

def join_dependency
  @join_dependency ||= (
    build_join_dependency(
      Arel::SelectManager.new(table.engine, 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/



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

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



70
71
72
73
74
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 70

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

#build_arelObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 23

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_fromObject



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 58

def build_from
  opts, name = from_visit(from_value)
  case opts
  when ::ActiveRecord::Relation
    name ||= 'subquery'
    opts.arel.as(name.to_s)
  when ::Arel::SelectManager
    name ||= 'subquery'
    opts.as(name.to_s)
  else
    opts
  end
end

#build_join_dependency(relation, joins) ⇒ Object



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
143
144
145
146
147
148
149
150
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 107

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_joinsObject

For 4.x adapters



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 152

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_order(arel) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 72

def build_order(arel)
  orders = order_visit(dehashified_order_values)
  orders = reverse_sql_order(attrs_to_orderings(orders)) if reverse_order_value

  orders = orders.uniq.reject(&:blank?).flat_map do |order|
    case order
    when Symbol
      table[order].asc
    when Hash
      order.map { |field, dir| table[field].send(dir) }
    else
      order
    end
  end

  arel.order(*orders) unless orders.empty?
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/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
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 266

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.



346
347
348
349
350
351
352
353
354
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 346

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

#dehashified_order_valuesObject (private)



114
115
116
117
118
119
120
121
122
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 114

def dehashified_order_values
  order_values.map { |o|
    if Hash === o && o.values.all? { |v| [:asc, :desc].include?(v) }
      o.map { |field, dir| table[field].send(dir) }
    else
      o
    end
  }
end

#eager_load(*args) ⇒ Object



170
171
172
173
174
175
176
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 170

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

#find_equality_predicates(nodes) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 282

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



300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 300

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



240
241
242
243
244
245
246
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 240

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

#group(*args) ⇒ Object



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

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

#having(*args) ⇒ Object



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

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

#includes(*args) ⇒ Object



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

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

#joins(*args) ⇒ Object



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

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 Active Record. 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.



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 40

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
    puts r.inspect if r.is_a?(Proc)
    super(r)
  end
end

#merge_resolving_duplicate_squeel_equalities(r) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 315

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



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

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

#order!(*args) ⇒ Object

This is copied directly from 4.0.0’s implementation, but adds an extra exclusion for Squeel::Nodes::Node to fix #248. Can be removed if/when rails/rails#11439 is merged.



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 93

def order!(*args)
  args.flatten!
  validate_order_args args

  references = args.reject { |arg|
    Arel::Node === arg || Squeel::Nodes::Node === arg
  }
  references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
  references!(references) if references.any?

  # if a symbol is given we prepend the quoted table name
  args = args.map { |arg|
    arg.is_a?(Symbol) ? "#{quoted_table_name}.#{arg} ASC" : arg
  }

  self.order_values = args + self.order_values
  self
end

#preload(*args) ⇒ Object



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

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

#reorder(*args) ⇒ Object



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

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

#resolve_duplicate_squeel_equalities(wheres) ⇒ Object



330
331
332
333
334
335
336
337
338
339
340
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 330

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



178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 178

def select(value = Proc.new)
  if block_given? && Proc === value
    if value.arity > 0 || (Squeel.sane_arity? && 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 Active Record 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.



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 87

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 !~ /[,*]/
  else
    :all
  end
end

#visit!Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 57

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

  self
end

#visitedObject

We don’t need to call with_default_scope in AR 3.0.x. In fact, since there is no with_default_scope in 3.0.x, that’d be pretty dumb.



19
20
21
# File 'lib/squeel/adapters/active_record/3.0/relation_extensions.rb', line 19

def visited
  with_default_scope.visit!
end

#where(opts = :chain, *rest) ⇒ Object



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

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.



398
399
400
401
402
403
404
405
406
407
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 398

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

  binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]

  Hash[equalities.map { |where|
    name = where.left.name
    [name, binds.fetch(name.to_s) { where.right }]
  }]
end