aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/insert_manager.rb
blob: 8839dd8181504d3406a40642b2969632d32f5367 (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
module Arel
  class InsertManager < Arel::TreeManager
    def initialize engine
      super
      @ast = Nodes::InsertStatement.new
    end

    def into table
      @ast.relation = table
      self
    end

    def columns; @ast.columns end
    def values= val; @ast.values = val; end

    def select select
      @ast.select = select
    end

    def insert fields
      return if fields.empty?

      if String === fields
        @ast.values = Nodes::SqlLiteral.new(fields)
      else
        @ast.relation ||= fields.first.first.relation

        values = []

        fields.each do |column, value|
          @ast.columns << column
          values << value
        end
        @ast.values = create_values values, @ast.columns
      end
    end

    def create_values values, columns
      Nodes::Values.new values, columns
    end
  end
end