Skip to content

Transactions

module

Defined in src/ralph/transactions.cr:27

Transaction support for models

This module provides transaction management capabilities including: - Model-level transactions (Model.transaction { ... }) - Nested transaction support (savepoints) - Transaction callbacks (after_commit, after_rollback) - Connection pinning for proper transactional isolation

All transaction state is stored per-Fiber to ensure thread/fiber safety in concurrent environments (e.g., web servers handling multiple requests).

Connection Pinning

When inside a transaction, all database operations are pinned to a single connection. This ensures that operations like foreign key checks see uncommitted data from earlier operations in the same transaction.

Example:

User.transaction do
  user1 = User.create(name: "Alice")
  user2 = User.create(name: "Bob")
  # Both will be saved or both will be rolled back
end

Class Methods

.after_commit

View source

Register an after_commit callback


.after_rollback

View source

Register an after_rollback callback


.cleanup_fiber_state(fiber_id : UInt64 | Nil = nil)

View source

Clean up state for a fiber (call when fiber ends if needed)


.clear_transaction_callbacks

View source

Clear all transaction callbacks


.fiber_state

View source

Get the transaction state for the current fiber


.has_pinned_connection?

View source

Check if there's a pinned connection for the current fiber


.in_transaction?

View source

Check if currently in a transaction


.pinned_connection

View source

Get the pinned connection for the current fiber (if in a transaction)


.pinned_connection=(conn : DB::Connection | Nil)

View source

Set the pinned connection for the current fiber


.run_after_commit_callbacks

View source

Run after_commit callbacks


.run_after_rollback_callbacks

View source

Run after_rollback callbacks


.transaction_committed=(value : Bool)

View source

Setter for transaction committed state


.transaction_committed?

View source

Check if the current transaction is committed (not rolled back)


.transaction_depth

View source

Get the current transaction depth


.transaction_depth=(value : Int32)

View source

Increment transaction depth


Nested Types

  • FiberState -

    Fiber-local transaction state container