On Wednesday, January 29, 2014 7:28:04 AM UTC-8, Jay wrote:
>
> Hi, 
>
>      I have been looking for two-phase transaction Mysql2 examples, but 
> there are only posts mentioning this feature.
>      Can any one post code snippet with more than 2 databases illustrating 
> two-phase transaction?
>

Well, there are examples in the transaction guide for a single database 
(http://sequel.jeremyevans.net/rdoc/files/doc/transactions_rdoc.html).

For three databases, something like this may work (though real production 
code would have more error handling:

  DB1.transaction(:prepare => 'foo')
    # ...
  end
  begin
    DB2.transaction(:prepare => 'foo')
      # ...
    end
    begin
      DB3.transaction(:prepare => 'foo')
        # ...
      end
    rescue
      DB2.rollback_prepared_transaction('foo')
      raise
    else
    end
  rescue Sequel::DatabaseError
    DB1.rollback_prepared_transaction('foo')
    raise
  else
    DB1.commit_prepared_transaction('foo')
    DB2.commit_prepared_transaction('foo')
    DB3.commit_prepared_transaction('foo')
  end

Generalizing such a strategy to accommodate an arbitrary number of 
databases may look something like this (though again, you'd probably add 
more error handling):

  def multi_db_commit(tx_id, dbs)
    prepared = []
    dbs.each do |db, pr|
      db.transaction(:prepare=>tx_id, &pr)
      prepared << db
    end
  rescue
    prepared.each do |db|
      begin
        db.rollback_prepared_transaction(tx_id)
      rescue Sequel::DatabaseError
        # ...
      end
    end
  else
    prepared.each do |db|
      begin
        db.commit_prepared_transaction(tx_id)
      rescue Sequel::DatabaseError
        # ...
      end
    end
  end
  multi_db_commit('foo', DB1=>proc{...}, DB2=>proc{...}, DB3=>proc{...})

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to