Sha256: 371482b616bc44cb4d9b663f878da203bf1c297506f4512cc4055ea67ba51d0f

Contents?: true

Size: 1.07 KB

Versions: 5

Compression:

Stored size: 1.07 KB

Contents

# frozen_string_literal: true

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

5 entries across 5 versions & 1 rubygems

Version Path
riddle-2.3.2 lib/riddle/query/insert.rb
riddle-2.3.1 lib/riddle/query/insert.rb
riddle-2.3.0 lib/riddle/query/insert.rb
riddle-2.2.2 lib/riddle/query/insert.rb
riddle-2.2.1 lib/riddle/query/insert.rb