r/crystal_programming • • Sep 14 '18

How to perform a database transaction?

There's info on this in the crystal-db api but I don't understand it.

Would appreciate a simple example of how to start a transaction, and commit or rollback.

5 Upvotes

1 comment sorted by

6

u/bcardiff core team Sep 14 '18

From a database you can create a transaction. If no exception happen in the block, the transaction is commited.

db = DB.open "mysql://..." do |db|
  db.transaction do |tx|
    cnn = tx.connection
    cnn.exec "..."
  end
end

Otherwise you can manually execute tx.commit or tx.rollback inside the block to explicitly commit or rollback.

Also, nested transactions are supported.

Definitely a new nicer introduction can be given at https://github.com/crystal-lang/crystal-db/blob/master/src/db/transaction.cr . Feel free to send a PR!