activerecord 3.0.0
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of activerecord might be problematic. Click here for more details.
- data/CHANGELOG +6023 -0
- data/README.rdoc +222 -0
- data/examples/associations.png +0 -0
- data/examples/performance.rb +162 -0
- data/examples/simple.rb +14 -0
- data/lib/active_record.rb +124 -0
- data/lib/active_record/aggregations.rb +277 -0
- data/lib/active_record/association_preload.rb +403 -0
- data/lib/active_record/associations.rb +2254 -0
- data/lib/active_record/associations/association_collection.rb +562 -0
- data/lib/active_record/associations/association_proxy.rb +295 -0
- data/lib/active_record/associations/belongs_to_association.rb +91 -0
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +78 -0
- data/lib/active_record/associations/has_and_belongs_to_many_association.rb +137 -0
- data/lib/active_record/associations/has_many_association.rb +128 -0
- data/lib/active_record/associations/has_many_through_association.rb +116 -0
- data/lib/active_record/associations/has_one_association.rb +143 -0
- data/lib/active_record/associations/has_one_through_association.rb +40 -0
- data/lib/active_record/associations/through_association_scope.rb +154 -0
- data/lib/active_record/attribute_methods.rb +60 -0
- data/lib/active_record/attribute_methods/before_type_cast.rb +33 -0
- data/lib/active_record/attribute_methods/dirty.rb +95 -0
- data/lib/active_record/attribute_methods/primary_key.rb +50 -0
- data/lib/active_record/attribute_methods/query.rb +39 -0
- data/lib/active_record/attribute_methods/read.rb +116 -0
- data/lib/active_record/attribute_methods/time_zone_conversion.rb +61 -0
- data/lib/active_record/attribute_methods/write.rb +37 -0
- data/lib/active_record/autosave_association.rb +369 -0
- data/lib/active_record/base.rb +1867 -0
- data/lib/active_record/callbacks.rb +288 -0
- data/lib/active_record/connection_adapters/abstract/connection_pool.rb +365 -0
- data/lib/active_record/connection_adapters/abstract/connection_specification.rb +113 -0
- data/lib/active_record/connection_adapters/abstract/database_limits.rb +57 -0
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +329 -0
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +81 -0
- data/lib/active_record/connection_adapters/abstract/quoting.rb +72 -0
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +739 -0
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +543 -0
- data/lib/active_record/connection_adapters/abstract_adapter.rb +212 -0
- data/lib/active_record/connection_adapters/mysql_adapter.rb +643 -0
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +1030 -0
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +53 -0
- data/lib/active_record/connection_adapters/sqlite_adapter.rb +401 -0
- data/lib/active_record/counter_cache.rb +115 -0
- data/lib/active_record/dynamic_finder_match.rb +53 -0
- data/lib/active_record/dynamic_scope_match.rb +32 -0
- data/lib/active_record/errors.rb +172 -0
- data/lib/active_record/fixtures.rb +1008 -0
- data/lib/active_record/locale/en.yml +40 -0
- data/lib/active_record/locking/optimistic.rb +172 -0
- data/lib/active_record/locking/pessimistic.rb +55 -0
- data/lib/active_record/log_subscriber.rb +48 -0
- data/lib/active_record/migration.rb +617 -0
- data/lib/active_record/named_scope.rb +138 -0
- data/lib/active_record/nested_attributes.rb +417 -0
- data/lib/active_record/observer.rb +140 -0
- data/lib/active_record/persistence.rb +291 -0
- data/lib/active_record/query_cache.rb +36 -0
- data/lib/active_record/railtie.rb +91 -0
- data/lib/active_record/railties/controller_runtime.rb +38 -0
- data/lib/active_record/railties/databases.rake +512 -0
- data/lib/active_record/reflection.rb +403 -0
- data/lib/active_record/relation.rb +393 -0
- data/lib/active_record/relation/batches.rb +89 -0
- data/lib/active_record/relation/calculations.rb +286 -0
- data/lib/active_record/relation/finder_methods.rb +355 -0
- data/lib/active_record/relation/predicate_builder.rb +41 -0
- data/lib/active_record/relation/query_methods.rb +261 -0
- data/lib/active_record/relation/spawn_methods.rb +112 -0
- data/lib/active_record/schema.rb +59 -0
- data/lib/active_record/schema_dumper.rb +195 -0
- data/lib/active_record/serialization.rb +60 -0
- data/lib/active_record/serializers/xml_serializer.rb +244 -0
- data/lib/active_record/session_store.rb +340 -0
- data/lib/active_record/test_case.rb +67 -0
- data/lib/active_record/timestamp.rb +88 -0
- data/lib/active_record/transactions.rb +356 -0
- data/lib/active_record/validations.rb +84 -0
- data/lib/active_record/validations/associated.rb +48 -0
- data/lib/active_record/validations/uniqueness.rb +185 -0
- data/lib/active_record/version.rb +9 -0
- data/lib/rails/generators/active_record.rb +27 -0
- data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
- data/lib/rails/generators/active_record/migration/templates/migration.rb +17 -0
- data/lib/rails/generators/active_record/model/model_generator.rb +38 -0
- data/lib/rails/generators/active_record/model/templates/migration.rb +16 -0
- data/lib/rails/generators/active_record/model/templates/model.rb +5 -0
- data/lib/rails/generators/active_record/model/templates/module.rb +5 -0
- data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
- data/lib/rails/generators/active_record/observer/templates/observer.rb +2 -0
- data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +24 -0
- data/lib/rails/generators/active_record/session_migration/templates/migration.rb +16 -0
- metadata +224 -0
@@ -0,0 +1,288 @@
|
|
1
|
+
require 'active_support/core_ext/array/wrap'
|
2
|
+
|
3
|
+
module ActiveRecord
|
4
|
+
# = Active Record Callbacks
|
5
|
+
#
|
6
|
+
# Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
|
7
|
+
# before or after an alteration of the object state. This can be used to make sure that associated and
|
8
|
+
# dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
|
9
|
+
# before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
|
10
|
+
# the <tt>Base#save</tt> call for a new record:
|
11
|
+
#
|
12
|
+
# * (-) <tt>save</tt>
|
13
|
+
# * (-) <tt>valid</tt>
|
14
|
+
# * (1) <tt>before_validation</tt>
|
15
|
+
# * (-) <tt>validate</tt>
|
16
|
+
# * (2) <tt>after_validation</tt>
|
17
|
+
# * (3) <tt>before_save</tt>
|
18
|
+
# * (4) <tt>before_create</tt>
|
19
|
+
# * (-) <tt>create</tt>
|
20
|
+
# * (5) <tt>after_create</tt>
|
21
|
+
# * (6) <tt>after_save</tt>
|
22
|
+
# * (7) <tt>after_commit</tt>
|
23
|
+
#
|
24
|
+
# Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
|
25
|
+
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
|
26
|
+
# <tt>after_rollback</tt>.
|
27
|
+
#
|
28
|
+
# That's a total of ten callbacks, which gives you immense power to react and prepare for each state in the
|
29
|
+
# Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
|
30
|
+
# except that each <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
|
31
|
+
#
|
32
|
+
# Examples:
|
33
|
+
# class CreditCard < ActiveRecord::Base
|
34
|
+
# # Strip everything but digits, so the user can specify "555 234 34" or
|
35
|
+
# # "5552-3434" or both will mean "55523434"
|
36
|
+
# before_validation(:on => :create) do
|
37
|
+
# self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
|
38
|
+
# end
|
39
|
+
# end
|
40
|
+
#
|
41
|
+
# class Subscription < ActiveRecord::Base
|
42
|
+
# before_create :record_signup
|
43
|
+
#
|
44
|
+
# private
|
45
|
+
# def record_signup
|
46
|
+
# self.signed_up_on = Date.today
|
47
|
+
# end
|
48
|
+
# end
|
49
|
+
#
|
50
|
+
# class Firm < ActiveRecord::Base
|
51
|
+
# # Destroys the associated clients and people when the firm is destroyed
|
52
|
+
# before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
|
53
|
+
# before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
|
54
|
+
# end
|
55
|
+
#
|
56
|
+
# == Inheritable callback queues
|
57
|
+
#
|
58
|
+
# Besides the overwritable callback methods, it's also possible to register callbacks through the
|
59
|
+
# use of the callback macros. Their main advantage is that the macros add behavior into a callback
|
60
|
+
# queue that is kept intact down through an inheritance hierarchy.
|
61
|
+
#
|
62
|
+
# class Topic < ActiveRecord::Base
|
63
|
+
# before_destroy :destroy_author
|
64
|
+
# end
|
65
|
+
#
|
66
|
+
# class Reply < Topic
|
67
|
+
# before_destroy :destroy_readers
|
68
|
+
# end
|
69
|
+
#
|
70
|
+
# Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
|
71
|
+
# run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
|
72
|
+
# where the +before_destroy+ methis is overriden:
|
73
|
+
#
|
74
|
+
# class Topic < ActiveRecord::Base
|
75
|
+
# def before_destroy() destroy_author end
|
76
|
+
# end
|
77
|
+
#
|
78
|
+
# class Reply < Topic
|
79
|
+
# def before_destroy() destroy_readers end
|
80
|
+
# end
|
81
|
+
#
|
82
|
+
# In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
|
83
|
+
# So, use the callback macros when you want to ensure that a certain callback is called for the entire
|
84
|
+
# hierarchy, and use the regular overwriteable methods when you want to leave it up to each descendant
|
85
|
+
# to decide whether they want to call +super+ and trigger the inherited callbacks.
|
86
|
+
#
|
87
|
+
# *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
|
88
|
+
# callbacks before specifying the associations. Otherwise, you might trigger the loading of a
|
89
|
+
# child before the parent has registered the callbacks and they won't be inherited.
|
90
|
+
#
|
91
|
+
# == Types of callbacks
|
92
|
+
#
|
93
|
+
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
|
94
|
+
# inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
|
95
|
+
# are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
|
96
|
+
# creating mix-ins), and inline eval methods are deprecated.
|
97
|
+
#
|
98
|
+
# The method reference callbacks work by specifying a protected or private method available in the object, like this:
|
99
|
+
#
|
100
|
+
# class Topic < ActiveRecord::Base
|
101
|
+
# before_destroy :delete_parents
|
102
|
+
#
|
103
|
+
# private
|
104
|
+
# def delete_parents
|
105
|
+
# self.class.delete_all "parent_id = #{id}"
|
106
|
+
# end
|
107
|
+
# end
|
108
|
+
#
|
109
|
+
# The callback objects have methods named after the callback called with the record as the only parameter, such as:
|
110
|
+
#
|
111
|
+
# class BankAccount < ActiveRecord::Base
|
112
|
+
# before_save EncryptionWrapper.new
|
113
|
+
# after_save EncryptionWrapper.new
|
114
|
+
# after_initialize EncryptionWrapper.new
|
115
|
+
# end
|
116
|
+
#
|
117
|
+
# class EncryptionWrapper
|
118
|
+
# def before_save(record)
|
119
|
+
# record.credit_card_number = encrypt(record.credit_card_number)
|
120
|
+
# end
|
121
|
+
#
|
122
|
+
# def after_save(record)
|
123
|
+
# record.credit_card_number = decrypt(record.credit_card_number)
|
124
|
+
# end
|
125
|
+
#
|
126
|
+
# alias_method :after_find, :after_save
|
127
|
+
#
|
128
|
+
# private
|
129
|
+
# def encrypt(value)
|
130
|
+
# # Secrecy is committed
|
131
|
+
# end
|
132
|
+
#
|
133
|
+
# def decrypt(value)
|
134
|
+
# # Secrecy is unveiled
|
135
|
+
# end
|
136
|
+
# end
|
137
|
+
#
|
138
|
+
# So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
|
139
|
+
# a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
|
140
|
+
# initialization data such as the name of the attribute to work with:
|
141
|
+
#
|
142
|
+
# class BankAccount < ActiveRecord::Base
|
143
|
+
# before_save EncryptionWrapper.new("credit_card_number")
|
144
|
+
# after_save EncryptionWrapper.new("credit_card_number")
|
145
|
+
# after_initialize EncryptionWrapper.new("credit_card_number")
|
146
|
+
# end
|
147
|
+
#
|
148
|
+
# class EncryptionWrapper
|
149
|
+
# def initialize(attribute)
|
150
|
+
# @attribute = attribute
|
151
|
+
# end
|
152
|
+
#
|
153
|
+
# def before_save(record)
|
154
|
+
# record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
|
155
|
+
# end
|
156
|
+
#
|
157
|
+
# def after_save(record)
|
158
|
+
# record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
|
159
|
+
# end
|
160
|
+
#
|
161
|
+
# alias_method :after_find, :after_save
|
162
|
+
#
|
163
|
+
# private
|
164
|
+
# def encrypt(value)
|
165
|
+
# # Secrecy is committed
|
166
|
+
# end
|
167
|
+
#
|
168
|
+
# def decrypt(value)
|
169
|
+
# # Secrecy is unveiled
|
170
|
+
# end
|
171
|
+
# end
|
172
|
+
#
|
173
|
+
# The callback macros usually accept a symbol for the method they're supposed to run, but you can also
|
174
|
+
# pass a "method string", which will then be evaluated within the binding of the callback. Example:
|
175
|
+
#
|
176
|
+
# class Topic < ActiveRecord::Base
|
177
|
+
# before_destroy 'self.class.delete_all "parent_id = #{id}"'
|
178
|
+
# end
|
179
|
+
#
|
180
|
+
# Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
|
181
|
+
# is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
|
182
|
+
#
|
183
|
+
# class Topic < ActiveRecord::Base
|
184
|
+
# before_destroy 'self.class.delete_all "parent_id = #{id}"',
|
185
|
+
# 'puts "Evaluated after parents are destroyed"'
|
186
|
+
# end
|
187
|
+
#
|
188
|
+
# == The +after_find+ and +after_initialize+ exceptions
|
189
|
+
#
|
190
|
+
# Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder,
|
191
|
+
# such as <tt>Base.find(:all)</tt>, we've had to implement a simple performance constraint (50% more speed
|
192
|
+
# on a simple test case). Unlike all the other callbacks, +after_find+ and +after_initialize+ will only be
|
193
|
+
# run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the
|
194
|
+
# callback types will be called.
|
195
|
+
#
|
196
|
+
# == <tt>before_validation*</tt> returning statements
|
197
|
+
#
|
198
|
+
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
|
199
|
+
# aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
|
200
|
+
# ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
|
201
|
+
#
|
202
|
+
# == Canceling callbacks
|
203
|
+
#
|
204
|
+
# If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
|
205
|
+
# cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
|
206
|
+
# Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
|
207
|
+
# methods on the model, which are called last.
|
208
|
+
#
|
209
|
+
# == Transactions
|
210
|
+
#
|
211
|
+
# The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
|
212
|
+
# within a transaction. That includes <tt>after_*</tt> hooks. If everything
|
213
|
+
# goes fine a COMMIT is executed once the chain has been completed.
|
214
|
+
#
|
215
|
+
# If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
|
216
|
+
# can also trigger a ROLLBACK raising an exception in any of the callbacks,
|
217
|
+
# including <tt>after_*</tt> hooks. Note, however, that in that case the client
|
218
|
+
# needs to be aware of it because an ordinary +save+ will raise such exception
|
219
|
+
# instead of quietly returning +false+.
|
220
|
+
#
|
221
|
+
# == Debugging callbacks
|
222
|
+
#
|
223
|
+
# To list the methods and procs registered with a particular callback, append <tt>_callback_chain</tt> to
|
224
|
+
# the callback name that you wish to list and send that to your class from the Rails console:
|
225
|
+
#
|
226
|
+
# >> Topic.after_save_callback_chain
|
227
|
+
# => [#<ActiveSupport::Callbacks::Callback:0x3f6a448
|
228
|
+
# @method=#<Proc:0x03f9a42c@/Users/foo/bar/app/models/topic.rb:43>, kind:after_save, identifiernil,
|
229
|
+
# options{}]
|
230
|
+
#
|
231
|
+
module Callbacks
|
232
|
+
extend ActiveSupport::Concern
|
233
|
+
|
234
|
+
CALLBACKS = [
|
235
|
+
:after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
|
236
|
+
:before_save, :around_save, :after_save, :before_create, :around_create,
|
237
|
+
:after_create, :before_update, :around_update, :after_update,
|
238
|
+
:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
|
239
|
+
]
|
240
|
+
|
241
|
+
included do
|
242
|
+
extend ActiveModel::Callbacks
|
243
|
+
include ActiveModel::Validations::Callbacks
|
244
|
+
|
245
|
+
define_model_callbacks :initialize, :find, :touch, :only => :after
|
246
|
+
define_model_callbacks :save, :create, :update, :destroy
|
247
|
+
end
|
248
|
+
|
249
|
+
module ClassMethods
|
250
|
+
def method_added(meth)
|
251
|
+
super
|
252
|
+
if CALLBACKS.include?(meth.to_sym)
|
253
|
+
ActiveSupport::Deprecation.warn("Base##{meth} has been deprecated, please use Base.#{meth} :method instead", caller[0,1])
|
254
|
+
send(meth.to_sym, meth.to_sym)
|
255
|
+
end
|
256
|
+
end
|
257
|
+
end
|
258
|
+
|
259
|
+
def destroy #:nodoc:
|
260
|
+
_run_destroy_callbacks { super }
|
261
|
+
end
|
262
|
+
|
263
|
+
def touch(*) #:nodoc:
|
264
|
+
_run_touch_callbacks { super }
|
265
|
+
end
|
266
|
+
|
267
|
+
def deprecated_callback_method(symbol) #:nodoc:
|
268
|
+
if respond_to?(symbol, true)
|
269
|
+
ActiveSupport::Deprecation.warn("Overwriting #{symbol} in your models has been deprecated, please use Base##{symbol} :method_name instead")
|
270
|
+
send(symbol)
|
271
|
+
end
|
272
|
+
end
|
273
|
+
|
274
|
+
private
|
275
|
+
|
276
|
+
def create_or_update #:nodoc:
|
277
|
+
_run_save_callbacks { super }
|
278
|
+
end
|
279
|
+
|
280
|
+
def create #:nodoc:
|
281
|
+
_run_create_callbacks { super }
|
282
|
+
end
|
283
|
+
|
284
|
+
def update(*) #:nodoc:
|
285
|
+
_run_update_callbacks { super }
|
286
|
+
end
|
287
|
+
end
|
288
|
+
end
|
@@ -0,0 +1,365 @@
|
|
1
|
+
require 'monitor'
|
2
|
+
require 'set'
|
3
|
+
require 'active_support/core_ext/module/synchronization'
|
4
|
+
|
5
|
+
module ActiveRecord
|
6
|
+
# Raised when a connection could not be obtained within the connection
|
7
|
+
# acquisition timeout period.
|
8
|
+
class ConnectionTimeoutError < ConnectionNotEstablished
|
9
|
+
end
|
10
|
+
|
11
|
+
module ConnectionAdapters
|
12
|
+
# Connection pool base class for managing Active Record database
|
13
|
+
# connections.
|
14
|
+
#
|
15
|
+
# == Introduction
|
16
|
+
#
|
17
|
+
# A connection pool synchronizes thread access to a limited number of
|
18
|
+
# database connections. The basic idea is that each thread checks out a
|
19
|
+
# database connection from the pool, uses that connection, and checks the
|
20
|
+
# connection back in. ConnectionPool is completely thread-safe, and will
|
21
|
+
# ensure that a connection cannot be used by two threads at the same time,
|
22
|
+
# as long as ConnectionPool's contract is correctly followed. It will also
|
23
|
+
# handle cases in which there are more threads than connections: if all
|
24
|
+
# connections have been checked out, and a thread tries to checkout a
|
25
|
+
# connection anyway, then ConnectionPool will wait until some other thread
|
26
|
+
# has checked in a connection.
|
27
|
+
#
|
28
|
+
# == Obtaining (checking out) a connection
|
29
|
+
#
|
30
|
+
# Connections can be obtained and used from a connection pool in several
|
31
|
+
# ways:
|
32
|
+
#
|
33
|
+
# 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
|
34
|
+
# earlier (pre-connection-pooling). Eventually, when you're done with
|
35
|
+
# the connection(s) and wish it to be returned to the pool, you call
|
36
|
+
# ActiveRecord::Base.clear_active_connections!. This will be the
|
37
|
+
# default behavior for Active Record when used in conjunction with
|
38
|
+
# Action Pack's request handling cycle.
|
39
|
+
# 2. Manually check out a connection from the pool with
|
40
|
+
# ActiveRecord::Base.connection_pool.checkout. You are responsible for
|
41
|
+
# returning this connection to the pool when finished by calling
|
42
|
+
# ActiveRecord::Base.connection_pool.checkin(connection).
|
43
|
+
# 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
|
44
|
+
# obtains a connection, yields it as the sole argument to the block,
|
45
|
+
# and returns it to the pool after the block completes.
|
46
|
+
#
|
47
|
+
# Connections in the pool are actually AbstractAdapter objects (or objects
|
48
|
+
# compatible with AbstractAdapter's interface).
|
49
|
+
#
|
50
|
+
# == Options
|
51
|
+
#
|
52
|
+
# There are two connection-pooling-related options that you can add to
|
53
|
+
# your database connection configuration:
|
54
|
+
#
|
55
|
+
# * +pool+: number indicating size of connection pool (default 5)
|
56
|
+
# * +wait_timeout+: number of seconds to block and wait for a connection
|
57
|
+
# before giving up and raising a timeout error (default 5 seconds).
|
58
|
+
class ConnectionPool
|
59
|
+
attr_reader :spec, :connections
|
60
|
+
|
61
|
+
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
|
62
|
+
# object which describes database connection information (e.g. adapter,
|
63
|
+
# host name, username, password, etc), as well as the maximum size for
|
64
|
+
# this ConnectionPool.
|
65
|
+
#
|
66
|
+
# The default ConnectionPool maximum size is 5.
|
67
|
+
def initialize(spec)
|
68
|
+
@spec = spec
|
69
|
+
|
70
|
+
# The cache of reserved connections mapped to threads
|
71
|
+
@reserved_connections = {}
|
72
|
+
|
73
|
+
# The mutex used to synchronize pool access
|
74
|
+
@connection_mutex = Monitor.new
|
75
|
+
@queue = @connection_mutex.new_cond
|
76
|
+
|
77
|
+
# default 5 second timeout unless on ruby 1.9
|
78
|
+
@timeout =
|
79
|
+
if RUBY_VERSION < '1.9'
|
80
|
+
spec.config[:wait_timeout] || 5
|
81
|
+
end
|
82
|
+
|
83
|
+
# default max pool size to 5
|
84
|
+
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
|
85
|
+
|
86
|
+
@connections = []
|
87
|
+
@checked_out = []
|
88
|
+
end
|
89
|
+
|
90
|
+
# Retrieve the connection associated with the current thread, or call
|
91
|
+
# #checkout to obtain one if necessary.
|
92
|
+
#
|
93
|
+
# #connection can be called any number of times; the connection is
|
94
|
+
# held in a hash keyed by the thread id.
|
95
|
+
def connection
|
96
|
+
@reserved_connections[current_connection_id] ||= checkout
|
97
|
+
end
|
98
|
+
|
99
|
+
# Signal that the thread is finished with the current connection.
|
100
|
+
# #release_connection releases the connection-thread association
|
101
|
+
# and returns the connection to the pool.
|
102
|
+
def release_connection(with_id = current_connection_id)
|
103
|
+
conn = @reserved_connections.delete(with_id)
|
104
|
+
checkin conn if conn
|
105
|
+
end
|
106
|
+
|
107
|
+
# If a connection already exists yield it to the block. If no connection
|
108
|
+
# exists checkout a connection, yield it to the block, and checkin the
|
109
|
+
# connection when finished.
|
110
|
+
def with_connection
|
111
|
+
connection_id = current_connection_id
|
112
|
+
fresh_connection = true unless @reserved_connections[connection_id]
|
113
|
+
yield connection
|
114
|
+
ensure
|
115
|
+
release_connection(connection_id) if fresh_connection
|
116
|
+
end
|
117
|
+
|
118
|
+
# Returns true if a connection has already been opened.
|
119
|
+
def connected?
|
120
|
+
!@connections.empty?
|
121
|
+
end
|
122
|
+
|
123
|
+
# Disconnects all connections in the pool, and clears the pool.
|
124
|
+
def disconnect!
|
125
|
+
@reserved_connections.each do |name,conn|
|
126
|
+
checkin conn
|
127
|
+
end
|
128
|
+
@reserved_connections = {}
|
129
|
+
@connections.each do |conn|
|
130
|
+
conn.disconnect!
|
131
|
+
end
|
132
|
+
@connections = []
|
133
|
+
end
|
134
|
+
|
135
|
+
# Clears the cache which maps classes
|
136
|
+
def clear_reloadable_connections!
|
137
|
+
@reserved_connections.each do |name, conn|
|
138
|
+
checkin conn
|
139
|
+
end
|
140
|
+
@reserved_connections = {}
|
141
|
+
@connections.each do |conn|
|
142
|
+
conn.disconnect! if conn.requires_reloading?
|
143
|
+
end
|
144
|
+
@connections.delete_if do |conn|
|
145
|
+
conn.requires_reloading?
|
146
|
+
end
|
147
|
+
end
|
148
|
+
|
149
|
+
# Verify active connections and remove and disconnect connections
|
150
|
+
# associated with stale threads.
|
151
|
+
def verify_active_connections! #:nodoc:
|
152
|
+
clear_stale_cached_connections!
|
153
|
+
@connections.each do |connection|
|
154
|
+
connection.verify!
|
155
|
+
end
|
156
|
+
end
|
157
|
+
|
158
|
+
# Return any checked-out connections back to the pool by threads that
|
159
|
+
# are no longer alive.
|
160
|
+
def clear_stale_cached_connections!
|
161
|
+
keys = @reserved_connections.keys - Thread.list.find_all { |t|
|
162
|
+
t.alive?
|
163
|
+
}.map { |thread| thread.object_id }
|
164
|
+
|
165
|
+
keys.each do |key|
|
166
|
+
checkin @reserved_connections[key]
|
167
|
+
@reserved_connections.delete(key)
|
168
|
+
end
|
169
|
+
end
|
170
|
+
|
171
|
+
# Check-out a database connection from the pool, indicating that you want
|
172
|
+
# to use it. You should call #checkin when you no longer need this.
|
173
|
+
#
|
174
|
+
# This is done by either returning an existing connection, or by creating
|
175
|
+
# a new connection. If the maximum number of connections for this pool has
|
176
|
+
# already been reached, but the pool is empty (i.e. they're all being used),
|
177
|
+
# then this method will wait until a thread has checked in a connection.
|
178
|
+
# The wait time is bounded however: if no connection can be checked out
|
179
|
+
# within the timeout specified for this pool, then a ConnectionTimeoutError
|
180
|
+
# exception will be raised.
|
181
|
+
#
|
182
|
+
# Returns: an AbstractAdapter object.
|
183
|
+
#
|
184
|
+
# Raises:
|
185
|
+
# - ConnectionTimeoutError: no connection can be obtained from the pool
|
186
|
+
# within the timeout period.
|
187
|
+
def checkout
|
188
|
+
# Checkout an available connection
|
189
|
+
@connection_mutex.synchronize do
|
190
|
+
loop do
|
191
|
+
conn = if @checked_out.size < @connections.size
|
192
|
+
checkout_existing_connection
|
193
|
+
elsif @connections.size < @size
|
194
|
+
checkout_new_connection
|
195
|
+
end
|
196
|
+
return conn if conn
|
197
|
+
# No connections available; wait for one
|
198
|
+
if @queue.wait(@timeout)
|
199
|
+
next
|
200
|
+
else
|
201
|
+
# try looting dead threads
|
202
|
+
clear_stale_cached_connections!
|
203
|
+
if @size == @checked_out.size
|
204
|
+
raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it."
|
205
|
+
end
|
206
|
+
end
|
207
|
+
end
|
208
|
+
end
|
209
|
+
end
|
210
|
+
|
211
|
+
# Check-in a database connection back into the pool, indicating that you
|
212
|
+
# no longer need this connection.
|
213
|
+
#
|
214
|
+
# +conn+: an AbstractAdapter object, which was obtained by earlier by
|
215
|
+
# calling +checkout+ on this pool.
|
216
|
+
def checkin(conn)
|
217
|
+
@connection_mutex.synchronize do
|
218
|
+
conn.send(:_run_checkin_callbacks) do
|
219
|
+
@checked_out.delete conn
|
220
|
+
@queue.signal
|
221
|
+
end
|
222
|
+
end
|
223
|
+
end
|
224
|
+
|
225
|
+
synchronize :clear_reloadable_connections!, :verify_active_connections!,
|
226
|
+
:connected?, :disconnect!, :with => :@connection_mutex
|
227
|
+
|
228
|
+
private
|
229
|
+
def new_connection
|
230
|
+
ActiveRecord::Base.send(spec.adapter_method, spec.config)
|
231
|
+
end
|
232
|
+
|
233
|
+
def current_connection_id #:nodoc:
|
234
|
+
Thread.current.object_id
|
235
|
+
end
|
236
|
+
|
237
|
+
def checkout_new_connection
|
238
|
+
c = new_connection
|
239
|
+
@connections << c
|
240
|
+
checkout_and_verify(c)
|
241
|
+
end
|
242
|
+
|
243
|
+
def checkout_existing_connection
|
244
|
+
c = (@connections - @checked_out).first
|
245
|
+
checkout_and_verify(c)
|
246
|
+
end
|
247
|
+
|
248
|
+
def checkout_and_verify(c)
|
249
|
+
c.run_callbacks :checkout do
|
250
|
+
c.verify!
|
251
|
+
@checked_out << c
|
252
|
+
end
|
253
|
+
c
|
254
|
+
end
|
255
|
+
end
|
256
|
+
|
257
|
+
# ConnectionHandler is a collection of ConnectionPool objects. It is used
|
258
|
+
# for keeping separate connection pools for Active Record models that connect
|
259
|
+
# to different databases.
|
260
|
+
#
|
261
|
+
# For example, suppose that you have 5 models, with the following hierarchy:
|
262
|
+
#
|
263
|
+
# |
|
264
|
+
# +-- Book
|
265
|
+
# | |
|
266
|
+
# | +-- ScaryBook
|
267
|
+
# | +-- GoodBook
|
268
|
+
# +-- Author
|
269
|
+
# +-- BankAccount
|
270
|
+
#
|
271
|
+
# Suppose that Book is to connect to a separate database (i.e. one other
|
272
|
+
# than the default database). Then Book, ScaryBook and GoodBook will all use
|
273
|
+
# the same connection pool. Likewise, Author and BankAccount will use the
|
274
|
+
# same connection pool. However, the connection pool used by Author/BankAccount
|
275
|
+
# is not the same as the one used by Book/ScaryBook/GoodBook.
|
276
|
+
#
|
277
|
+
# Normally there is only a single ConnectionHandler instance, accessible via
|
278
|
+
# ActiveRecord::Base.connection_handler. Active Record models use this to
|
279
|
+
# determine that connection pool that they should use.
|
280
|
+
class ConnectionHandler
|
281
|
+
attr_reader :connection_pools
|
282
|
+
|
283
|
+
def initialize(pools = {})
|
284
|
+
@connection_pools = pools
|
285
|
+
end
|
286
|
+
|
287
|
+
def establish_connection(name, spec)
|
288
|
+
@connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec)
|
289
|
+
end
|
290
|
+
|
291
|
+
# Returns any connections in use by the current thread back to the pool,
|
292
|
+
# and also returns connections to the pool cached by threads that are no
|
293
|
+
# longer alive.
|
294
|
+
def clear_active_connections!
|
295
|
+
@connection_pools.each_value {|pool| pool.release_connection }
|
296
|
+
end
|
297
|
+
|
298
|
+
# Clears the cache which maps classes
|
299
|
+
def clear_reloadable_connections!
|
300
|
+
@connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
|
301
|
+
end
|
302
|
+
|
303
|
+
def clear_all_connections!
|
304
|
+
@connection_pools.each_value {|pool| pool.disconnect! }
|
305
|
+
end
|
306
|
+
|
307
|
+
# Verify active connections.
|
308
|
+
def verify_active_connections! #:nodoc:
|
309
|
+
@connection_pools.each_value {|pool| pool.verify_active_connections! }
|
310
|
+
end
|
311
|
+
|
312
|
+
# Locate the connection of the nearest super class. This can be an
|
313
|
+
# active or defined connection: if it is the latter, it will be
|
314
|
+
# opened and set as the active connection for the class it was defined
|
315
|
+
# for (not necessarily the current class).
|
316
|
+
def retrieve_connection(klass) #:nodoc:
|
317
|
+
pool = retrieve_connection_pool(klass)
|
318
|
+
(pool && pool.connection) or raise ConnectionNotEstablished
|
319
|
+
end
|
320
|
+
|
321
|
+
# Returns true if a connection that's accessible to this class has
|
322
|
+
# already been opened.
|
323
|
+
def connected?(klass)
|
324
|
+
conn = retrieve_connection_pool(klass)
|
325
|
+
conn && conn.connected?
|
326
|
+
end
|
327
|
+
|
328
|
+
# Remove the connection for this class. This will close the active
|
329
|
+
# connection and the defined connection (if they exist). The result
|
330
|
+
# can be used as an argument for establish_connection, for easily
|
331
|
+
# re-establishing the connection.
|
332
|
+
def remove_connection(klass)
|
333
|
+
pool = @connection_pools[klass.name]
|
334
|
+
return nil unless pool
|
335
|
+
|
336
|
+
@connection_pools.delete_if { |key, value| value == pool }
|
337
|
+
pool.disconnect!
|
338
|
+
pool.spec.config
|
339
|
+
end
|
340
|
+
|
341
|
+
def retrieve_connection_pool(klass)
|
342
|
+
pool = @connection_pools[klass.name]
|
343
|
+
return pool if pool
|
344
|
+
return nil if ActiveRecord::Base == klass
|
345
|
+
retrieve_connection_pool klass.superclass
|
346
|
+
end
|
347
|
+
end
|
348
|
+
|
349
|
+
class ConnectionManagement
|
350
|
+
def initialize(app)
|
351
|
+
@app = app
|
352
|
+
end
|
353
|
+
|
354
|
+
def call(env)
|
355
|
+
@app.call(env)
|
356
|
+
ensure
|
357
|
+
# Don't return connection (and perform implicit rollback) if
|
358
|
+
# this request is a part of integration test
|
359
|
+
unless env.key?("rack.test")
|
360
|
+
ActiveRecord::Base.clear_active_connections!
|
361
|
+
end
|
362
|
+
end
|
363
|
+
end
|
364
|
+
end
|
365
|
+
end
|