Sha256: 09e7dfcb5191b62b1f20cfa50c32a31dbbebe354fd1f1cb2a5f4edc9ac7dccf8

Contents?: true

Size: 927 Bytes

Versions: 3

Compression:

Stored size: 927 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.gsub(/['\\]/, '').gsub(/\s+/, ' ')}'"
    when TrueClass, FalseClass
      value ? 1 : 0
    when Time
      value.to_i
    else
      value
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
riddle-1.5.6 lib/riddle/query/insert.rb
riddle-1.5.5 lib/riddle/query/insert.rb
riddle-1.5.4 lib/riddle/query/insert.rb