aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_relation/relations/join.rb
blob: 8e0dcb2a4b18255ce983900fdc189dfd4c720972 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
module ActiveRelation
  class Join < Relation
    attr_reader :join_sql, :relation1, :relation2, :predicates

    def initialize(join_sql, relation1, relation2, *predicates)
      @join_sql, @relation1, @relation2, @predicates = join_sql, relation1, relation2, predicates
    end

    def ==(other)
      self.class == other.class       and
      predicates == other.predicates  and (
        (relation1 == other.relation1 and relation2 == other.relation2) or
        (relation2 == other.relation1 and relation1 == other.relation2)
      )
    end

    def qualify
      descend(&:qualify)
    end
    
    def attributes
      (externalize(relation1).attributes +
        externalize(relation2).attributes).collect { |a| a.bind(self) }
    end
    
    def prefix_for(attribute)
      externalize(relation1).prefix_for(attribute) or
      externalize(relation2).prefix_for(attribute)
    end

    def descend(&block)
      Join.new(join_sql, relation1.descend(&block), relation2.descend(&block), *predicates.collect(&block))
    end
    
    protected
    def joins
      this_join = [
        join_sql,
        externalize(relation2).table_sql,
        "ON",
        predicates.collect { |p| p.bind(self).to_sql }.join(' AND ')
      ].join(" ")
      [relation1.joins, relation2.joins, this_join].compact.join(" ")
    end

    def selects
      externalize(relation1).selects + externalize(relation2).selects
    end
   
    def table_sql
      externalize(relation1).table_sql
    end
    
    private
    def externalize(relation)
      Externalizer.new(relation)
    end
    
    Externalizer = Struct.new(:relation) do
      def table_sql
        relation.aggregation?? relation.to_sql(Sql::Aggregation.new) : relation.send(:table_sql)
      end
      
      def selects
        relation.aggregation?? [] : relation.send(:selects)
      end
      
      def attributes
        relation.aggregation?? relation.attributes.collect(&:to_attribute) : relation.attributes
      end
      
      def prefix_for(attribute)
        if relation[attribute]
          relation.alias?? relation.alias : relation.prefix_for(attribute)
        end
      end
    end
  end
end