From 1c8a2f232bbe66cce3d0915b7f91d5b1ad16b100 Mon Sep 17 00:00:00 2001 From: nate Date: Thu, 10 Sep 2009 09:28:55 -0400 Subject: [PATCH] Changes Model::find() to allow modification of DataSource connection during callbacks. --- cake/libs/model/model.php | 4 +++- cake/tests/cases/libs/model/model_read.test.php | 17 +++++++++++++++++ cake/tests/cases/libs/model/models.php | 12 ++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/cake/libs/model/model.php b/cake/libs/model/model.php index 84b096fbe..4f1934def 100644 --- a/cake/libs/model/model.php +++ b/cake/libs/model/model.php @@ -1948,7 +1948,6 @@ class Model extends Overloadable { list($type, $query) = array($conditions, $fields); } - $db =& ConnectionManager::getDataSource($this->useDbConfig); $this->findQueryType = $type; $this->id = $this->getID(); @@ -1995,6 +1994,9 @@ class Model extends Overloadable { } } + if (!$db =& ConnectionManager::getDataSource($this->useDbConfig)) { + return false; + } $results = $db->read($this, $query); $this->resetAssociations(); $this->findQueryType = null; diff --git a/cake/tests/cases/libs/model/model_read.test.php b/cake/tests/cases/libs/model/model_read.test.php index eec0cfe70..74def2ae4 100644 --- a/cake/tests/cases/libs/model/model_read.test.php +++ b/cake/tests/cases/libs/model/model_read.test.php @@ -4899,6 +4899,23 @@ class ModelReadTest extends BaseModelTest { $expected = array('mariano', 'nate', 'larry', 'garrett'); $this->assertEqual($result, $expected); } + + /** + * Tests that the database configuration assigned to the model can be changed using + * (before|after)Find callbacks + * + * @return void + */ + function testCallbackSourceChange() { + $this->loadFixtures('Post'); + $TestModel = new Post(); + $this->assertEqual(3, count($TestModel->find('all'))); + + $this->expectError(new PatternExpectation('/Non-existent data source foo/i')); + $this->expectError(new PatternExpectation('/Only variable references/i')); + $this->assertFalse($TestModel->find('all', array('connection' => 'foo'))); + } + /** * testMultipleBelongsToWithSameClass method * diff --git a/cake/tests/cases/libs/model/models.php b/cake/tests/cases/libs/model/models.php index f601b82aa..086eda794 100644 --- a/cake/tests/cases/libs/model/models.php +++ b/cake/tests/cases/libs/model/models.php @@ -763,6 +763,18 @@ class Post extends CakeTestModel { * @access public */ var $belongsTo = array('Author'); + + function beforeFind($queryData) { + if (isset($queryData['connection'])) { + $this->useDbConfig = $queryData['connection']; + } + return true; + } + + function afterFind($results) { + $this->useDbConfig = 'test_suite'; + return $results; + } } /** * Author class