Sha256: 57440550e081007a3cada65cadd667e19070fdcb1c846458b41d569d5101b50c

Contents?: true

Size: 1.43 KB

Versions: 15

Compression:

Stored size: 1.43 KB

Contents

class Baza::SqlQueries::MysqlUpsertDuplicateKey
  def initialize(args)
    @db = args.fetch(:db)
    @table_name = args.fetch(:table_name)
    @updates = StringCases.stringify_keys(args.fetch(:updates))
    @terms = StringCases.stringify_keys(args.fetch(:terms))
    @buffer = args[:buffer]
    @return_id = args[:return_id]
  end

  def to_sql
    sql = insert_sql
    sql << " ON DUPLICATE KEY UPDATE"

    first = true

    if @return_id
      sql << " #{@db.sep_col}#{@db.escape_column(primary_key_column_name)}#{@db.sep_col} = LAST_INSERT_ID(#{@db.sep_col}#{@db.escape_column(primary_key_column_name)}#{@db.sep_col})"
      first = false
    end

    @updates.each do |key, value|
      sql << "," unless first
      first = false if first
      sql << " #{@db.sep_col}#{@db.escape_column(key)}#{@db.sep_col} = #{@db.sqlval(value)}"
    end

    sql
  end

  def execute
    if @buffer
      @buffer.query(to_sql)
    else
      @db.query(to_sql)
      return @db.query(last_insert_sql).fetch.fetch(:id).to_i if @return_id
    end
  end

private

  def insert_sql
    @db.insert(@table_name, @updates.merge(@terms), return_sql: true)
  end

  def table
    @table ||= @db.tables[@table_name.to_s]
  end

  def primary_key_column_name
    @primary_key_column_name ||= table.columns(primarykey: true).first.name
  end

  def last_insert_sql
    "SELECT LAST_INSERT_ID() AS `id` FROM #{@db.sep_table}#{@db.escape_table(@table_name)}#{@db.sep_table}"
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
baza-0.0.35 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.34 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.33 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.32 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.31 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.30 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.29 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.28 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.27 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.26 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.25 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.24 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.23 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.22 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb
baza-0.0.21 lib/baza/sql_queries/mysql_upsert_duplicate_key.rb