Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I perform transactions with ruby mysql2

I've started using mysql2 gem. I'm trying to figure out a few basic things - one of them is how to explicitly perform transactions (for batch operations, like multiple INSERT/UPDATE queries).

In the old ruby-mysql, this was my approach:

client  = Mysql.real_connect(...)
inserts = [
  "INSERT INTO ...",
  "UPDATE .. WHERE id=..",
  # etc
]

client.autocommit(false)
inserts.each do |ins|  
  begin
    client.query(ins)
  rescue
    # handle errors or abort entirely
  end
end
client.commit

I couldn't find much in the docs - how can the same be done with mysql2?

like image 967
sa125 Avatar asked Feb 15 '12 05:02

sa125


1 Answers

I just have done a implementation:

class DBConnector
  def transaction(&block)
    raise ArgumentError, "No block was given" unless block_given?
    begin
      client.query("BEGIN")
      yield
      client.query("COMMIT")
    rescue
      client.query("ROLLBACK")
    end
  end
end

So you could use like this:

DBConnector.transaction do
  # your db queries here
end
like image 179
Bruno Coimbra Avatar answered Oct 21 '22 15:10

Bruno Coimbra