aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/where_clause.rb
blob: cd6da052a9f55e531b294d6dcb5ce7d1d7bf4022 (plain) (blame)
1
2
3
4
5
6
7
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
module ActiveRecord
  class Relation
    class WhereClause # :nodoc:
      attr_reader :parts, :binds

      def initialize(parts, binds)
        @parts = parts
        @binds = binds
      end

      def +(other)
        WhereClause.new(
          parts + other.parts,
          binds + other.binds,
        )
      end

      def merge(other)
        WhereClause.new(
          parts_unreferenced_by(other) + other.parts,
          non_conflicting_binds(other) + other.binds,
        )
      end

      def ==(other)
        other.is_a?(WhereClause) &&
          parts == other.parts &&
          binds == other.binds
      end

      def self.empty
        new([], [])
      end

      protected

      def referenced_columns
        @referenced_columns ||= begin
          equality_nodes = parts.select { |n| equality_node?(n) }
          Set.new(equality_nodes, &:left)
        end
      end

      private

      def parts_unreferenced_by(other)
        parts.reject do |n|
          equality_node?(n) && other.referenced_columns.include?(n.left)
        end
      end

      def equality_node?(node)
        node.respond_to?(:operator) && node.operator == :==
      end

      def non_conflicting_binds(other)
        conflicts = referenced_columns & other.referenced_columns
        conflicts.map! { |node| node.name.to_s }
        binds.reject { |col, _| conflicts.include?(col.name) }
      end
    end
  end
end