Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 487 lines (420 sloc) 16.967 kB
d869298 @raggi Don't depend on rubygems loading thread (for Mutex)
raggi authored
1 require 'thread'
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
2 require 'monitor'
50cd4bd @nicksieger Introduce synchronization around connection pool access
nicksieger authored
3 require 'set'
e8550ee @jeremy Cherry-pick core extensions
jeremy authored
4 require 'active_support/core_ext/module/synchronization'
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
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
60 attr_accessor :automatic_reconnect
cccb998 @josevalim Expose connections available in the connection pool.
josevalim authored
61 attr_reader :spec, :connections
0de661d @tenderlove the connection pool caches table_exists? calls
tenderlove authored
62 attr_reader :columns, :columns_hash, :primary_keys, :tables
2fe088a @tenderlove cache column defaults for AR object instantiation
tenderlove authored
63 attr_reader :column_defaults
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)
72 @spec = spec
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
73
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
74 # The cache of reserved connections mapped to threads
75 @reserved_connections = {}
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
76
cab76ce @nicksieger Add synchronization to connection pool also
nicksieger authored
77 # The mutex used to synchronize pool access
78 @connection_mutex = Monitor.new
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
79 @queue = @connection_mutex.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
dd944cb @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
85 @connections = []
86 @checked_out = []
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
87 @automatic_reconnect = true
dd944cb @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
88 @tables = {}
89 @visitor = nil
59f7780 @tenderlove adjust query counts to be consistent across databases, make sure data…
tenderlove authored
90
5f3cf42 @tenderlove connection pool can cache column, table, and primary key information
tenderlove authored
91 @columns = Hash.new do |h, table_name|
92 h[table_name] = with_connection do |conn|
0cd4286 @tenderlove making sure primary key is set on the columns
tenderlove authored
93
94 # Fetch a list of columns
95 conn.columns(table_name, "#{table_name} Columns").tap do |columns|
96
97 # set primary key information
98 columns.each do |column|
99 column.primary = column.name == primary_keys[table_name]
100 end
101 end
5f3cf42 @tenderlove connection pool can cache column, table, and primary key information
tenderlove authored
102 end
103 end
104
105 @columns_hash = Hash.new do |h, table_name|
106 h[table_name] = Hash[columns[table_name].map { |col|
107 [col.name, col]
108 }]
109 end
110
2fe088a @tenderlove cache column defaults for AR object instantiation
tenderlove authored
111 @column_defaults = Hash.new do |h, table_name|
112 h[table_name] = Hash[columns[table_name].map { |col|
113 [col.name, col.default]
114 }]
115 end
116
5f3cf42 @tenderlove connection pool can cache column, table, and primary key information
tenderlove authored
117 @primary_keys = Hash.new do |h, table_name|
118 h[table_name] = with_connection do |conn|
0de661d @tenderlove the connection pool caches table_exists? calls
tenderlove authored
119 table_exists?(table_name) ? conn.primary_key(table_name) : 'id'
5f3cf42 @tenderlove connection pool can cache column, table, and primary key information
tenderlove authored
120 end
121 end
122 end
123
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
124 # A cached lookup for table existence.
0de661d @tenderlove the connection pool caches table_exists? calls
tenderlove authored
125 def table_exists?(name)
126 return true if @tables.key? name
127
128 with_connection do |conn|
129 conn.tables.each { |table| @tables[table] = true }
f960cb2 @metaskills Allow the connection pool's #table_exists? method to give the connect…
metaskills authored
130 @tables[name] = true if !@tables.key?(name) && conn.table_exists?(name)
0de661d @tenderlove the connection pool caches table_exists? calls
tenderlove authored
131 end
132
133 @tables.key? name
134 end
135
5f3cf42 @tenderlove connection pool can cache column, table, and primary key information
tenderlove authored
136 # Clears out internal caches:
137 #
138 # * columns
139 # * columns_hash
59f7780 @tenderlove adjust query counts to be consistent across databases, make sure data…
tenderlove authored
140 # * tables
5f3cf42 @tenderlove connection pool can cache column, table, and primary key information
tenderlove authored
141 def clear_cache!
142 @columns.clear
143 @columns_hash.clear
2fe088a @tenderlove cache column defaults for AR object instantiation
tenderlove authored
144 @column_defaults.clear
59f7780 @tenderlove adjust query counts to be consistent across databases, make sure data…
tenderlove authored
145 @tables.clear
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
146 end
147
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
148 # Clear out internal caches for table with +table_name+.
c94651f @tenderlove almost fisted
tenderlove authored
149 def clear_table_cache!(table_name)
150 @columns.delete table_name
151 @columns_hash.delete table_name
2fe088a @tenderlove cache column defaults for AR object instantiation
tenderlove authored
152 @column_defaults.delete table_name
c94651f @tenderlove almost fisted
tenderlove authored
153 @primary_keys.delete table_name
154 end
155
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
156 # Retrieve the connection associated with the current thread, or call
157 # #checkout to obtain one if necessary.
158 #
159 # #connection can be called any number of times; the connection is
160 # held in a hash keyed by the thread id.
161 def connection
072cd60 @tenderlove refactor if / else to ||=
tenderlove authored
162 @reserved_connections[current_connection_id] ||= checkout
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
163 end
164
4211866 @tenderlove adding active_connection? to the connection pool
tenderlove authored
165 # Check to see if there is an active connection in this connection
166 # pool.
167 def active_connection?
168 @reserved_connections.key? current_connection_id
169 end
170
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
171 # 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
172 # #release_connection releases the connection-thread association
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
173 # and returns the connection to the pool.
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
174 def release_connection(with_id = current_connection_id)
175 conn = @reserved_connections.delete(with_id)
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
176 checkin conn if conn
177 end
178
5501b99 @account-settings Ensure ActiveRecord::Base.connection_pool.with_connection creates a n…
account-settings authored
179 # 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
180 # 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
181 # connection when finished.
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
182 def with_connection
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
183 connection_id = current_connection_id
184 fresh_connection = true unless @reserved_connections[connection_id]
5501b99 @account-settings Ensure ActiveRecord::Base.connection_pool.with_connection creates a n…
account-settings authored
185 yield connection
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
186 ensure
3344520 @tenderlove reduce the number of times current_connection_id is called in with_co…
tenderlove authored
187 release_connection(connection_id) if fresh_connection
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
188 end
189
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
190 # Returns true if a connection has already been opened.
191 def connected?
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
192 !@connections.empty?
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
193 end
194
a293278 @lifo Merge docrails
lifo authored
195 # 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
196 def disconnect!
197 @reserved_connections.each do |name,conn|
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
198 checkin conn
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
199 end
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
200 @reserved_connections = {}
201 @connections.each do |conn|
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
202 conn.disconnect!
203 end
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
204 @connections = []
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
205 end
206
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
207 # Clears the cache which maps classes.
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
208 def clear_reloadable_connections!
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
209 @reserved_connections.each do |name, conn|
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
210 checkin conn
029952e @nicksieger Extract a base class for connection pools, start to flesh out reserve…
nicksieger authored
211 end
212 @reserved_connections = {}
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
213 @connections.each do |conn|
214 conn.disconnect! if conn.requires_reloading?
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
215 end
62c4e4d @ebeigarts Fix connection reloading in development mode. [#4929 state:resolved]
ebeigarts authored
216 @connections.delete_if do |conn|
217 conn.requires_reloading?
218 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
219 end
220
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integrati…
nicksieger authored
221 # Verify active connections and remove and disconnect connections
222 # associated with stale threads.
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
223 def verify_active_connections! #:nodoc:
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
224 clear_stale_cached_connections!
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
225 @connections.each do |connection|
7ba2872 @nicksieger Deprecate verification_timeout and verify before reset
nicksieger authored
226 connection.verify!
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
227 end
228 end
229
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
230 # Return any checked-out connections back to the pool by threads that
231 # are no longer alive.
232 def clear_stale_cached_connections!
42be67e @tenderlove unfactoring clear_stale_cached_connections!
tenderlove authored
233 keys = @reserved_connections.keys - Thread.list.find_all { |t|
234 t.alive?
235 }.map { |thread| thread.object_id }
236 keys.each do |key|
237 checkin @reserved_connections[key]
238 @reserved_connections.delete(key)
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
239 end
240 end
241
a293278 @lifo Merge docrails
lifo authored
242 # Check-out a database connection from the pool, indicating that you want
243 # to use it. You should call #checkin when you no longer need this.
244 #
245 # This is done by either returning an existing connection, or by creating
246 # a new connection. If the maximum number of connections for this pool has
247 # already been reached, but the pool is empty (i.e. they're all being used),
248 # then this method will wait until a thread has checked in a connection.
249 # The wait time is bounded however: if no connection can be checked out
250 # within the timeout specified for this pool, then a ConnectionTimeoutError
251 # exception will be raised.
252 #
253 # Returns: an AbstractAdapter object.
254 #
255 # Raises:
256 # - ConnectionTimeoutError: no connection can be obtained from the pool
257 # within the timeout period.
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
258 def checkout
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
259 # Checkout an available connection
260 @connection_mutex.synchronize do
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
261 loop do
262 conn = if @checked_out.size < @connections.size
263 checkout_existing_connection
264 elsif @connections.size < @size
265 checkout_new_connection
266 end
267 return conn if conn
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
268
269 @queue.wait(@timeout)
270
271 if(@checked_out.size < @connections.size)
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
272 next
273 else
8343611 @alk made ConnectionPool#checkout more robust by trying to loot dead threa…
alk authored
274 clear_stale_cached_connections!
275 if @size == @checked_out.size
dd77733 @jeremy Timeout the connection pool monitor on ruby 1.8 only
jeremy authored
276 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 threa…
alk authored
277 end
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
278 end
2a04110 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests
Hemant Kumar authored
279
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
280 end
281 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
282 end
283
a293278 @lifo Merge docrails
lifo authored
284 # Check-in a database connection back into the pool, indicating that you
285 # no longer need this connection.
286 #
287 # +conn+: an AbstractAdapter object, which was obtained by earlier by
288 # calling +checkout+ on this pool.
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
289 def checkin(conn)
290 @connection_mutex.synchronize do
57bc25c @jfirebaugh Use run_callbacks; the generated _run_<name>_callbacks method is not …
jfirebaugh authored
291 conn.run_callbacks :checkin do
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
292 @checked_out.delete conn
293 @queue.signal
294 end
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
295 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
296 end
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
297
113cc4e @nicksieger Remove some synchronization that's probably overkill, assuming one do…
nicksieger authored
298 synchronize :clear_reloadable_connections!, :verify_active_connections!,
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
299 :connected?, :disconnect!, :with => :@connection_mutex
300
301 private
dd944cb @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
302
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
303 def new_connection
dd944cb @jonleighton Make it the responsibility of the connection to hold onto an ARel vis…
jonleighton authored
304 connection = ActiveRecord::Base.send(spec.adapter_method, spec.config)
305
306 # TODO: This is a bit icky, and in the long term we may want to change the method
307 # signature for connections. Also, if we switch to have one visitor per
308 # connection (and therefore per thread), we can get rid of the thread-local
309 # variable in Arel::Visitors::ToSql.
310 @visitor ||= connection.class.visitor_for(self)
311 connection.visitor = @visitor
312
313 connection
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
314 end
315
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
316 def current_connection_id #:nodoc:
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
317 Thread.current.object_id
318 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
319
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
320 def checkout_new_connection
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
321 raise ConnectionNotEstablished unless @automatic_reconnect
322
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
323 c = new_connection
324 @connections << c
a96b7d4 @nicksieger Add connection reset and verification upon each connection checkout
nicksieger authored
325 checkout_and_verify(c)
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
326 end
327
328 def checkout_existing_connection
d7d2d73 @nicksieger Fix typo: was using brackets instead of parens. Must need more sleep.
nicksieger authored
329 c = (@connections - @checked_out).first
a96b7d4 @nicksieger Add connection reset and verification upon each connection checkout
nicksieger authored
330 checkout_and_verify(c)
331 end
332
333 def checkout_and_verify(c)
471a394 @nicksieger Modify connection pool callbacks to be compatible w/ new style
nicksieger authored
334 c.run_callbacks :checkout do
335 c.verify!
336 @checked_out << c
337 end
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
338 c
339 end
340 end
341
a293278 @lifo Merge docrails
lifo authored
342 # 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
343 # for keeping separate connection pools for Active Record models that connect
a293278 @lifo Merge docrails
lifo authored
344 # to different databases.
345 #
346 # For example, suppose that you have 5 models, with the following hierarchy:
347 #
348 # |
349 # +-- Book
350 # | |
351 # | +-- ScaryBook
352 # | +-- GoodBook
353 # +-- Author
354 # +-- BankAccount
355 #
356 # Suppose that Book is to connect to a separate database (i.e. one other
357 # than the default database). Then Book, ScaryBook and GoodBook will all use
358 # the same connection pool. Likewise, Author and BankAccount will use the
359 # same connection pool. However, the connection pool used by Author/BankAccount
360 # is not the same as the one used by Book/ScaryBook/GoodBook.
361 #
362 # 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
363 # ActiveRecord::Base.connection_handler. Active Record models use this to
a293278 @lifo Merge docrails
lifo authored
364 # determine that connection pool that they should use.
ca6d717 @nicksieger Deprecate allow_concurrency and make it have no effect
nicksieger authored
365 class ConnectionHandler
b952470 @tenderlove use an attr_reader for performance
tenderlove authored
366 attr_reader :connection_pools
367
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
368 def initialize(pools = {})
369 @connection_pools = pools
370 end
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
371
372 def establish_connection(name, spec)
8e5e02b @nicksieger Collapse connection pool class hierarchy; YAGNI.
nicksieger authored
373 @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec)
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
374 end
375
25f9497 @tenderlove adding active_connections? to the connection pool for finding open co…
tenderlove authored
376 # Returns true if there are any active connections among the connection
377 # pools that the ConnectionHandler is managing.
378 def active_connections?
379 connection_pools.values.any? { |pool| pool.active_connection? }
380 end
381
d07a6b1 @nicksieger Make clear_active_connections! also return stale connections back to …
nicksieger authored
382 # Returns any connections in use by the current thread back to the pool,
383 # and also returns connections to the pool cached by threads that are no
384 # longer alive.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
385 def clear_active_connections!
529c271 @nicksieger Simplify dispatcher callbacks to eliminate unnecessary stale thread p…
nicksieger authored
386 @connection_pools.each_value {|pool| pool.release_connection }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
387 end
388
8f1b141 @smartinez87 Fixed punctuation errors.
smartinez87 authored
389 # Clears the cache which maps classes.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
390 def clear_reloadable_connections!
391 @connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
392 end
393
394 def clear_all_connections!
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
395 @connection_pools.each_value {|pool| pool.disconnect! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
396 end
397
398 # Verify active connections.
399 def verify_active_connections! #:nodoc:
817a07b @nicksieger More doco and class/method renames. Now have a strategy for integrati…
nicksieger authored
400 @connection_pools.each_value {|pool| pool.verify_active_connections! }
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
401 end
402
403 # Locate the connection of the nearest super class. This can be an
404 # active or defined connection: if it is the latter, it will be
405 # opened and set as the active connection for the class it was defined
406 # for (not necessarily the current class).
407 def retrieve_connection(klass) #:nodoc:
408 pool = retrieve_connection_pool(klass)
409 (pool && pool.connection) or raise ConnectionNotEstablished
410 end
411
82fcd9d @nicksieger Clean up the code, get rid of reserve/release, add some more docs
nicksieger authored
412 # Returns true if a connection that's accessible to this class has
413 # already been opened.
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
414 def connected?(klass)
0832bc6 @lifo Make sure ActiveRecord::Base.connected? doesn't raise an exception fo…
lifo authored
415 conn = retrieve_connection_pool(klass)
a4458f5 @tenderlove removing useless ternary
tenderlove authored
416 conn && conn.connected?
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
417 end
418
419 # Remove the connection for this class. This will close the active
420 # connection and the defined connection (if they exist). The result
421 # can be used as an argument for establish_connection, for easily
422 # re-establishing the connection.
423 def remove_connection(klass)
c5af3a6 @rsutphin Completely remove the pool when removing a connection. Fixes #2820.
rsutphin authored
424 pool = @connection_pools.delete(klass.name)
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
425 return nil unless pool
426
acccb72 @tenderlove column cache now lives on the connection pool
tenderlove authored
427 pool.automatic_reconnect = false
04ef434 @tenderlove only test for existence of +pool+ once
tenderlove authored
428 pool.disconnect!
429 pool.spec.config
ff97e9d @nicksieger Connection handling methods extracted out into separate ConnectionHan…
nicksieger authored
430 end
431
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
432 def retrieve_connection_pool(klass)
3007545 @nicksieger Minor tweak to retrieve_connection_pool -- recurse instead of loop
nicksieger authored
433 pool = @connection_pools[klass.name]
434 return pool if pool
435 return nil if ActiveRecord::Base == klass
436 retrieve_connection_pool klass.superclass
fe575dd @nicksieger Nearing the finish line. Initial fixed-size connection pool implement…
nicksieger authored
437 end
72d959d @nicksieger Split connection handler into single- and multiple-thread versions.
nicksieger authored
438 end
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
439
440 class ConnectionManagement
e524609 @tenderlove proxy body responses so we close database connections after body is f…
tenderlove authored
441 class Proxy # :nodoc:
442 attr_reader :body, :testing
443
444 def initialize(body, testing = false)
445 @body = body
446 @testing = testing
447 end
448
aba7a43 @stevehodgkiss Fix inconsistencies by being polite to the wrapped body. Needed for R…
stevehodgkiss authored
449 def method_missing(method_sym, *arguments, &block)
450 @body.send(method_sym, *arguments, &block)
451 end
452
453 def respond_to?(method_sym, include_private = false)
454 super || @body.respond_to?(method_sym)
455 end
456
e524609 @tenderlove proxy body responses so we close database connections after body is f…
tenderlove authored
457 def each(&block)
458 body.each(&block)
459 end
460
461 def close
462 body.close if body.respond_to?(:close)
463
464 # Don't return connection (and perform implicit rollback) if
465 # this request is a part of integration test
466 ActiveRecord::Base.clear_active_connections! unless testing
467 end
468 end
469
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
470 def initialize(app)
471 @app = app
472 end
473
474 def call(env)
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
475 testing = env.key?('rack.test')
476
e524609 @tenderlove proxy body responses so we close database connections after body is f…
tenderlove authored
477 status, headers, body = @app.call(env)
478
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
479 [status, headers, Proxy.new(body, testing)]
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if…
tenderlove authored
480 rescue
c7b7c6a @tenderlove make sure that active connections are not cleared during test when an…
tenderlove authored
481 ActiveRecord::Base.clear_active_connections! unless testing
3b2a032 @tenderlove clearing active connections in the ConnectionManagement middleware if…
tenderlove authored
482 raise
1b22071 @josh Ensure ActiveRecord session store's connections are checked in after …
josh authored
483 end
484 end
6edaa26 @nicksieger Initial conversion to connection pool
nicksieger authored
485 end
21eb18a @alk Fix race in ConnectionPool#checkout
alk authored
486 end
Something went wrong with that request. Please try again.