Skip to content

Instantly share code, notes, and snippets.

@RX14

RX14/db.cr Secret

Created December 11, 2016 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RX14/250582514cfc4c399289ae185cf6a2eb to your computer and use it in GitHub Desktop.
Save RX14/250582514cfc4c399289ae185cf6a2eb to your computer and use it in GitHub Desktop.
@@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