Sha256: 83a7560f1cffbba5c4f4b7c4deb0485e899b91c0a195fb6dbfd367ee00db4e08

Contents?: true

Size: 861 Bytes

Versions: 6

Compression:

Stored size: 861 Bytes

Contents

class Riddle::Query::Insert
  attr_reader :columns, :values
  
  def initialize(index, columns = [], values = [])
    @index   = index
    @columns = columns
    @values  = values.first.is_a?(Array) ? values : [values]
    @replace = false
  end
  
  def replace!
    @replace = true
    self
  end
  
  def to_sql
    "#{command} INTO #{@index} (#{columns_to_s}) VALUES (#{values_to_s})"
  end
  
  private
  
  def command
    @replace ? 'REPLACE' : 'INSERT'
  end
  
  def columns_to_s
    columns.join(', ')
  end
        
  def values_to_s
    values.collect { |value_set|
      value_set.collect { |value|
        translated_value(value)
      }.join(', ')
    }.join('), (')
  end
  
  def translated_value(value)
    case value
    when String
      "'#{value}'"
    when TrueClass, FalseClass
      value ? 1 : 0
    else
      value
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
riddle-1.5.3 lib/riddle/query/insert.rb
riddle-1.5.2 lib/riddle/query/insert.rb
riddle-1.5.1 lib/riddle/query/insert.rb
riddle-1.5.0 lib/riddle/query/insert.rb
riddle-1.4.0 lib/riddle/query/insert.rb
riddle-1.3.3 lib/riddle/query/insert.rb