diff --git a/cake/libs/model/model.php b/cake/libs/model/model.php index 4f8625f6f..6d346ce95 100644 --- a/cake/libs/model/model.php +++ b/cake/libs/model/model.php @@ -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']; } diff --git a/cake/tests/cases/libs/model/model.test.php b/cake/tests/cases/libs/model/model.test.php index 93d978c5f..fa95237df 100644 --- a/cake/tests/cases/libs/model/model.test.php +++ b/cake/tests/cases/libs/model/model.test.php @@ -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();