aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_relation/predicates.rb
blob: c4f7b835120fbe252c22b8ea97cb70ac9e418e88 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
module ActiveRelation
  class Predicate
    def ==(other)
      self.class == other.class
    end
  end

  class Binary < Predicate
    attr_reader :attribute, :operand

    def initialize(attribute, operand)
      @attribute, @operand = attribute, operand
    end

    def ==(other)
      super and @attribute == other.attribute and @operand == other.operand
    end
    
    def bind(relation)
      descend{ |x| x.bind(relation) }
    end
    
    def qualify
      descend(&:qualify)
    end

    def to_sql(strategy = Sql::Predicate.new)
      "#{attribute.to_sql(strategy)} #{predicate_sql} #{operand.to_sql(strategy)}"
    end
    
    def descend
      self.class.new(yield(attribute), yield(operand))
    end
  end

  class Equality < Binary
    def ==(other)
      self.class == other.class and
        ((attribute == other.attribute and operand == other.operand) or
         (attribute == other.operand and operand == other.attribute))
    end

    protected
    def predicate_sql
      '='
    end
  end

  class GreaterThanOrEqualTo < Binary
    protected
    def predicate_sql
      '>='
    end
  end

  class GreaterThan < Binary
    protected
    def predicate_sql
      '>'
    end
  end

  class LessThanOrEqualTo < Binary
    protected
    def predicate_sql
      '<='
    end
  end

  class LessThan < Binary
    protected
    def predicate_sql
      '<'
    end
  end

  class Match < Binary
    alias_method :regexp, :operand

    def initialize(attribute, regexp)
      @attribute, @regexp = attribute, regexp
    end
  end

  class RelationInclusion < Binary
    alias_method :relation, :operand
    
    protected
    def predicate_sql
      'IN'
    end
  end
end