Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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