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

#reverse_order_valueObject (private)

Returns the value of attribute reverse_order_value.



10
11
12
# File 'lib/squeel/adapters/active_record/4.2/relation_extensions.rb', line 10

def reverse_order_value
  @reverse_order_value
end

#stashed_join_dependenciesObject (private)

Returns the value of attribute stashed_join_dependencies.



8
9
10
# File 'lib/squeel/adapters/active_record/4.1/relation_extensions.rb', line 8

def stashed_join_dependencies
  @stashed_join_dependencies
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/



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

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



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

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



116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 116

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(manager, joins) ⇒ Object Also known as: build_joins



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

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
    when Nodes::SubqueryJoin
      :subquery_join
    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
  subquery_joins            = (buckets[:subquery_join] || []).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.join_sources.concat(build_join_from_subquery(subquery_joins))

  manager
end

#build_join_from_subquery(subquery_joins) ⇒ Object (private)



409
410
411
412
413
414
415
416
417
418
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 409

def build_join_from_subquery(subquery_joins)
  subquery_joins.map do |join|
    join.type.new(
      Arel::Nodes::TableAlias.new(
        Arel::Nodes::Grouping.new(join.subquery.left.arel.ast),
        join.subquery.right),
      Arel::Nodes::On.new(where_visit(join.constraints))
    )
  end
end

#build_order(arel) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 130

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



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 251

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



269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 269

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

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

  arel.where(Arel::Nodes::And.new(groups.map{|_, bins| bins}.flatten)) if groups.any?

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



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

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)



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

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



173
174
175
176
177
178
179
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 173

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

#execute_grouped_calculation(operation, column_name, distinct) ⇒ Object



437
438
439
440
441
442
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 437

def execute_grouped_calculation(operation, column_name, distinct)
  arel = Arel::SelectManager.new(table.engine, table)
  build_join_dependency(arel, joins_values.flatten) unless joins_values.empty?
  self.group_values = group_visit(group_values.uniq.reject{|g| g.blank?}) unless group_values.empty?
  super
end

#expand_attrs_from_hash(opts) ⇒ Object



273
274
275
276
277
278
279
280
281
282
# File 'lib/squeel/adapters/active_record/4.1/relation_extensions.rb', line 273

def expand_attrs_from_hash(opts)
  opts = ::ActiveRecord::PredicateBuilder.resolve_column_aliases(klass, opts)
  attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)

  attributes.values.grep(::ActiveRecord::Relation) do |rel|
    self.bind_values += rel.bind_values
  end

  attributes
end

#find_equality_predicates(nodes, relation_table_name = table_name) ⇒ Object



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

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



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

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



243
244
245
246
247
248
249
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 243

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

#group(*args) ⇒ Object



195
196
197
198
199
200
201
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 195

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

#having(*args) ⇒ Object



235
236
237
238
239
240
241
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 235

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

#includes(*args) ⇒ Object



157
158
159
160
161
162
163
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 157

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

#joins(*args) ⇒ Object



219
220
221
222
223
224
225
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 219

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
# 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
    super(r)
  end
end

#merge_resolving_duplicate_squeel_equalities(r) ⇒ Object



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

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



203
204
205
206
207
208
209
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 203

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.



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 151

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) ?
      Arel::Nodes::Ascending.new(klass.arel_table[arg]) :
      arg
  }

  self.order_values += args
  self
end

#preload(*args) ⇒ Object



165
166
167
168
169
170
171
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 165

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

#preprocess_attrs_with_ar(attributes) ⇒ Object



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 420

def preprocess_attrs_with_ar(attributes)
  attributes.map do |key, value|
    case key
      when Squeel::Nodes::Node
        {key => value}
      when Symbol
        if value.is_a?(Hash)
          {key => value}
        else
          ::ActiveRecord::PredicateBuilder.build_from_hash(klass, {key => value}, table)
        end
      else
        ::ActiveRecord::PredicateBuilder.build_from_hash(klass, {key => value}, table)
      end
  end
end

#reorder(*args) ⇒ Object



211
212
213
214
215
216
217
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 211

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

#resetObject



11
12
13
14
# File 'lib/squeel/adapters/active_record/4.1/relation_extensions.rb', line 11

def reset
  @stashed_join_dependencies = nil
  super
end

#resolve_duplicate_squeel_equalities(wheres) ⇒ Object



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

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

#reverse_order!Object

We are using 4.1 version of reverse_order! Because 4.2 reverse the order immediately before build_order



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

def reverse_order!
  self.reverse_order_value = !reverse_order_value
  self
end

#reverse_sql_order(order_query) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/squeel/adapters/active_record/4.1/relation_extensions.rb', line 63

def reverse_sql_order(order_query)
  return super if order_query.empty?

  order_query.flat_map do |o|
    case o
      when Arel::Attributes::Attribute
        Arel::Nodes::Ascending.new(o).reverse
      else
        super
      end
  end
end

#select(value = Proc.new) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 181

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.



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

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

#to_sql_with_binding_paramsObject



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 183

def to_sql_with_binding_params
  @to_sql ||= begin
    relation   = self
    connection = klass.connection

    if eager_loading?
      find_with_associations { |rel| relation = rel }
    end

    ast   = relation.arel.ast
    binds = relation.bind_values.dup

    visitor = connection.visitor.clone
    visitor.class_eval do
      include ::Arel::Visitors::BindVisitor
    end

    visitor.accept(ast) do
      connection.quote(*binds.shift.reverse)
    end
  end
end

#visit!Object



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

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



227
228
229
230
231
232
233
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 227

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

#where_unscoping(target_value) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/squeel/adapters/active_record/4.0/relation_extensions.rb', line 33

def where_unscoping(target_value)
  target_value = target_value.to_s

  where_values.reject! do |rel|
    case rel
    when Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual
      subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right)
      subrelation.name == target_value
    when Hash
      rel.stringify_keys.has_key?(target_value)
    when Squeel::Nodes::Predicate
      rel.expr.symbol.to_s == target_value if rel.expr.respond_to?(:symbol)
    end
  end

  bind_values.reject! { |col,_| col.name == target_value }
end

#where_values_hash_with_squeel(relation_table_name = table_name) ⇒ 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
404
405
406
407
# File 'lib/squeel/adapters/active_record/relation_extensions.rb', line 399

def where_values_hash_with_squeel(relation_table_name = table_name)
  equalities = find_equality_predicates(where_visit(with_default_scope.where_values), relation_table_name)
  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