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 # == Nested transactions
126 # #transaction calls can be nested. By default, this makes all database
127 # statements in the nested transaction block become part of the parent
128 # transaction. For example:
130 # User.transaction do
131 # User.create(:username => 'Kotori')
132 # User.transaction do
133 # User.create(:username => 'Nemu')
134 # raise ActiveRecord::Rollback
138 # User.find(:all) # => empty
140 # It is also possible to requires a sub-transaction by passing
141 # <tt>:requires_new => true</tt>. If anything goes wrong, the
142 # database rolls back to the beginning of the sub-transaction
143 # without rolling back the parent transaction. For example:
145 # User.transaction do
146 # User.create(:username => 'Kotori')
147 # User.transaction(:requires_new => true) do
148 # User.create(:username => 'Nemu')
149 # raise ActiveRecord::Rollback
153 # User.find(:all) # => Returns only Kotori
155 # Most databases don't support true nested transactions. At the time of
156 # writing, the only database that we're aware of that supports true nested
157 # transactions, is MS-SQL. Because of this, Active Record emulates nested
158 # transactions by using savepoints. See
159 # http://dev.mysql.com/doc/refman/5.0/en/savepoints.html
160 # for more information about savepoints.
164 # If you're on MySQL, then do not use DDL operations in nested transactions
165 # blocks that are emulated with savepoints. That is, do not execute statements
166 # like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
167 # releases all savepoints upon executing a DDL operation. When #transaction
168 # is finished and tries to release the savepoint it created earlier, a
169 # database error will occur because the savepoint has already been
170 # automatically released. The following example demonstrates the problem:
172 # Model.connection.transaction do # BEGIN
173 # Model.connection.transaction(:requires_new => true) do # CREATE SAVEPOINT active_record_1
174 # Model.connection.create_table(...) # active_record_1 now automatically released
175 # end # RELEASE savepoint active_record_1
176 # # ^^^^ BOOM! database error!
179 # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
180 def transaction(options
= {}, &block
)
181 # See the ConnectionAdapters::DatabaseStatements#transaction API docs.
182 connection
.transaction(options
, &block
)
186 # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
187 def transaction(&block
)
188 self.class.transaction(&block
)
191 def destroy_with_transactions
#:nodoc:
192 with_transaction_returning_status(:destroy_without_transactions)
195 def save_with_transactions(perform_validation
= true) #:nodoc:
196 rollback_active_record_state
! { with_transaction_returning_status(:save_without_transactions, perform_validation
) }
199 def save_with_transactions
! #:nodoc:
200 rollback_active_record_state
! { self.class.transaction
{ save_without_transactions
! } }
203 # Reset id and @new_record if the transaction rolls back.
204 def rollback_active_record_state
!
205 id_present
= has_attribute
?(self.class.primary_key
)
207 previous_new_record
= new_record
?
210 @new_record = previous_new_record
212 self.id
= previous_id
214 @attributes.delete(self.class.primary_key
)
215 @attributes_cache.delete(self.class.primary_key
)
220 # Executes +method+ within a transaction and captures its return value as a
221 # status flag. If the status is true the transaction is committed, otherwise
222 # a ROLLBACK is issued. In any case the status flag is returned.
224 # This method is available within the context of an ActiveRecord::Base
226 def with_transaction_returning_status(method
, *args
)
228 self.class.transaction
do
229 status
= send(method
, *args
)
230 raise ActiveRecord
::Rollback unless status