Skip to content
Newer
Older
100644 443 lines (383 sloc) 14.7 KB
d869298 @raggi Don't depend on rubygems loading thread (for Mutex)
raggi authored
1 require 'thread'
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
2 require 'monitor'
50cd4bd @nicksieger Introduce synchronization around connection pool access
nicksieger authored
3 require 'set'
e8550ee @jeremy Cherry-pick core extensions
jeremy authored
4 require 'active_support/core_ext/module/synchronization'
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
5 require 'active_support/core_ext/module/deprecation'
50cd4bd @nicksieger Introduce synchronization around connection pool access
nicksieger authored
6
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
7 module ActiveRecord
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
8 # Raised when a connection could not be obtained within the connection
9 # acquisition timeout period.
10 class ConnectionTimeoutError < ConnectionNotEstablished
11 end
12
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
13 module ConnectionAdapters
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
14 # Connection pool base class for managing Active Record database
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
15 # connections.
16 #
a293278 @lifo Merge docrails
lifo authored
17 # == Introduction
18 #
19 # A connection pool synchronizes thread access to a limited number of
20 # database connections. The basic idea is that each thread checks out a
21 # database connection from the pool, uses that connection, and checks the
22 # connection back in. ConnectionPool is completely thread-safe, and will
23 # ensure that a connection cannot be used by two threads at the same time,
24 # as long as ConnectionPool's contract is correctly followed. It will also
25 # handle cases in which there are more threads than connections: if all
26 # connections have been checked out, and a thread tries to checkout a
27 # connection anyway, then ConnectionPool will wait until some other thread
28 # has checked in a connection.
29 #
30 # == Obtaining (checking out) a connection
31 #
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
32 # Connections can be obtained and used from a connection pool in several
33 # ways:
34 #
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
35 # 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integrati…
nicksieger authored
36 # earlier (pre-connection-pooling). Eventually, when you're done with
37 # the connection(s) and wish it to be returned to the pool, you call
38 # ActiveRecord::Base.clear_active_connections!. This will be the
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
39 # default behavior for Active Record when used in conjunction with
40 # Action Pack's request handling cycle.
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
41 # 2. Manually check out a connection from the pool with
42 # ActiveRecord::Base.connection_pool.checkout. You are responsible for
43 # returning this connection to the pool when finished by calling
44 # ActiveRecord::Base.connection_pool.checkin(connection).
45 # 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
46 # obtains a connection, yields it as the sole argument to the block,
47 # and returns it to the pool after the block completes.
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
48 #
a293278 @lifo Merge docrails
lifo authored
49 # Connections in the pool are actually AbstractAdapter objects (or objects
50 # compatible with AbstractAdapter's interface).
51 #
52 # == Options
53 #
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
54 # There are two connection-pooling-related options that you can add to
55 # your database connection configuration:
56 #
57 # * +pool+: number indicating size of connection pool (default 5)
58 # * +wait_timeout+: number of seconds to block and wait for a connection
59 # before giving up and raising a timeout error (default 5 seconds).
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integrati…
nicksieger authored
60 class ConnectionPool
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
61 attr_accessor :automatic_reconnect
cccb998 @josevalim Expose connections available in the connection pool.
josevalim authored
62 attr_reader :spec, :connections
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
63
a293278 @lifo Merge docrails
lifo authored
64 # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
65 # object which describes database connection information (e.g. adapter,
66 # host name, username, password, etc), as well as the maximum size for
67 # this ConnectionPool.
68 #
69 # The default ConnectionPool maximum size is 5.
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
70 def initialize(spec)
71 @spec = spec
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
72
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
73 # The cache of reserved connections mapped to threads
74 @reserved_connections = {}
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
75
cab76ce @nicksieger Add synchronization to connection pool also
nicksieger authored
76 # The mutex used to synchronize pool access
77 @connection_mutex = Monitor.new
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
78 @queue = @connection_mutex.new_cond
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
79 @timeout = spec.config[:wait_timeout] || 5
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
80
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
81 # default max pool size to 5
82 @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
83
7db90aa @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
84 @connections = []
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
85 @automatic_reconnect = true
c94651f @tenderlove almost fisted
tenderlove authored
86 end
87
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
88 # Retrieve the connection associated with the current thread, or call
89 # #checkout to obtain one if necessary.
90 #
91 # #connection can be called any number of times; the connection is
92 # held in a hash keyed by the thread id.
93 def connection
072cd60 @tenderlove refactor if / else to ||=
tenderlove authored
94 @reserved_connections[current_connection_id] ||= checkout
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
95 end
96
4211866 @tenderlove adding active_connection? to the connection pool
tenderlove authored
97 # Check to see if there is an active connection in this connection
98 # pool.
99 def active_connection?
ce3d8d6 @tenderlove Start implementing @reserved_connections in terms of connection leases.
tenderlove authored
100 active_connections.any?
4211866 @tenderlove adding active_connection? to the connection pool
tenderlove authored
101 end
102
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
103 # Signal that the thread is finished with the current connection.
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integrati…
nicksieger authored
104 # #release_connection releases the connection-thread association
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
105 # and returns the connection to the pool.
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
106 def release_connection(with_id = current_connection_id)
107 conn = @reserved_connections.delete(with_id)
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
108 checkin conn if conn
109 end
110
0034b78 @smartinez87 Remove extra white spaces on ActiveRecord docs.
smartinez87 authored
111 # If a connection already exists yield it to the block. If no connection
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
112 # exists checkout a connection, yield it to the block, and checkin the
5501b99 @account-settings Ensure ActiveRecord::Base.connection_pool.with_connection creates a n…
account-settings authored
113 # connection when finished.
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
114 def with_connection
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
115 connection_id = current_connection_id
ce3d8d6 @tenderlove Start implementing @reserved_connections in terms of connection leases.
tenderlove authored
116 fresh_connection = true unless active_connection?
5501b99 @account-settings Ensure ActiveRecord::Base.connection_pool.with_connection creates a n…
account-settings authored
117 yield connection
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
118 ensure
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
119 release_connection(connection_id) if fresh_connection
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
120 end
121
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
122 # Returns true if a connection has already been opened.
123 def connected?
ce3d8d6 @tenderlove Start implementing @reserved_connections in terms of connection leases.
tenderlove authored
124 @connections.any?
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
125 end
126
a293278 @lifo Merge docrails
lifo authored
127 # Disconnects all connections in the pool, and clears the pool.
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
128 def disconnect!
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
129 @reserved_connections = {}
130 @connections.each do |conn|
beff819 @tenderlove just check in all connections
tenderlove authored
131 checkin conn
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
132 conn.disconnect!
133 end
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
134 @connections = []
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
135 end
136
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
137 # Clears the cache which maps classes.
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
138 def clear_reloadable_connections!
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
139 @reserved_connections = {}
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
140 @connections.each do |conn|
beff819 @tenderlove just check in all connections
tenderlove authored
141 checkin conn
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
142 conn.disconnect! if conn.requires_reloading?
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
143 end
62c4e4d @ebeigarts Fix connection reloading in development mode. [#4929 state:resolved]
ebeigarts authored
144 @connections.delete_if do |conn|
145 conn.requires_reloading?
146 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
147 end
148
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integrati…
nicksieger authored
149 # Verify active connections and remove and disconnect connections
150 # associated with stale threads.
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
151 def verify_active_connections! #:nodoc:
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
152 clear_stale_cached_connections!
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
153 @connections.each do |connection|
7ba2872 @nicksieger Deprecate verification_timeout and verify before reset
nicksieger authored
154 connection.verify!
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
155 end
156 end
157
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
158 def columns
159 with_connection do |c|
160 c.schema_cache.columns
161 end
162 end
163 deprecate :columns
164
165 def columns_hash
166 with_connection do |c|
167 c.schema_cache.columns_hash
168 end
169 end
170 deprecate :columns_hash
171
172 def primary_keys
173 with_connection do |c|
174 c.schema_cache.primary_keys
175 end
176 end
177 deprecate :primary_keys
178
179 def clear_cache!
180 with_connection do |c|
181 c.schema_cache.clear!
182 end
183 end
184 deprecate :clear_cache!
185
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
186 # Return any checked-out connections back to the pool by threads that
187 # are no longer alive.
188 def clear_stale_cached_connections!
42be67e @tenderlove unfactoring clear_stale_cached_connections!
tenderlove authored
189 keys = @reserved_connections.keys - Thread.list.find_all { |t|
190 t.alive?
191 }.map { |thread| thread.object_id }
192 keys.each do |key|
193 checkin @reserved_connections[key]
194 @reserved_connections.delete(key)
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
195 end
196 end
197
a293278 @lifo Merge docrails
lifo authored
198 # Check-out a database connection from the pool, indicating that you want
199 # to use it. You should call #checkin when you no longer need this.
200 #
201 # This is done by either returning an existing connection, or by creating
202 # a new connection. If the maximum number of connections for this pool has
203 # already been reached, but the pool is empty (i.e. they're all being used),
204 # then this method will wait until a thread has checked in a connection.
205 # The wait time is bounded however: if no connection can be checked out
206 # within the timeout specified for this pool, then a ConnectionTimeoutError
207 # exception will be raised.
208 #
209 # Returns: an AbstractAdapter object.
210 #
211 # Raises:
212 # - ConnectionTimeoutError: no connection can be obtained from the pool
213 # within the timeout period.
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
214 def checkout
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
215 # Checkout an available connection
216 @connection_mutex.synchronize do
21eb18a Fix race in ConnectionPool#checkout
Aliaksey Kandratsenka authored
217 loop do
b72b477 @tenderlove Use connection lease to determine "checked_out" connections
tenderlove authored
218 conn = @connections.find { |c| c.lease }
219
220 unless conn
221 if @connections.size < @size
222 conn = checkout_new_connection
223 conn.lease
224 end
225 end
226
227 if conn
228 checkout_and_verify conn
229 return conn
230 end
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
231
232 @queue.wait(@timeout)
233
5725e39 @tenderlove Rename `checked_out` to more descriptive `active_connections`
tenderlove authored
234 if(active_connections.size < @connections.size)
21eb18a Fix race in ConnectionPool#checkout
Aliaksey Kandratsenka authored
235 next
236 else
8343611 made ConnectionPool#checkout more robust by trying to loot dead threa…
Aliaksey Kandratsenka authored
237 clear_stale_cached_connections!
5725e39 @tenderlove Rename `checked_out` to more descriptive `active_connections`
tenderlove authored
238 if @size == active_connections.size
05f29ca @smartinez87 Remove extra white-space on some exception messages.
smartinez87 authored
239 raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it."
8343611 made ConnectionPool#checkout more robust by trying to loot dead threa…
Aliaksey Kandratsenka authored
240 end
21eb18a Fix race in ConnectionPool#checkout
Aliaksey Kandratsenka authored
241 end
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
242
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
243 end
244 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
245 end
246
a293278 @lifo Merge docrails
lifo authored
247 # Check-in a database connection back into the pool, indicating that you
248 # no longer need this connection.
249 #
250 # +conn+: an AbstractAdapter object, which was obtained by earlier by
251 # calling +checkout+ on this pool.
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
252 def checkin(conn)
253 @connection_mutex.synchronize do
57bc25c @jfirebaugh Use run_callbacks; the generated _run_<name>_callbacks method is not …
jfirebaugh authored
254 conn.run_callbacks :checkin do
b72b477 @tenderlove Use connection lease to determine "checked_out" connections
tenderlove authored
255 conn.expire
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
256 @queue.signal
257 end
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
258 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
259 end
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
260
113cc4e @nicksieger Remove some synchronization that's probably overkill, assuming one do…
nicksieger authored
261 synchronize :clear_reloadable_connections!, :verify_active_connections!,
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
262 :connected?, :disconnect!, :with => :@connection_mutex
263
264 private
7db90aa @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
265
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
266 def new_connection
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
267 ActiveRecord::Base.send(spec.adapter_method, spec.config)
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
268 end
269
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
270 def current_connection_id #:nodoc:
f41b58d @mjtko use thread locals and an instance variable within QueryCache#BodyProx…
mjtko authored
271 ActiveRecord::Base.connection_id ||= Thread.current.object_id
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
272 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
273
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
274 def checkout_new_connection
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
275 raise ConnectionNotEstablished unless @automatic_reconnect
276
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
277 c = new_connection
29d2040 @tenderlove AbstractAdapter#close can be called to add the connection back to the
tenderlove authored
278 c.pool = self
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
279 @connections << c
b72b477 @tenderlove Use connection lease to determine "checked_out" connections
tenderlove authored
280 c
a96b7d4 @nicksieger Add connection reset and verification upon each connection checkout
nicksieger authored
281 end
282
283 def checkout_and_verify(c)
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
284 c.run_callbacks :checkout do
285 c.verify!
286 end
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
287 c
288 end
b72b477 @tenderlove Use connection lease to determine "checked_out" connections
tenderlove authored
289
5725e39 @tenderlove Rename `checked_out` to more descriptive `active_connections`
tenderlove authored
290 def active_connections
b72b477 @tenderlove Use connection lease to determine "checked_out" connections
tenderlove authored
291 @connections.find_all { |c| c.in_use? }
292 end
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
293 end
294
a293278 @lifo Merge docrails
lifo authored
295 # ConnectionHandler is a collection of ConnectionPool objects. It is used
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
296 # for keeping separate connection pools for Active Record models that connect
a293278 @lifo Merge docrails
lifo authored
297 # to different databases.
298 #
299 # For example, suppose that you have 5 models, with the following hierarchy:
300 #
301 # |
302 # +-- Book
303 # | |
304 # | +-- ScaryBook
305 # | +-- GoodBook
306 # +-- Author
307 # +-- BankAccount
308 #
309 # Suppose that Book is to connect to a separate database (i.e. one other
310 # than the default database). Then Book, ScaryBook and GoodBook will all use
311 # the same connection pool. Likewise, Author and BankAccount will use the
312 # same connection pool. However, the connection pool used by Author/BankAccount
313 # is not the same as the one used by Book/ScaryBook/GoodBook.
314 #
315 # Normally there is only a single ConnectionHandler instance, accessible via
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
316 # ActiveRecord::Base.connection_handler. Active Record models use this to
a293278 @lifo Merge docrails
lifo authored
317 # determine that connection pool that they should use.
ca6d717 @nicksieger Deprecate allow_concurrency and make it have no effect
nicksieger authored
318 class ConnectionHandler
b952470 @tenderlove use an attr_reader for performance
tenderlove authored
319 attr_reader :connection_pools
320
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
321 def initialize(pools = {})
322 @connection_pools = pools
ffb218c @tenderlove pools are 1:1 with spec now rather than 1:1 with class
tenderlove authored
323 @class_to_pool = {}
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
324 end
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
325
326 def establish_connection(name, spec)
ffb218c @tenderlove pools are 1:1 with spec now rather than 1:1 with class
tenderlove authored
327 @connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec)
328 @class_to_pool[name] = @connection_pools[spec]
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
329 end
330
25f9497 @tenderlove adding active_connections? to the connection pool for finding open co…
tenderlove authored
331 # Returns true if there are any active connections among the connection
332 # pools that the ConnectionHandler is managing.
333 def active_connections?
334 connection_pools.values.any? { |pool| pool.active_connection? }
335 end
336
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
337 # Returns any connections in use by the current thread back to the pool,
338 # and also returns connections to the pool cached by threads that are no
339 # longer alive.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
340 def clear_active_connections!
529c271 @nicksieger Simplify dispatcher callbacks to eliminate unnecessary stale thread p…
nicksieger authored
341 @connection_pools.each_value {|pool| pool.release_connection }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
342 end
343
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
344 # Clears the cache which maps classes.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
345 def clear_reloadable_connections!
346 @connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
347 end
348
349 def clear_all_connections!
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
350 @connection_pools.each_value {|pool| pool.disconnect! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
351 end
352
353 # Verify active connections.
354 def verify_active_connections! #:nodoc:
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integrati…
nicksieger authored
355 @connection_pools.each_value {|pool| pool.verify_active_connections! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
356 end
357
358 # Locate the connection of the nearest super class. This can be an
359 # active or defined connection: if it is the latter, it will be
360 # opened and set as the active connection for the class it was defined
361 # for (not necessarily the current class).
362 def retrieve_connection(klass) #:nodoc:
363 pool = retrieve_connection_pool(klass)
364 (pool && pool.connection) or raise ConnectionNotEstablished
365 end
366
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
367 # Returns true if a connection that's accessible to this class has
368 # already been opened.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
369 def connected?(klass)
0832bc6 @lifo Make sure ActiveRecord::Base.connected? doesn't raise an exception fo…
lifo authored
370 conn = retrieve_connection_pool(klass)
a4458f5 @tenderlove removing useless ternary
tenderlove authored
371 conn && conn.connected?
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
372 end
373
374 # Remove the connection for this class. This will close the active
375 # connection and the defined connection (if they exist). The result
376 # can be used as an argument for establish_connection, for easily
377 # re-establishing the connection.
378 def remove_connection(klass)
ffb218c @tenderlove pools are 1:1 with spec now rather than 1:1 with class
tenderlove authored
379 pool = @class_to_pool.delete(klass.name)
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
380 return nil unless pool
381
ffb218c @tenderlove pools are 1:1 with spec now rather than 1:1 with class
tenderlove authored
382 @connection_pools.delete pool.spec
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
383 pool.automatic_reconnect = false
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
384 pool.disconnect!
385 pool.spec.config
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
386 end
387
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
388 def retrieve_connection_pool(klass)
ffb218c @tenderlove pools are 1:1 with spec now rather than 1:1 with class
tenderlove authored
389 pool = @class_to_pool[klass.name]
3007545 @nicksieger Minor tweak to retrieve_connection_pool -- recurse instead of loop
nicksieger authored
390 return pool if pool
391 return nil if ActiveRecord::Base == klass
392 retrieve_connection_pool klass.superclass
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
393 end
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
394 end
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
395
396 class ConnectionManagement
e524609 @tenderlove proxy body responses so we close database connections after body is f…
tenderlove authored
397 class Proxy # :nodoc:
398 attr_reader :body, :testing
399
400 def initialize(body, testing = false)
401 @body = body
402 @testing = testing
403 end
404
5044420 @stevehodgkiss Fix inconsistencies by being polite to the wrapped body. Needed for R…
stevehodgkiss authored
405 def method_missing(method_sym, *arguments, &block)
406 @body.send(method_sym, *arguments, &block)
407 end
408
409 def respond_to?(method_sym, include_private = false)
410 super || @body.respond_to?(method_sym)
411 end
412
e524609 @tenderlove proxy body responses so we close database connections after body is f…
tenderlove authored
413 def each(&block)
414 body.each(&block)
415 end
416
417 def close
418 body.close if body.respond_to?(:close)
419
420 # Don't return connection (and perform implicit rollback) if
421 # this request is a part of integration test
422 ActiveRecord::Base.clear_active_connections! unless testing
423 end
424 end
425
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
426 def initialize(app)
427 @app = app
428 end
429
430 def call(env)
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
431 testing = env.key?('rack.test')
432
e524609 @tenderlove proxy body responses so we close database connections after body is f…
tenderlove authored
433 status, headers, body = @app.call(env)
434
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
435 [status, headers, Proxy.new(body, testing)]
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if…
tenderlove authored
436 rescue
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
437 ActiveRecord::Base.clear_active_connections! unless testing
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if…
tenderlove authored
438 raise
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
439 end
440 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
441 end
21eb18a Fix race in ConnectionPool#checkout
Aliaksey Kandratsenka authored
442 end
Something went wrong with that request. Please try again.