Ben Carpenter Sat Oct 16 20:18:47 -0400 2010

Subject: Switching between different databases

We have multiple databases with the same schema, and need determine at runtime which database to use based on a string. Is there a way to safely switch the database used by php-activerecord?

For example, at one time, we may want the following:

$dbname = 'foo';
ActiveRecord\Config::initialize(function($cfg) {
global $dbname;
$cfg->set_model_directory(dirname(FILE) . '/models'); // load the DB models from the 'models' directory
$cfg->set_connections(array('development' => 'mysql:///'.$dbname));
});

but at another time, we may have $dbname = 'bar';

Is it okay to do another ActiveRecord\Config::initialize to switch databases, or will this break something?


Keith Thibodeaux Sat Oct 16 20:35:34 -0400 2010

I'm not positive, but it sounds like it would break things. However, what you have appears to work at a glance. Are you having issues with the above posted code that you could go into detail with?

Gabriel Littman Mon Jan 10 19:43:20 -0500 2011

I've been defining mulitple connections in my config...

$cfg->set_connections(array(
'stat' => "mysql://$user:$password@$host/$stat_database",
'tasks' => "mysql://$user:$password@$host/$task_database"
));
$cfg->set_default_connection('stats');
And then applying ti to different models when needed...
class TaskModel extends ActiveRecord\Model{
static $connection = 'tasks';
}

No need to switch...

Ben Carpenter Wed Jan 12 16:40:41 -0500 2011

Actually, my problem is that I have multiple clones of the same schema, and I need to be able switch databases (all models). You have a different problem; that is, you have different models in different databases. The solution to your problem is also listed in the docs.

Kien La Wed Jan 12 18:52:52 -0500 2011

If your schemas are exactly the same then I don't think calling initialize multiple times should cause problems. Of course, I recommend you test that first.

(1-4/4)