Updating Model::setDataSource(), table prefixes now switch when switching DataSource, unless a custom table prefix is set, fixes #4062

git-svn-id: https://svn.cakephp.org/repo/branches/1.2.x.x@6496 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
nate 2008-03-01 05:15:53 +00:00
parent b1c7938ad5
commit 6546a39098
2 changed files with 36 additions and 1 deletions

View file

@ -2378,12 +2378,19 @@ class Model extends Overloadable {
* @access public
*/
function setDataSource($dataSource = null) {
$oldConfig = $this->useDbConfig;
if ($dataSource != null) {
$this->useDbConfig = $dataSource;
}
$db =& ConnectionManager::getDataSource($this->useDbConfig);
if (!empty($oldConfig)) {
$oldDb =& ConnectionManager::getDataSource($oldConfig);
if (!empty($db->config['prefix']) && $this->tablePrefix === null) {
if (empty($this->tablePrefix) || ($this->tablePrefix == $oldDb->config['prefix'])) {
$this->tablePrefix = $db->config['prefix'];
}
} else {
$this->tablePrefix = $db->config['prefix'];
}

View file

@ -2814,6 +2814,7 @@ class ModelTest extends CakeTestCase {
$this->loadFixtures('Uuid');
$this->model =& new Uuid();
$this->model->save(array('title' => 'Test record'));
$result = $this->model->findByTitle('Test record');
$this->assertEqual(array_keys($result['Uuid']), array('id', 'title', 'created', 'updated'));
@ -2999,6 +3000,33 @@ class ModelTest extends CakeTestCase {
$this->assertEqual($this->model->data, $expected);
}
function testTablePrefixSwitching() {
$db =& ConnectionManager::getDataSource('test_suite');
ConnectionManager::create('database1', array_merge($db->config, array('prefix' => 'aaa_')));
ConnectionManager::create('database2', array_merge($db->config, array('prefix' => 'bbb_')));
$db1 = ConnectionManager::getDataSource('database1');
$db2 = ConnectionManager::getDataSource('database2');
$this->model = new Apple();
$this->model->setDataSource('database1');
$this->assertEqual($db->fullTableName($this->model, false), 'aaa_apples');
$this->assertEqual($db1->fullTableName($this->model, false), 'aaa_apples');
$this->assertEqual($db2->fullTableName($this->model, false), 'aaa_apples');
$this->model->setDataSource('database2');
$this->assertEqual($db->fullTableName($this->model, false), 'bbb_apples');
$this->assertEqual($db1->fullTableName($this->model, false), 'bbb_apples');
$this->assertEqual($db2->fullTableName($this->model, false), 'bbb_apples');
$this->model = new Apple();
$this->model->tablePrefix = 'custom_';
$this->assertEqual($db->fullTableName($this->model, false), 'custom_apples');
$this->model->setDataSource('database1');
$this->assertEqual($db->fullTableName($this->model, false), 'custom_apples');
$this->assertEqual($db1->fullTableName($this->model, false), 'custom_apples');
}
function testDynamicBehaviorAttachment() {
$this->loadFixtures('Apple');
$this->model =& new Apple();