-
-
Save RX14/250582514cfc4c399289ae185cf6a2eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@@transactions = Hash(PG::Connection, Int32).new { 0 } | |
def self.transaction | |
transaction_id = Random::DEFAULT.next_u32 | |
App.db do |db| | |
transaction_counter = @@transactions[db] | |
if transaction_counter == 0 | |
db.exec("BEGIN") | |
else | |
db.exec("SAVEPOINT txn#{transaction_id}") | |
end | |
@@transactions[db] = transaction_counter + 1 | |
begin | |
yield db | |
@@transactions[db] = transaction_counter | |
if transaction_counter == 0 | |
db.exec("COMMIT") | |
else | |
db.exec("RELEASE SAVEPOINT txn#{transaction_id}") | |
end | |
rescue e | |
@@transactions[db] = transaction_counter | |
if transaction_counter == 0 | |
db.exec("ROLLBACK") | |
else | |
db.exec("ROLLBACK TO SAVEPOINT txn#{transaction_id}") | |
end | |
raise e | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment