aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/relations/writes/update.rb
blob: 52ca6ecf05f4642a1e1d4caa113d41323dc2d3b3 (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
module Arel
  class Update < Compound
    attributes :relation, :assignments
    deriving :==

    def initialize(relation, assignments)
      @relation, @assignments = relation, assignments
    end

    def to_sql(formatter = nil)
      [
        "UPDATE #{table_sql} SET",
        map_assignments,
        ("WHERE #{wheres.map(&:to_sql).join('\n\tAND ')}"  unless wheres.blank?  ),
        ("LIMIT #{taken}"                                      unless taken.blank?    )
      ].join("\n")
    end

    def call(connection = engine)
      connection.update(to_sql)
    end

    def map_assignments
      assignments.collect do |attribute, value|
        attribute.respond_to?(:name) ?
          "#{engine.quote_column_name(attribute.name)} = #{attribute.format(value)}" : attribute
      end.join(",\n")
    end
  end
end