Class: Baza::SqlQueries::MysqlUpsert

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

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ MysqlUpsert

Returns a new instance of MysqlUpsert.



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

def initialize(args)
  @db = args.fetch(:db)
  @table_name = args.fetch(:table_name)
  @updates = args.fetch(:updates)
  @terms = args.fetch(:terms)
end

Instance Method Details

#executeObject



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

def execute
  procedure_name = "baza_upsert_#{SecureRandom.hex(5)}"

  sql = "CREATE PROCEDURE `#{@db.escape_table(procedure_name)}` () BEGIN\n"
  sql << "\tIF EXISTS(#{select_query}) THEN\n"
  sql << "\t\t#{update_sql};\n"
  sql << "\tELSE\n"
  sql << "\t\t#{insert_sql};\n"
  sql << "\tEND IF;\n"
  sql << "END;\n"

  @db.query(sql)

  begin
    @db.query("CALL `#{@db.escape_table(procedure_name)}`")
  ensure
    @db.query("DROP PROCEDURE `#{@db.escape_table(procedure_name)}`")
  end
end