4 # See ActiveRecord::Transactions::ClassMethods for documentation.
6 class TransactionError
< ActiveRecordError
# :nodoc:
9 def self.included(base
)
10 base
.extend(ClassMethods
)
13 [:destroy, :save, :save!].each
do |method
|
14 alias_method_chain method
, :transactions
19 # Transactions are protective blocks where SQL statements are only permanent
20 # if they can all succeed as one atomic action. The classic example is a
21 # transfer between two accounts where you can only have a deposit if the
22 # withdrawal succeeded and vice versa. Transactions enforce the integrity of
23 # the database and guard the data against program errors or database
24 # break-downs. So basically you should use transaction blocks whenever you
25 # have a number of statements that must be executed together or not at all.
28 # ActiveRecord::Base.transaction do
29 # david.withdrawal(100)
33 # This example will only take money from David and give to Mary if neither
34 # +withdrawal+ nor +deposit+ raises an exception. Exceptions will force a
35 # ROLLBACK that returns the database to the state before the transaction was
36 # begun. Be aware, though, that the objects will _not_ have their instance
37 # data returned to their pre-transactional state.
39 # == Different Active Record classes in a single transaction
41 # Though the transaction class method is called on some Active Record class,
42 # the objects within the transaction block need not all be instances of
43 # that class. This is because transactions are per-database connection, not
46 # In this example a <tt>Balance</tt> record is transactionally saved even
47 # though <tt>transaction</tt> is called on the <tt>Account</tt> class:
49 # Account.transaction do
54 # Note that the +transaction+ method is also available as a model instance
55 # method. For example, you can also do this:
57 # balance.transaction do
62 # == Transactions are not distributed across database connections
64 # A transaction acts on a single database connection. If you have
65 # multiple class-specific databases, the transaction will not protect
66 # interaction among them. One workaround is to begin a transaction
67 # on each class whose models you alter:
69 # Student.transaction do
70 # Course.transaction do
71 # course.enroll(student)
72 # student.units += course.units
76 # This is a poor solution, but full distributed transactions are beyond
77 # the scope of Active Record.
79 # == Save and destroy are automatically wrapped in a transaction
81 # Both Base#save and Base#destroy come wrapped in a transaction that ensures
82 # that whatever you do in validations or callbacks will happen under the
83 # protected cover of a transaction. So you can use validations to check for
84 # values that the transaction depends on or you can raise exceptions in the
85 # callbacks to rollback, including <tt>after_*</tt> callbacks.
87 # == Exception handling and rolling back
89 # Also have in mind that exceptions thrown within a transaction block will
90 # be propagated (after triggering the ROLLBACK), so you should be ready to
91 # catch those in your application code.
93 # One exception is the ActiveRecord::Rollback exception, which will trigger
94 # a ROLLBACK when raised, but not be re-raised by the transaction block.
96 # *Warning*: one should not catch ActiveRecord::StatementInvalid exceptions
97 # inside a transaction block. StatementInvalid exceptions indicate that an
98 # error occurred at the database level, for example when a unique constraint
99 # is violated. On some database systems, such as PostgreSQL, database errors
100 # inside a transaction causes the entire transaction to become unusable
101 # until it's restarted from the beginning. Here is an example which
102 # demonstrates the problem:
104 # # Suppose that we have a Number model with a unique column called 'i'.
105 # Number.transaction do
106 # Number.create(:i => 0)
108 # # This will raise a unique constraint error...
109 # Number.create(:i => 0)
110 # rescue ActiveRecord::StatementInvalid
111 # # ...which we ignore.
114 # # On PostgreSQL, the transaction is now unusable. The following
115 # # statement will cause a PostgreSQL error, even though the unique
116 # # constraint is no longer violated:
117 # Number.create(:i => 1)
118 # # => "PGError: ERROR: current transaction is aborted, commands
119 # # ignored until end of transaction block"
122 # One should restart the entire transaction if a StatementError occurred.
124 # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
125 def transaction(&block
)
126 connection
.increment_open_transactions
129 connection
.transaction(connection
.open_transactions
== 1, &block
)
131 connection
.decrement_open_transactions
136 # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
137 def transaction(&block
)
138 self.class.transaction(&block
)
141 def destroy_with_transactions
#:nodoc:
142 with_transaction_returning_status(:destroy_without_transactions)
145 def save_with_transactions(perform_validation
= true) #:nodoc:
146 rollback_active_record_state
! { with_transaction_returning_status(:save_without_transactions, perform_validation
) }
149 def save_with_transactions
! #:nodoc:
150 rollback_active_record_state
! { transaction
{ save_without_transactions
! } }
153 # Reset id and @new_record if the transaction rolls back.
154 def rollback_active_record_state
!
155 id_present
= has_attribute
?(self.class.primary_key
)
157 previous_new_record
= new_record
?
160 @new_record = previous_new_record
162 self.id
= previous_id
164 @attributes.delete(self.class.primary_key
)
165 @attributes_cache.delete(self.class.primary_key
)
170 # Executes +method+ within a transaction and captures its return value as a
171 # status flag. If the status is true the transaction is committed, otherwise
172 # a ROLLBACK is issued. In any case the status flag is returned.
174 # This method is available within the context of an ActiveRecord::Base
176 def with_transaction_returning_status(method
, *args
)
179 status
= send(method
, *args
)
180 raise ActiveRecord
::Rollback unless status