Merged updates from trunk into stable branch
[feedcatcher.git] / vendor / rails / activerecord / lib / active_record / transactions.rb
1 require 'thread'
2
3 module ActiveRecord
4 # See ActiveRecord::Transactions::ClassMethods for documentation.
5 module Transactions
6 class TransactionError < ActiveRecordError # :nodoc:
7 end
8
9 def self.included(base)
10 base.extend(ClassMethods)
11
12 base.class_eval do
13 [:destroy, :save, :save!].each do |method|
14 alias_method_chain method, :transactions
15 end
16 end
17 end
18
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.
26 # Example:
27 #
28 # ActiveRecord::Base.transaction do
29 # david.withdrawal(100)
30 # mary.deposit(100)
31 # end
32 #
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.
38 #
39 # == Different Active Record classes in a single transaction
40 #
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
44 # per-model.
45 #
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:
48 #
49 # Account.transaction do
50 # balance.save!
51 # account.save!
52 # end
53 #
54 # Note that the +transaction+ method is also available as a model instance
55 # method. For example, you can also do this:
56 #
57 # balance.transaction do
58 # balance.save!
59 # account.save!
60 # end
61 #
62 # == Transactions are not distributed across database connections
63 #
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:
68 #
69 # Student.transaction do
70 # Course.transaction do
71 # course.enroll(student)
72 # student.units += course.units
73 # end
74 # end
75 #
76 # This is a poor solution, but full distributed transactions are beyond
77 # the scope of Active Record.
78 #
79 # == Save and destroy are automatically wrapped in a transaction
80 #
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.
86 #
87 # == Exception handling and rolling back
88 #
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.
92 #
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.
95 #
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:
103 #
104 # # Suppose that we have a Number model with a unique column called 'i'.
105 # Number.transaction do
106 # Number.create(:i => 0)
107 # begin
108 # # This will raise a unique constraint error...
109 # Number.create(:i => 0)
110 # rescue ActiveRecord::StatementInvalid
111 # # ...which we ignore.
112 # end
113 #
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"
120 # end
121 #
122 # One should restart the entire transaction if a StatementError occurred.
123 #
124 # == Nested transactions
125 #
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:
129 #
130 # User.transaction do
131 # User.create(:username => 'Kotori')
132 # User.transaction do
133 # User.create(:username => 'Nemu')
134 # raise ActiveRecord::Rollback
135 # end
136 # end
137 #
138 # User.find(:all) # => empty
139 #
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:
144 #
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
150 # end
151 # end
152 #
153 # User.find(:all) # => Returns only Kotori
154 #
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.
161 #
162 # === Caveats
163 #
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:
171 #
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!
177 # end
178 module ClassMethods
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)
183 end
184 end
185
186 # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
187 def transaction(&block)
188 self.class.transaction(&block)
189 end
190
191 def destroy_with_transactions #:nodoc:
192 with_transaction_returning_status(:destroy_without_transactions)
193 end
194
195 def save_with_transactions(perform_validation = true) #:nodoc:
196 rollback_active_record_state! { with_transaction_returning_status(:save_without_transactions, perform_validation) }
197 end
198
199 def save_with_transactions! #:nodoc:
200 rollback_active_record_state! { self.class.transaction { save_without_transactions! } }
201 end
202
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)
206 previous_id = id
207 previous_new_record = new_record?
208 yield
209 rescue Exception
210 @new_record = previous_new_record
211 if id_present
212 self.id = previous_id
213 else
214 @attributes.delete(self.class.primary_key)
215 @attributes_cache.delete(self.class.primary_key)
216 end
217 raise
218 end
219
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.
223 #
224 # This method is available within the context of an ActiveRecord::Base
225 # instance.
226 def with_transaction_returning_status(method, *args)
227 status = nil
228 self.class.transaction do
229 status = send(method, *args)
230 raise ActiveRecord::Rollback unless status
231 end
232 status
233 end
234 end
235 end