Class: Baza::SqlQueries::MysqlUpsertDuplicateKey

Inherits:
Object
  • Object
show all
Defined in:
lib/baza/sql_queries/mysql_upsert_duplicate_key.rb

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ MysqlUpsertDuplicateKey

Returns a new instance of MysqlUpsertDuplicateKey.



2
3
4
5
6
7
8
9
# File 'lib/baza/sql_queries/mysql_upsert_duplicate_key.rb', line 2

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

Instance Method Details

#executeObject



31
32
33
34
35
36
37
38
# File 'lib/baza/sql_queries/mysql_upsert_duplicate_key.rb', line 31

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

#to_sqlObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/baza/sql_queries/mysql_upsert_duplicate_key.rb', line 11

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