Class: SQB::Update

Inherits:
Base
  • Object
show all
Includes:
Filtering, Limiting
Defined in:
lib/sqb/update.rb

Instance Attribute Summary

Attributes inherited from Base

#options, #prepared_arguments

Instance Method Summary collapse

Methods included from Limiting

#limit

Methods included from Filtering

#or, #where

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from SQB::Base

Instance Method Details

#set(hash) ⇒ Object

Set a value to be updated

Parameters:

  • key (String)
  • value (String, nil)


43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sqb/update.rb', line 43

def set(hash)
  if @where
    raise QueryError, "Filtering has already been provided. Must filter after setting values."
  end

  @sets ||= {}
  hash.each do |key, value|
    @sets[key] = value_escape(value)
  end
  self
end

#to_sqlObject



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
# File 'lib/sqb/update.rb', line 11

def to_sql
  [].tap do |query|
    query << "UPDATE"
    query << escape_and_join(@options[:database_name], @table_name)
    query << "SET"
    if @sets && !@sets.empty?
      query << @sets.map do |key, value|
        "#{escape_and_join(@table_name, key)} = #{value}"
      end.join(', ')
    else
      raise NoValuesError, "No values have been updated. Use `set` to set the values to update."
    end

    if @where && !@where.empty?
      query << "WHERE"
      query << @where.join(' AND ')
    end

    if @limit
      query << "LIMIT #{@limit.to_i}"
    end

    if @offset
      query << "OFFSET #{@offset.to_i}"
    end
  end.join(' ')
end