Class: QueryKit::UpdateQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/querykit/update_query.rb

Overview

UpdateQuery class for building SQL UPDATE statements.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table = nil) ⇒ UpdateQuery

Initialize a new UpdateQuery instance.



9
10
11
12
13
14
# File 'lib/querykit/update_query.rb', line 9

def initialize(table = nil)
  @table = table
  @values = {}
  @wheres = []
  @bindings = []
end

Instance Attribute Details

#bindingsObject (readonly)

Returns the value of attribute bindings.



6
7
8
# File 'lib/querykit/update_query.rb', line 6

def bindings
  @bindings
end

#tableObject (readonly)

Returns the value of attribute table.



6
7
8
# File 'lib/querykit/update_query.rb', line 6

def table
  @table
end

#valuesObject (readonly)

Returns the value of attribute values.



6
7
8
# File 'lib/querykit/update_query.rb', line 6

def values
  @values
end

#wheresObject (readonly)

Returns the value of attribute wheres.



6
7
8
# File 'lib/querykit/update_query.rb', line 6

def wheres
  @wheres
end

Instance Method Details

#set(data) ⇒ Object

Set the values to update.



17
18
19
20
# File 'lib/querykit/update_query.rb', line 17

def set(data)
  @values.merge!(data)
  self
end

#to_sObject

Return the SQL UPDATE statement as a string.



55
56
57
# File 'lib/querykit/update_query.rb', line 55

def to_s
  to_sql
end

#to_sqlObject

Generate the SQL UPDATE statement.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/querykit/update_query.rb', line 34

def to_sql
  raise "No table specified" unless @table
  raise "No values to update" if @values.empty?

  @bindings = @values.values + @wheres.map { |w| w[:value] }

  sql = []
  sql << "UPDATE #{@table}"
  sql << "SET"
  sql << @values.keys.map { |k| "#{k} = ?" }.join(', ')

  unless @wheres.empty?
    sql << "WHERE"
    where_clauses = @wheres.map { |w| "#{w[:column]} #{w[:operator]} ?" }
    sql << where_clauses.join(' AND ')
  end

  sql.join(' ')
end

#where(column, operator = nil, value = nil) ⇒ Object

Add a WHERE condition to the update query.



23
24
25
26
27
28
29
30
31
# File 'lib/querykit/update_query.rb', line 23

def where(column, operator = nil, value = nil)
  if value.nil? && !operator.nil?
    value = operator
    operator = '='
  end

  @wheres << { type: 'basic', column: column, operator: operator, value: value, boolean: 'AND' }
  self
end