aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/table.rb
blob: 06bbe7b99e8135a9ede510f41748cbc5e4607b7a (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
94
95
module Arel
  class Table
    include Arel::Crud

    @engine = nil
    class << self; attr_accessor :engine; end

    attr_reader :name, :engine, :aliases, :table_alias

    def initialize name, engine = Table.engine
      @name    = name
      @engine  = engine
      @engine  = engine[:engine] if Hash === engine
      @columns = nil
      @aliases = []
      @table_alias = nil
      @primary_key = nil

      # Sometime AR sends an :as parameter to table, to let the table know that
      # it is an Alias.  We may want to override new, and return a TableAlias
      # node?
      @table_alias = engine[:as] if Hash === engine
    end

    def primary_key
      @primary_key ||= self[@engine.connection.primary_key(name)]
    end

    def alias
      Nodes::TableAlias.new("#{name}_2", self).tap do |node|
        @aliases << node
      end
    end

    def tm
      SelectManager.new(@engine).from(self)
    end

    def from table
      SelectManager.new(@engine).from table
    end

    def joins manager
      nil
    end

    def join relation, klass = Nodes::InnerJoin
      return tm unless relation

      sm = SelectManager.new(@engine)
      case relation
      when String, Nodes::SqlLiteral
        raise if relation.blank?
        sm.from Nodes::StringJoin.new(self, relation)
      else
        sm.from klass.new(self, relation, nil)
      end
    end

    def group *columns
      tm.group(*columns)
    end

    def order *expr
      tm.order(*expr)
    end

    def where condition
      tm.where condition
    end

    def project *things
      tm.project(*things)
    end

    def take amount
      tm.take amount
    end

    def having expr
      tm.having expr
    end

    def columns
      @columns ||= @engine.connection.columns(@name, "#{@name} Columns").map do |column|
        Attributes.for(column).new self, column.name.to_sym, column
      end
    end

    def [] name
      name = name.to_sym
      columns.find { |column| column.name == name }
    end
  end
end