简体   繁体   English

我可以在ActiveRecord(或Mongoid)中为数据库连接和table_name配置线程安全的每个请求配置吗?

[英]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 一个包含用户和的用户的sqlite3数据库
  • many sqlite databases for each user 每个用户都有许多sqlite数据库

Each user will LCRUD his tables in his databases (similar to phpmyadmin) 每个用户都会在他的数据库中LCRUD他的表(类似于phpmyadmin)

The problem 问题

I would like to have thread safe per-request configuration for database connection and table_name 我想为数据库连接和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. 现在想象两个不同的用户同时发出2个请求。

The options? 选项?

  • I give up ActiveRecord and use bare-bones DB driver 我放弃了ActiveRecord并使用了裸机DB驱动程序
  • I give up thread saftey 我放弃线程安全

I believe this is the incantation: 我相信这是咒语:
Use Class.new(AR::Base) to dynamically create classes 使用Class.new(AR::Base)动态创建类

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. Rails通常设置为每个请求一个进程,以便每个http请求由其自己的进程处理。 Look up passenger for apache module that allows that 查找允许的apache模块的乘客

In such configuration there is no need for thread safety, infact active record is not fully theadsafe afaik 在这样的配置中,不需要线程安全,事实上活动记录不完全是安全的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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