mysql - Safe way to iterate over multiple databases in Rails -


i have several rails apps running on single mysql server. of them run same app, , of databases have same schema, each database belongs different customer.

conceptually, here's want do:

   customer.all.each |customer|       connection.execute("use #{customer.database}")       customer.do_some_complex_stuff_with_multiple_models    end 

this approach not work because, when run in web request, underlying model classes cache different database connections a/r connection pool. connection on execute "use" statement, may not connection model uses, in case queries wrong database.

i read through rails a/r code (version 3.0.3), , came code execute in loop, instead of "use" statement:

activerecord::base.clear_active_connections! activerecord::base.establish_connection(each_customer_database_config) 

i believe connection pool per-thread, seems clobber connection pool , re-establish 1 thread web request on. if connections shared in way i'm not seeing, not want code wreak havoc other active web requests in same app.

is safe in running web app? there other way this?

imo switching new database connection different requests expensive operation. ar maintains limited pool of connections.

i guess should move postgresql, have concept of schemas.

in ideal sql world structure of database

database --> schemas --> tables 

in mysql, database , schemas same thing. postgres has separate schemas, can hold tables different customers. can switch schema on fly without changing ar connection setting

activerecord::base.connection.set_schema_search_path("customer's schema") 

developing require bit of hacking though.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -