Skip to content

Transaction

A database transaction in progress.

Passed to the block given to Connection.transaction. A block that returns without committing or rolling back is committed on success and rolled back on error, so calling either method is only needed to finish early.

Methods

commit()

Commits the transaction, making its changes permanent.

Example

conn.transaction do |tx|
  conn.execute t"UPDATE accounts SET balance = balance - 100 WHERE id = 1"
  conn.execute t"UPDATE accounts SET balance = balance + 100 WHERE id = 2"
  tx.commit()

rollback()

Rolls the transaction back, discarding its changes.

Example

conn.transaction do |tx|
  conn.execute t"INSERT INTO audit (action) VALUES ('attempt')"
  if should_cancel
    tx.rollback()