Sha256: 9ac0bfb4cfa2563842811ebb2160c965dbbd4d71886730af4038ee4f6a0c96ce

Contents?: true

Size: 1.04 KB

Versions: 7

Compression:

Stored size: 1.04 KB

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.collect { |column|
      column.to_s == 'id' ? 'id' : "`#{column}`"
    }.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
    when Date
      value.to_time.to_i
    when Array
      "(#{value.join(',')})"
    else
      value
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
riddle-2.2.0 lib/riddle/query/insert.rb
riddle-2.1.0 lib/riddle/query/insert.rb
riddle-2.0.0 lib/riddle/query/insert.rb
riddle-1.5.12 lib/riddle/query/insert.rb
riddle-1.5.11 lib/riddle/query/insert.rb
riddle-1.5.10 lib/riddle/query/insert.rb
riddle-1.5.9 lib/riddle/query/insert.rb