Multiple databases - "stuck" after unknown database

I’m implementing a one database per subdomain app, which is pretty
simple using the before_filter described on the wiki:
http://wiki.rubyonrails.org/rails/pages/HowtoUseMultipleDatabases.

I just do this in my hijack_db method:

return unless request.subdomains.first
db_name = “#{request.subdomains.first}_#{RAILS_ENV}”
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.configurations[RAILS_ENV].merge({ ‘database’ =>
db_name }))

My problem happens when someone hits a subdomain that doesn’t exist.
It tries to connect to a database that doesn’t exist and throws the
Mysql::Error 'Unknown database …" Then on the next request, before
it ever makes it to the ApplicationController, when it’s making a
connection to the database for the query cache, it tries to use the
last connection specification (the invalid one) and I just get the
unknown database error again before my hijack_db ever gets a chance to
connect to a good db. At that point, the app is “stuck” trying to
connect to the unknown db.

I have a fix for this but I’m wondering if it’s a hack or if it’s
something I should actually try submitting as a patch to Rails (I’ve
never contributed before).

My fix/hack is that I just wrap the connection method in
ConnectionPool in a begin/rescue and catch the unknown database error
and “revert” the database in the connection specification to the one
from database.yml so that (assuming the database.yml has a valid db)
the next request will succeed.

Anyone have any opinions on this?

Hi Rich,

Rich wrote:

It tries to connect to a database that doesn’t exist and throws the
Mysql::Error 'Unknown database …"

I have a fix for this but I’m wondering if it’s a hack

‘Hack’ can have such a negative connotation. I like ‘monkey patch’
better
:wink:

My fix/hack is that I just wrap the connection method in
ConnectionPool in a begin/rescue and catch the unknown
database error and “revert” the database in the connection
specification to the one from database.yml so that (assuming
the database.yml has a valid db) the next request will succeed.

I’m wondering why the same result couldn’t be had by wrapping the
connection
in your hijack_db method. I don’t know enough about the nitty-gritty of
connections, so plz take this as a question that, if you’ve got time,
I’m
interested in. I’ve got a project that might want this same sort of db
setup (one per subdomain).

Thanks,
Bill

Did you, by any chance, play in the NBA in the 70s and 80s? Sorry you
probably get that a lot.

The connection in hijack_db never gets called if it’s an unknown
database. I’m no expert either, but it appears that at some point
before ApplicationController starts handling the request, Rails is
doing something with the query cache and it needs to establish a
connection for that. That’s where the unknown db error is raised so I
need to catch it there, lower down.