aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/primitives/expression.rb
blob: 836f0147456ae7dd732aecbdeec9677bebd48ef4 (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
module Arel
  class Expression < Attribute
    attributes :attribute, :function_sql, :alias, :ancestor
    deriving :==
    delegate :relation, :to => :attribute
    alias_method :name, :alias

    def initialize(attribute, function_sql, aliaz = nil, ancestor = nil)
      @attribute, @function_sql, @alias, @ancestor = attribute, function_sql, aliaz, ancestor
    end

    def to_sql(formatter = Sql::SelectClause.new(relation))
      formatter.expression self
    end

    def aggregation?
      true
    end

    module Transformations
      def as(aliaz)
        Expression.new(attribute, function_sql, aliaz, self)
      end

      def bind(new_relation)
        new_relation == relation ? self : Expression.new(attribute.bind(new_relation), function_sql, @alias, self)
      end

      def to_attribute
        Attribute.new(relation, @alias, :ancestor => self)
      end
    end
    include Transformations
  end
end