Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 441 lines (383 sloc) 15.19 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 ConnectionHandle...
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 implemented,...
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 Recor...
fxn authored
14 # Connection pool base class for managing Active Record database
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implemented,...
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 implemented,...
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 Recor...
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 integration ...
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 Recor...
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 implemented,...
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 integration ...
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/re...
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 visito...
jonleighton authored
84 @connections = []
85 @checked_out = []
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
86 @automatic_reconnect = true
7db90aa @jonleighton Make it the responsibility of the connection to hold onto an ARel visito...
jonleighton authored
87 @visitor = nil
c94651f @tenderlove almost fisted
tenderlove authored
88 end
89
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
90 # Retrieve the connection associated with the current thread, or call
91 # #checkout to obtain one if necessary.
92 #
93 # #connection can be called any number of times; the connection is
94 # held in a hash keyed by the thread id.
95 def connection
072cd60 @tenderlove refactor if / else to ||=
tenderlove authored
96 @reserved_connections[current_connection_id] ||= checkout
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
97 end
98
4211866 @tenderlove adding active_connection? to the connection pool
tenderlove authored
99 # Check to see if there is an active connection in this connection
100 # pool.
101 def active_connection?
102 @reserved_connections.key? current_connection_id
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 integration ...
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_conne...
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 -exec ...
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 new ...
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_conne...
tenderlove authored
117 connection_id = current_connection_id
118 fresh_connection = true unless @reserved_connections[connection_id]
5501b99 @coderrr Ensure ActiveRecord::Base.connection_pool.with_connection creates a new ...
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_conne...
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/re...
nicksieger authored
124 # Returns true if a connection has already been opened.
125 def connected?
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
126 !@connections.empty?
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/re...
nicksieger authored
130 def disconnect!
131 @reserved_connections.each do |name,conn|
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
132 checkin conn
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve/re...
nicksieger authored
133 end
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
134 @reserved_connections = {}
135 @connections.each do |conn|
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
136 conn.disconnect!
137 end
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
138 @connections = []
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
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!
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve/re...
nicksieger authored
143 @reserved_connections.each do |name, conn|
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
144 checkin conn
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve/re...
nicksieger authored
145 end
146 @reserved_connections = {}
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
147 @connections.each do |conn|
148 conn.disconnect! if conn.requires_reloading?
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
149 end
62c4e4d @ebeigarts Fix connection reloading in development mode. [#4929 state:resolved]
ebeigarts authored
150 @connections.delete_if do |conn|
151 conn.requires_reloading?
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 integration ...
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:
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to the...
nicksieger authored
158 clear_stale_cached_connections!
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
159 @connections.each do |connection|
7ba2872 @nicksieger Deprecate verification_timeout and verify before reset
nicksieger authored
160 connection.verify!
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
161 end
162 end
163
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
164 def columns
165 with_connection do |c|
166 c.schema_cache.columns
167 end
168 end
169 deprecate :columns
170
171 def columns_hash
172 with_connection do |c|
173 c.schema_cache.columns_hash
174 end
175 end
176 deprecate :columns_hash
177
178 def primary_keys
179 raise
180 with_connection do |c|
181 c.schema_cache.primary_keys
182 end
183 end
184 deprecate :primary_keys
185
186 def clear_cache!
187 with_connection do |c|
188 c.schema_cache.clear!
189 end
190 end
191 deprecate :clear_cache!
192
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to the...
nicksieger authored
193 # Return any checked-out connections back to the pool by threads that
194 # are no longer alive.
195 def clear_stale_cached_connections!
42be67e @tenderlove unfactoring clear_stale_cached_connections!
tenderlove authored
196 keys = @reserved_connections.keys - Thread.list.find_all { |t|
197 t.alive?
198 }.map { |thread| thread.object_id }
199 keys.each do |key|
200 checkin @reserved_connections[key]
201 @reserved_connections.delete(key)
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to the...
nicksieger authored
202 end
203 end
204
a293278 @lifo Merge docrails
lifo authored
205 # Check-out a database connection from the pool, indicating that you want
206 # to use it. You should call #checkin when you no longer need this.
207 #
208 # This is done by either returning an existing connection, or by creating
209 # a new connection. If the maximum number of connections for this pool has
210 # already been reached, but the pool is empty (i.e. they're all being used),
211 # then this method will wait until a thread has checked in a connection.
212 # The wait time is bounded however: if no connection can be checked out
213 # within the timeout specified for this pool, then a ConnectionTimeoutError
214 # exception will be raised.
215 #
216 # Returns: an AbstractAdapter object.
217 #
218 # Raises:
219 # - ConnectionTimeoutError: no connection can be obtained from the pool
220 # within the timeout period.
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
221 def checkout
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
222 # Checkout an available connection
223 @connection_mutex.synchronize do
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
224 loop do
225 conn = if @checked_out.size < @connections.size
226 checkout_existing_connection
227 elsif @connections.size < @size
228 checkout_new_connection
229 end
230 return conn if conn
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
231
232 @queue.wait(@timeout)
233
234 if(@checked_out.size < @connections.size)
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
235 next
236 else
8343611 @alk made ConnectionPool#checkout more robust by trying to loot dead threads ...
alk authored
237 clear_stale_cached_connections!
238 if @size == @checked_out.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 @alk made ConnectionPool#checkout more robust by trying to loot dead threads ...
alk authored
240 end
21eb18a @alk Fix race in ConnectionPool#checkout
alk 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 a p...
jfirebaugh authored
254 conn.run_callbacks :checkin do
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
255 @checked_out.delete conn
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 doesn...
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 visito...
jonleighton authored
265
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implemented,...
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 implemented,...
nicksieger authored
268 end
269
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to the...
nicksieger authored
270 def current_connection_id #:nodoc:
f41b58d @mjtko use thread locals and an instance variable within QueryCache#BodyProxy t...
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 implemented,...
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 implemented,...
nicksieger authored
277 c = new_connection
278 @connections << c
a96b7d4 @nicksieger Add connection reset and verification upon each connection checkout
nicksieger authored
279 checkout_and_verify(c)
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implemented,...
nicksieger authored
280 end
281
282 def checkout_existing_connection
d7d2d73 @nicksieger Fix typo: was using brackets instead of parens. Must need more sleep.
nicksieger authored
283 c = (@connections - @checked_out).first
a96b7d4 @nicksieger Add connection reset and verification upon each connection checkout
nicksieger authored
284 checkout_and_verify(c)
285 end
286
287 def checkout_and_verify(c)
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
288 c.run_callbacks :checkout do
289 c.verify!
290 @checked_out << c
291 end
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implemented,...
nicksieger authored
292 c
293 end
294 end
295
a293278 @lifo Merge docrails
lifo authored
296 # ConnectionHandler is a collection of ConnectionPool objects. It is used
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Recor...
fxn authored
297 # for keeping separate connection pools for Active Record models that connect
a293278 @lifo Merge docrails
lifo authored
298 # to different databases.
299 #
300 # For example, suppose that you have 5 models, with the following hierarchy:
301 #
302 # |
303 # +-- Book
304 # | |
305 # | +-- ScaryBook
306 # | +-- GoodBook
307 # +-- Author
308 # +-- BankAccount
309 #
310 # Suppose that Book is to connect to a separate database (i.e. one other
311 # than the default database). Then Book, ScaryBook and GoodBook will all use
312 # the same connection pool. Likewise, Author and BankAccount will use the
313 # same connection pool. However, the connection pool used by Author/BankAccount
314 # is not the same as the one used by Book/ScaryBook/GoodBook.
315 #
316 # Normally there is only a single ConnectionHandler instance, accessible via
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Recor...
fxn authored
317 # ActiveRecord::Base.connection_handler. Active Record models use this to
a293278 @lifo Merge docrails
lifo authored
318 # determine that connection pool that they should use.
ca6d717 @nicksieger Deprecate allow_concurrency and make it have no effect
nicksieger authored
319 class ConnectionHandler
b952470 @tenderlove use an attr_reader for performance
tenderlove authored
320 attr_reader :connection_pools
321
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
322 def initialize(pools = {})
323 @connection_pools = pools
324 end
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
325
326 def establish_connection(name, spec)
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
327 @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec)
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
328 end
329
25f9497 @tenderlove adding active_connections? to the connection pool for finding open conne...
tenderlove authored
330 # Returns true if there are any active connections among the connection
331 # pools that the ConnectionHandler is managing.
332 def active_connections?
333 connection_pools.values.any? { |pool| pool.active_connection? }
334 end
335
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to the...
nicksieger authored
336 # Returns any connections in use by the current thread back to the pool,
337 # and also returns connections to the pool cached by threads that are no
338 # longer alive.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
339 def clear_active_connections!
529c271 @nicksieger Simplify dispatcher callbacks to eliminate unnecessary stale thread purg...
nicksieger authored
340 @connection_pools.each_value {|pool| pool.release_connection }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
341 end
342
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
343 # Clears the cache which maps classes.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
344 def clear_reloadable_connections!
345 @connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
346 end
347
348 def clear_all_connections!
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
349 @connection_pools.each_value {|pool| pool.disconnect! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
350 end
351
352 # Verify active connections.
353 def verify_active_connections! #:nodoc:
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integration ...
nicksieger authored
354 @connection_pools.each_value {|pool| pool.verify_active_connections! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
355 end
356
357 # Locate the connection of the nearest super class. This can be an
358 # active or defined connection: if it is the latter, it will be
359 # opened and set as the active connection for the class it was defined
360 # for (not necessarily the current class).
361 def retrieve_connection(klass) #:nodoc:
362 pool = retrieve_connection_pool(klass)
363 (pool && pool.connection) or raise ConnectionNotEstablished
364 end
365
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
366 # Returns true if a connection that's accessible to this class has
367 # already been opened.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
368 def connected?(klass)
0832bc6 @lifo Make sure ActiveRecord::Base.connected? doesn't raise an exception for d...
lifo authored
369 conn = retrieve_connection_pool(klass)
a4458f5 @tenderlove removing useless ternary
tenderlove authored
370 conn && conn.connected?
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
371 end
372
373 # Remove the connection for this class. This will close the active
374 # connection and the defined connection (if they exist). The result
375 # can be used as an argument for establish_connection, for easily
376 # re-establishing the connection.
377 def remove_connection(klass)
4edf6ea @tenderlove Merge pull request #2897 from rsutphin/ar31-remove_connection
tenderlove authored
378 pool = @connection_pools.delete(klass.name)
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
379 return nil unless pool
380
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
381 pool.automatic_reconnect = false
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
382 pool.disconnect!
383 pool.spec.config
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHandle...
nicksieger authored
384 end
385
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implemented,...
nicksieger authored
386 def retrieve_connection_pool(klass)
3007545 @nicksieger Minor tweak to retrieve_connection_pool -- recurse instead of loop
nicksieger authored
387 pool = @connection_pools[klass.name]
388 return pool if pool
389 return nil if ActiveRecord::Base == klass
390 retrieve_connection_pool klass.superclass
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implemented,...
nicksieger authored
391 end
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
392 end
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after eac...
josh authored
393
394 class ConnectionManagement
e524609 @tenderlove proxy body responses so we close database connections after body is flus...
tenderlove authored
395 class Proxy # :nodoc:
396 attr_reader :body, :testing
397
398 def initialize(body, testing = false)
399 @body = body
400 @testing = testing
401 end
402
5044420 @stevehodgkiss Fix inconsistencies by being polite to the wrapped body. Needed for Rack...
stevehodgkiss authored
403 def method_missing(method_sym, *arguments, &block)
404 @body.send(method_sym, *arguments, &block)
405 end
406
407 def respond_to?(method_sym, include_private = false)
408 super || @body.respond_to?(method_sym)
409 end
410
e524609 @tenderlove proxy body responses so we close database connections after body is flus...
tenderlove authored
411 def each(&block)
412 body.each(&block)
413 end
414
415 def close
416 body.close if body.respond_to?(:close)
417
418 # Don't return connection (and perform implicit rollback) if
419 # this request is a part of integration test
420 ActiveRecord::Base.clear_active_connections! unless testing
421 end
422 end
423
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after eac...
josh authored
424 def initialize(app)
425 @app = app
426 end
427
428 def call(env)
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an ex...
tenderlove authored
429 testing = env.key?('rack.test')
430
e524609 @tenderlove proxy body responses so we close database connections after body is flus...
tenderlove authored
431 status, headers, body = @app.call(env)
432
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an ex...
tenderlove authored
433 [status, headers, Proxy.new(body, testing)]
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if an...
tenderlove authored
434 rescue
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an ex...
tenderlove authored
435 ActiveRecord::Base.clear_active_connections! unless testing
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if an...
tenderlove authored
436 raise
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after eac...
josh authored
437 end
438 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
439 end
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
440 end
Something went wrong with that request. Please try again.