简体   繁体   中英

Can I have thread safe per-request configuration for database connection and table_name in ActiveRecord (or Mongoid)?

Also known as the <<"User has many Databases" question.>>

The environment

My app is modeled like so:

user has_many databases  
database has_many tables  
table has_many rows  
row habtm(+value) columns   

you get the idea!

So instead of modelling a database inside a database, I would like to have:

  • a sqlite3 database that holds the users and
  • many sqlite databases for each user

Each user will LCRUD his tables in his databases (similar to phpmyadmin)

The problem

I would like to have thread safe per-request configuration for database connection and table_name

class Table < ActiveRecord::Base
end

# in some controller
# set the connection to the user-selected database from some DB list
Table.connection = current_user.session.connection
# set the name to the user-selected table from some tables list
Table.table_name = params[:table_name]
@rows = Table.all #display them

EDIT
As you see, the connection is global and shared between threads, but as per my app's specs, each user has it's own connection. Now imagine that 2 different users make 2 requests at the same time.

The options?

  • I give up ActiveRecord and use bare-bones DB driver
  • I give up thread saftey

I believe this is the incantation:
Use Class.new(AR::Base) to dynamically create classes

post_class = Class.new(ActiveRecord::Base)
post_class.connection = set_up_connection()
post_class.table_name = :posts

@posts = post_class.all
puts @posts

# note: post_class will get GC'ed at scope end just like any var, sweet!

Rails is usually setup with a process per request so that every http request is handled by its own process. Look up passenger for apache module that allows that

In such configuration there is no need for thread safety, infact active record is not fully theadsafe afaik

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM