aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/relations/writes/update.rb
blob: 760f4e931fc3e73ee8990f0cc5701c5e2fab73c9 (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
    attr_reader :assignments

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

    def to_sql(formatter = nil)
      [
        "UPDATE #{table_sql} SET",
        assignments.collect do |attribute, value|
          "#{value.format(attribute)} = #{attribute.format(value)}"
        end.join(",\n"),
        ("WHERE #{wheres.collect(&:to_sql).join('\n\tAND ')}"  unless wheres.blank?  ),
        ("LIMIT     #{taken}"                                  unless taken.blank?    )
      ].join("\n")
    end
    
    def call(connection = engine.connection)
      connection.update(to_sql)
    end
    
    def ==(other)
      Update      === other          and
      relation    ==  other.relation and
      assignments ==  other.assignments
    end
  end
end