Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 459 lines (398 sloc) 15.501 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
cceabe0 @tenderlove raise a pull full error when the connection pool is full and no conne…
tenderlove authored
12 # Raised when a connection pool is full and another connection is requested
13 class PoolFullError < ConnectionNotEstablished
14 def initialize size, timeout
15 super("Connection pool of size #{size} and timeout #{timeout}s is full")
16 end
17 end
18
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
19 module ConnectionAdapters
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
20 # Connection pool base class for managing Active Record database
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
21 # connections.
22 #
a293278 @lifo Merge docrails
lifo authored
23 # == Introduction
24 #
25 # A connection pool synchronizes thread access to a limited number of
26 # database connections. The basic idea is that each thread checks out a
27 # database connection from the pool, uses that connection, and checks the
28 # connection back in. ConnectionPool is completely thread-safe, and will
29 # ensure that a connection cannot be used by two threads at the same time,
30 # as long as ConnectionPool's contract is correctly followed. It will also
31 # handle cases in which there are more threads than connections: if all
32 # connections have been checked out, and a thread tries to checkout a
33 # connection anyway, then ConnectionPool will wait until some other thread
34 # has checked in a connection.
35 #
36 # == Obtaining (checking out) a connection
37 #
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
38 # Connections can be obtained and used from a connection pool in several
39 # ways:
40 #
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
41 # 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
42 # earlier (pre-connection-pooling). Eventually, when you're done with
43 # the connection(s) and wish it to be returned to the pool, you call
44 # 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
45 # default behavior for Active Record when used in conjunction with
46 # Action Pack's request handling cycle.
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
47 # 2. Manually check out a connection from the pool with
48 # ActiveRecord::Base.connection_pool.checkout. You are responsible for
49 # returning this connection to the pool when finished by calling
50 # ActiveRecord::Base.connection_pool.checkin(connection).
51 # 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
52 # obtains a connection, yields it as the sole argument to the block,
53 # and returns it to the pool after the block completes.
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
54 #
a293278 @lifo Merge docrails
lifo authored
55 # Connections in the pool are actually AbstractAdapter objects (or objects
56 # compatible with AbstractAdapter's interface).
57 #
58 # == Options
59 #
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
60 # There are two connection-pooling-related options that you can add to
61 # your database connection configuration:
62 #
63 # * +pool+: number indicating size of connection pool (default 5)
64 # * +wait_timeout+: number of seconds to block and wait for a connection
65 # 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
66 class ConnectionPool
41c24eb @tenderlove each connection pool has a reaper
tenderlove authored
67 # Every +frequency+ seconds, the reaper will call +reap+ on +pool+.
68 # A reaper instantiated with a nil frequency will never reap the
69 # connection pool.
641b43e @tenderlove updating the reaping frequency documentation
tenderlove authored
70 #
71 # Configure the frequency by setting "reaping_frequency" in your
72 # database yaml file.
cde7692 @tenderlove introduce a timer class for reaping connections
tenderlove authored
73 class Reaper
74 attr_reader :pool, :frequency
75
76 def initialize(pool, frequency)
77 @pool = pool
78 @frequency = frequency
79 end
80
59f2696 @tenderlove rename start to run and use Thread.pass rather than sleeping to sched…
tenderlove authored
81 def run
cde7692 @tenderlove introduce a timer class for reaping connections
tenderlove authored
82 return unless frequency
83 Thread.new(frequency, pool) { |t, p|
84 while true
85 sleep t
86 p.reap
87 end
88 }
89 end
90 end
91
c606fe2 @tenderlove push synchronization in to each method. Reduces method calls and makes
tenderlove authored
92 include MonitorMixin
93
17ff88c @tenderlove connections can be removed from the pool
tenderlove authored
94 attr_accessor :automatic_reconnect, :timeout
41c24eb @tenderlove each connection pool has a reaper
tenderlove authored
95 attr_reader :spec, :connections, :size, :reaper
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
96
a293278 @lifo Merge docrails
lifo authored
97 # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
98 # object which describes database connection information (e.g. adapter,
99 # host name, username, password, etc), as well as the maximum size for
100 # this ConnectionPool.
101 #
102 # The default ConnectionPool maximum size is 5.
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
103 def initialize(spec)
c606fe2 @tenderlove push synchronization in to each method. Reduces method calls and makes
tenderlove authored
104 super()
105
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
106 @spec = spec
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
107
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
108 # The cache of reserved connections mapped to threads
109 @reserved_connections = {}
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
110
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
111 @timeout = spec.config[:wait_timeout] || 5
41c24eb @tenderlove each connection pool has a reaper
tenderlove authored
112 @reaper = Reaper.new self, spec.config[:reaping_frequency]
59f2696 @tenderlove rename start to run and use Thread.pass rather than sleeping to sched…
tenderlove authored
113 @reaper.run
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
114
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
115 # default max pool size to 5
116 @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
117
7db90aa @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
118 @connections = []
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
119 @automatic_reconnect = true
c94651f @tenderlove almost fisted
tenderlove authored
120 end
121
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
122 # Retrieve the connection associated with the current thread, or call
123 # #checkout to obtain one if necessary.
124 #
125 # #connection can be called any number of times; the connection is
126 # held in a hash keyed by the thread id.
127 def connection
072cd60 @tenderlove refactor if / else to ||=
tenderlove authored
128 @reserved_connections[current_connection_id] ||= checkout
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
129 end
130
d523504 @tenderlove make active_connection? return true only if there is an open connecti…
tenderlove authored
131 # Is there an open connection that is being used for the current thread?
4211866 @tenderlove adding active_connection? to the connection pool
tenderlove authored
132 def active_connection?
d523504 @tenderlove make active_connection? return true only if there is an open connecti…
tenderlove authored
133 @reserved_connections.fetch(current_connection_id) {
134 return false
135 }.in_use?
4211866 @tenderlove adding active_connection? to the connection pool
tenderlove authored
136 end
137
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
138 # 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
139 # #release_connection releases the connection-thread association
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
140 # and returns the connection to the pool.
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
141 def release_connection(with_id = current_connection_id)
142 conn = @reserved_connections.delete(with_id)
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
143 checkin conn if conn
144 end
145
0034b78 @smartinez87 Remove extra white spaces on ActiveRecord docs.
smartinez87 authored
146 # 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
147 # 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
148 # connection when finished.
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
149 def with_connection
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
150 connection_id = current_connection_id
ce3d8d6 @tenderlove Start implementing @reserved_connections in terms of connection leases.
tenderlove authored
151 fresh_connection = true unless active_connection?
5501b99 @account-settings Ensure ActiveRecord::Base.connection_pool.with_connection creates a n…
account-settings authored
152 yield connection
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
153 ensure
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
154 release_connection(connection_id) if fresh_connection
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
155 end
156
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
157 # Returns true if a connection has already been opened.
158 def connected?
c606fe2 @tenderlove push synchronization in to each method. Reduces method calls and makes
tenderlove authored
159 synchronize { @connections.any? }
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
160 end
161
a293278 @lifo Merge docrails
lifo authored
162 # 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
163 def disconnect!
c606fe2 @tenderlove push synchronization in to each method. Reduces method calls and makes
tenderlove authored
164 synchronize do
165 @reserved_connections = {}
166 @connections.each do |conn|
167 checkin conn
168 conn.disconnect!
169 end
170 @connections = []
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
171 end
172 end
173
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
174 # Clears the cache which maps classes.
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
175 def clear_reloadable_connections!
c606fe2 @tenderlove push synchronization in to each method. Reduces method calls and makes
tenderlove authored
176 synchronize do
177 @reserved_connections = {}
178 @connections.each do |conn|
179 checkin conn
180 conn.disconnect! if conn.requires_reloading?
181 end
182 @connections.delete_if do |conn|
183 conn.requires_reloading?
184 end
62c4e4d @ebeigarts Fix connection reloading in development mode. [#4929 state:resolved]
ebeigarts authored
185 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
186 end
187
cceabe0 @tenderlove raise a pull full error when the connection pool is full and no conne…
tenderlove authored
188 def clear_stale_cached_connections! # :nodoc:
27ebb3d @jrochkind deprecated clear_stale_active_connections! can call #reap instead of …
jrochkind authored
189 reap
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
190 end
27ebb3d @jrochkind deprecated clear_stale_active_connections! can call #reap instead of …
jrochkind authored
191 deprecate :clear_stale_cached_connections! => "Please use #reap instead"
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
192
a293278 @lifo Merge docrails
lifo authored
193 # Check-out a database connection from the pool, indicating that you want
194 # to use it. You should call #checkin when you no longer need this.
195 #
cceabe0 @tenderlove raise a pull full error when the connection pool is full and no conne…
tenderlove authored
196 # This is done by either returning and leasing existing connection, or by
197 # creating a new connection and leasing it.
198 #
199 # If all connections are leased and the pool is at capacity (meaning the
200 # number of currently leased connections is greater than or equal to the
201 # size limit set), an ActiveRecord::PoolFullError exception will be raised.
a293278 @lifo Merge docrails
lifo authored
202 #
203 # Returns: an AbstractAdapter object.
204 #
205 # Raises:
cceabe0 @tenderlove raise a pull full error when the connection pool is full and no conne…
tenderlove authored
206 # - PoolFullError: no connection can be obtained from the pool.
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
207 def checkout
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
208 # Checkout an available connection
c606fe2 @tenderlove push synchronization in to each method. Reduces method calls and makes
tenderlove authored
209 synchronize do
cceabe0 @tenderlove raise a pull full error when the connection pool is full and no conne…
tenderlove authored
210 # Try to find a connection that hasn't been leased, and lease it
211 conn = connections.find { |c| c.lease }
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
212
5dc7257 @tenderlove refactor checking out the connection
tenderlove authored
213 # If all connections were leased, and we have room to expand,
214 # create a new connection and lease it.
cceabe0 @tenderlove raise a pull full error when the connection pool is full and no conne…
tenderlove authored
215 if !conn && connections.size < size
5dc7257 @tenderlove refactor checking out the connection
tenderlove authored
216 conn = checkout_new_connection
217 conn.lease
df9de6f @tenderlove infinite loop is no longer necessary
tenderlove authored
218 end
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
219
df9de6f @tenderlove infinite loop is no longer necessary
tenderlove authored
220 if conn
221 checkout_and_verify conn
222 else
cceabe0 @tenderlove raise a pull full error when the connection pool is full and no conne…
tenderlove authored
223 raise PoolFullError.new(size, timeout)
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
224 end
225 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
226 end
227
a293278 @lifo Merge docrails
lifo authored
228 # Check-in a database connection back into the pool, indicating that you
229 # no longer need this connection.
230 #
231 # +conn+: an AbstractAdapter object, which was obtained by earlier by
232 # calling +checkout+ on this pool.
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
233 def checkin(conn)
c606fe2 @tenderlove push synchronization in to each method. Reduces method calls and makes
tenderlove authored
234 synchronize do
57bc25c @jfirebaugh Use run_callbacks; the generated _run_<name>_callbacks method is not …
jfirebaugh authored
235 conn.run_callbacks :checkin do
b72b477 @tenderlove Use connection lease to determine "checked_out" connections
tenderlove authored
236 conn.expire
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
237 end
0210c44 @tenderlove make sure connections returned after close are marked as in_use
tenderlove authored
238
239 release conn
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
240 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
241 end
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
242
17ff88c @tenderlove connections can be removed from the pool
tenderlove authored
243 # Remove a connection from the connection pool. The connection will
244 # remain open and active but will no longer be managed by this pool.
245 def remove(conn)
246 synchronize do
247 @connections.delete conn
e060cf0 @tenderlove deal with removing connections associated with the current thread
tenderlove authored
248
249 # FIXME: we might want to store the key on the connection so that removing
250 # from the reserved hash will be a little easier.
0210c44 @tenderlove make sure connections returned after close are marked as in_use
tenderlove authored
251 release conn
17ff88c @tenderlove connections can be removed from the pool
tenderlove authored
252 end
253 end
254
86729eb @tenderlove connections can be reaped via the `reap` method
tenderlove authored
255 # Removes dead connections from the pool. A dead connection can occur
256 # if a programmer forgets to close a connection at the end of a thread
257 # or a thread dies unexpectedly.
258 def reap
259 synchronize do
260 stale = Time.now - @timeout
261 connections.dup.each do |conn|
b1ac881 @tenderlove connections are only removed if they are inactve
tenderlove authored
262 remove conn if conn.in_use? && stale > conn.last_use && !conn.active?
86729eb @tenderlove connections can be reaped via the `reap` method
tenderlove authored
263 end
264 end
265 end
266
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
267 private
7db90aa @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
268
0210c44 @tenderlove make sure connections returned after close are marked as in_use
tenderlove authored
269 def release(conn)
270 thread_id = nil
271
272 if @reserved_connections[current_connection_id] == conn
273 thread_id = current_connection_id
274 else
275 thread_id = @reserved_connections.keys.find { |k|
276 @reserved_connections[k] == conn
277 }
278 end
279
280 @reserved_connections.delete thread_id if thread_id
281 end
282
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
283 def new_connection
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
284 ActiveRecord::Base.send(spec.adapter_method, spec.config)
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
285 end
286
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
287 def current_connection_id #:nodoc:
f41b58d @mjtko use thread locals and an instance variable within QueryCache#BodyProx…
mjtko authored
288 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
289 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
290
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
291 def checkout_new_connection
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
292 raise ConnectionNotEstablished unless @automatic_reconnect
293
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
294 c = new_connection
29d2040 @tenderlove AbstractAdapter#close can be called to add the connection back to the
tenderlove authored
295 c.pool = self
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
296 @connections << c
b72b477 @tenderlove Use connection lease to determine "checked_out" connections
tenderlove authored
297 c
a96b7d4 @nicksieger Add connection reset and verification upon each connection checkout
nicksieger authored
298 end
299
300 def checkout_and_verify(c)
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
301 c.run_callbacks :checkout do
302 c.verify!
303 end
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
304 c
305 end
306 end
307
a293278 @lifo Merge docrails
lifo authored
308 # 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
309 # for keeping separate connection pools for Active Record models that connect
a293278 @lifo Merge docrails
lifo authored
310 # to different databases.
311 #
312 # For example, suppose that you have 5 models, with the following hierarchy:
313 #
314 # |
315 # +-- Book
316 # | |
317 # | +-- ScaryBook
318 # | +-- GoodBook
319 # +-- Author
320 # +-- BankAccount
321 #
322 # Suppose that Book is to connect to a separate database (i.e. one other
323 # than the default database). Then Book, ScaryBook and GoodBook will all use
324 # the same connection pool. Likewise, Author and BankAccount will use the
325 # same connection pool. However, the connection pool used by Author/BankAccount
326 # is not the same as the one used by Book/ScaryBook/GoodBook.
327 #
328 # 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
329 # ActiveRecord::Base.connection_handler. Active Record models use this to
a293278 @lifo Merge docrails
lifo authored
330 # determine that connection pool that they should use.
ca6d717 @nicksieger Deprecate allow_concurrency and make it have no effect
nicksieger authored
331 class ConnectionHandler
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
332 def initialize(pools = Hash.new { |h,k| h[k] = {} })
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
333 @connection_pools = pools
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
334 @class_to_pool = Hash.new { |h,k| h[k] = {} }
335 end
336
337 def connection_pools
decafdd @tenderlove use Process.pid rather than $$
tenderlove authored
338 @connection_pools[Process.pid]
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
339 end
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
340
341 def establish_connection(name, spec)
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
342 set_pool_for_spec spec, ConnectionAdapters::ConnectionPool.new(spec)
343 set_class_to_pool name, connection_pools[spec]
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
344 end
345
25f9497 @tenderlove adding active_connections? to the connection pool for finding open co…
tenderlove authored
346 # Returns true if there are any active connections among the connection
347 # pools that the ConnectionHandler is managing.
348 def active_connections?
349 connection_pools.values.any? { |pool| pool.active_connection? }
350 end
351
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
352 # Returns any connections in use by the current thread back to the pool,
353 # and also returns connections to the pool cached by threads that are no
354 # longer alive.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
355 def clear_active_connections!
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
356 connection_pools.each_value {|pool| pool.release_connection }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
357 end
358
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
359 # Clears the cache which maps classes.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
360 def clear_reloadable_connections!
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
361 connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
362 end
363
364 def clear_all_connections!
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
365 connection_pools.each_value {|pool| pool.disconnect! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
366 end
367
368 # Locate the connection of the nearest super class. This can be an
369 # active or defined connection: if it is the latter, it will be
370 # opened and set as the active connection for the class it was defined
371 # for (not necessarily the current class).
372 def retrieve_connection(klass) #:nodoc:
373 pool = retrieve_connection_pool(klass)
374 (pool && pool.connection) or raise ConnectionNotEstablished
375 end
376
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
377 # Returns true if a connection that's accessible to this class has
378 # already been opened.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
379 def connected?(klass)
0832bc6 @lifo Make sure ActiveRecord::Base.connected? doesn't raise an exception fo…
lifo authored
380 conn = retrieve_connection_pool(klass)
a4458f5 @tenderlove removing useless ternary
tenderlove authored
381 conn && conn.connected?
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
382 end
383
384 # Remove the connection for this class. This will close the active
385 # connection and the defined connection (if they exist). The result
386 # can be used as an argument for establish_connection, for easily
387 # re-establishing the connection.
388 def remove_connection(klass)
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
389 pool = class_to_pool.delete(klass.name)
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
390 return nil unless pool
391
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
392 connection_pools.delete pool.spec
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
393 pool.automatic_reconnect = false
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
394 pool.disconnect!
395 pool.spec.config
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
396 end
397
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
398 def retrieve_connection_pool(klass)
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
399 pool = get_pool_for_class klass.name
3007545 @nicksieger Minor tweak to retrieve_connection_pool -- recurse instead of loop
nicksieger authored
400 return pool if pool
dae7b65 @jonleighton Support establishing connection on ActiveRecord::Model.
jonleighton authored
401 return nil if ActiveRecord::Model == klass
7293cac @jonleighton Extract common logic into a method
jonleighton authored
402 retrieve_connection_pool klass.active_record_super
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
403 end
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
404
405 private
406
407 def class_to_pool
decafdd @tenderlove use Process.pid rather than $$
tenderlove authored
408 @class_to_pool[Process.pid]
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
409 end
410
411 def set_pool_for_spec(spec, pool)
decafdd @tenderlove use Process.pid rather than $$
tenderlove authored
412 @connection_pools[Process.pid][spec] = pool
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
413 end
414
415 def set_class_to_pool(name, pool)
decafdd @tenderlove use Process.pid rather than $$
tenderlove authored
416 @class_to_pool[Process.pid][name] = pool
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
417 pool
418 end
419
420 def get_pool_for_class(klass)
decafdd @tenderlove use Process.pid rather than $$
tenderlove authored
421 @class_to_pool[Process.pid].fetch(klass) {
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored
422 c_to_p = @class_to_pool.values.find { |class_to_pool|
423 class_to_pool[klass]
424 }
425
426 if c_to_p
427 pool = c_to_p[klass]
428 pool = ConnectionAdapters::ConnectionPool.new pool.spec
429 set_pool_for_spec pool.spec, pool
430 set_class_to_pool klass, pool
431 else
432 set_class_to_pool klass, nil
433 end
434 }
435 end
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
436 end
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
437
438 class ConnectionManagement
439 def initialize(app)
440 @app = app
441 end
442
443 def call(env)
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
444 testing = env.key?('rack.test')
445
2b81240 @lest use Rack::BodyProxy in activerecord middlewares
lest authored
446 response = @app.call(env)
447 response[2] = ::Rack::BodyProxy.new(response[2]) do
448 ActiveRecord::Base.clear_active_connections! unless testing
449 end
e524609 @tenderlove proxy body responses so we close database connections after body is f…
tenderlove authored
450
2b81240 @lest use Rack::BodyProxy in activerecord middlewares
lest authored
451 response
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if…
tenderlove authored
452 rescue
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
453 ActiveRecord::Base.clear_active_connections! unless testing
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if…
tenderlove authored
454 raise
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
455 end
456 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
457 end
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
458 end
Something went wrong with that request. Please try again.