I currently use this little addition to
ActiveRecord to allow me to switch databases on the fly (used in a middleware on an incoming connection and in other places where I need to work with multiple customers databases (like migrations)):
module ActiveRecord module ConnectionAdapters class Mysql2Adapter < AbstractMysqlAdapter # Allows us to connect to a new database in a clean way def change_database!(db) if @config[:database] != db @config.merge!(:database => db) clear_query_cache reconnect! end end def restore_default_database! database = YAML::load_file('config/database.yml')[Rails.env]['database'] change_database!(database) end end end end
I was excited to try the Rails 6 approach to multiple databases but was saddened to see that they have only considered a finite number of databases and those are listed in the
In my situation I can create a new database while the application is running (when creating a new client site) and then connect to it by visiting the domain name associated with the site.
My code above reuses the same connection. I’ve tried using
establish_connection but this eventually ends up returning
No connection pool with 'primary' found. once the connection pool appears to exhaust itself. I’d imagine I’d need a pool with at least the number of databases I have in it for it not to run out, and even then, it still could if there was more than one connection to a site per time period.
My gut is to stick with what I have, but I was wondering if there are any other caches I should be clearing when changing databases mid-stream? (for Rails 6.0 and 6.1)
I should mention that each database is exactly the same structure; it’s just a way of partitioning data between customers.
I’ve posted this question on StackOverflow but I think this might be a better place to look for a more qualified response.