Froze rails gems
[depot.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 module ClassMethods
124 # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
125 def transaction(&block)
126 connection.increment_open_transactions
127
128 begin
129 connection.transaction(connection.open_transactions == 1, &block)
130 ensure
131 connection.decrement_open_transactions
132 end
133 end
134 end
135
136 # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
137 def transaction(&block)
138 self.class.transaction(&block)
139 end
140
141 def destroy_with_transactions #:nodoc:
142 with_transaction_returning_status(:destroy_without_transactions)
143 end
144
145 def save_with_transactions(perform_validation = true) #:nodoc:
146 rollback_active_record_state! { with_transaction_returning_status(:save_without_transactions, perform_validation) }
147 end
148
149 def save_with_transactions! #:nodoc:
150 rollback_active_record_state! { transaction { save_without_transactions! } }
151 end
152
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)
156 previous_id = id
157 previous_new_record = new_record?
158 yield
159 rescue Exception
160 @new_record = previous_new_record
161 if id_present
162 self.id = previous_id
163 else
164 @attributes.delete(self.class.primary_key)
165 @attributes_cache.delete(self.class.primary_key)
166 end
167 raise
168 end
169
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.
173 #
174 # This method is available within the context of an ActiveRecord::Base
175 # instance.
176 def with_transaction_returning_status(method, *args)
177 status = nil
178 transaction do
179 status = send(method, *args)
180 raise ActiveRecord::Rollback unless status
181 end
182 status
183 end
184 end
185 end