Fixing autoFields causing invalid SQL when cross database joins are being done. Tests added. Fixes #476

This commit is contained in:
Mark Story 2010-04-19 22:38:18 -04:00
parent 2f0255ec1a
commit 029d2581af
2 changed files with 45 additions and 3 deletions

View file

@ -187,7 +187,7 @@ class ContainableBehavior extends ModelBehavior {
foreach (array('hasOne', 'belongsTo') as $type) {
if (!empty($Model->{$type})) {
foreach ($Model->{$type} as $assoc => $data) {
if (!empty($data['fields'])) {
if ($Model->useDbConfig == $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
foreach ((array) $data['fields'] as $field) {
$query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
}
@ -195,15 +195,24 @@ class ContainableBehavior extends ModelBehavior {
}
}
}
if (!empty($mandatory[$Model->alias])) {
foreach ($mandatory[$Model->alias] as $field) {
if ($field == '--primaryKey--') {
$field = $Model->primaryKey;
} else if (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
list($modelName, $field) = explode('.', $field);
$field = $modelName . '.' . (($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field);
if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) {
$field = $modelName . '.' . (
($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
);
} else {
$field = null;
}
}
if ($field !== null) {
$query['fields'][] = $field;
}
$query['fields'][] = $field;
}
}
$query['fields'] = array_unique($query['fields']);

View file

@ -3593,6 +3593,39 @@ class ContainableBehaviorTest extends CakeTestCase {
$this->assertEqual($expected, $this->Article->hasAndBelongsToMany);
}
/**
* test that autoFields doesn't splice in fields from other databases.
*
* @return void
*/
function testAutoFieldsWithMultipleDatabases() {
$config = new DATABASE_CONFIG();
$skip = $this->skipIf(
!isset($config->test) || !isset($config->test2),
'%s Primary and secondary test databases not configured, skipping cross-database '
.'join tests.'
.' To run these tests, you must define $test and $test2 in your database configuration.'
);
if ($skip) {
return;
}
$db =& ConnectionManager::getDataSource('test2');
$this->_fixtures[$this->_fixtureClassMap['User']]->create($db);
$this->_fixtures[$this->_fixtureClassMap['User']]->insert($db);
$this->Article->User->setDataSource('test2');
$result = $this->Article->find('all', array(
'fields' => array('Article.title'),
'contain' => array('User')
));
$this->assertTrue(isset($result[0]['Article']));
$this->assertTrue(isset($result[0]['User']));
$this->_fixtures[$this->_fixtureClassMap['User']]->drop($db);
}
/**
* containments method
*