Fix incorrectly quoted table aliases in virtual fields.

DboSource::_quoteFields() is already a bit of a mess, and while I'm not
happy about having to add more regex replacement, it seems to be the
only reasonable solution given that the code is already 'parsing' SQL
to apply identifier quoting.

Fixes #6602
This commit is contained in:
mark_story 2015-05-20 22:22:38 -04:00
parent d18748a50d
commit 52a0d642ec
2 changed files with 39 additions and 0 deletions

View file

@ -2869,12 +2869,19 @@ class DboSource extends DataSource {
if (!empty($this->endQuote)) {
$end = preg_quote($this->endQuote);
}
// Remove quotes and requote all the Model.field names.
$conditions = str_replace(array($start, $end), '', $conditions);
$conditions = preg_replace_callback(
'/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_][a-z0-9\\-_]*\\.[a-z0-9_][a-z0-9_\\-]*)/i',
array(&$this, '_quoteMatchedField'),
$conditions
);
// Quote `table_name AS Alias`
$conditions = preg_replace(
'/(\s[a-z0-9\\-_.' . $start . $end . ']*' . $end . ')\s+AS\s+([a-z0-9\\-_]+)/i',
'\1 AS ' . $this->startQuote . '\2' . $this->endQuote,
$conditions
);
if ($conditions !== null) {
return $conditions;
}

View file

@ -7836,6 +7836,38 @@ class ModelReadTest extends BaseModelTest {
$this->assertEquals(4, $result);
}
/**
* Test virtualfields that contain subqueries get correctly
* quoted allowing reserved words to be used.
*
* @return void
*/
public function testVirtualFieldSubqueryReservedWords() {
$this->loadFixtures('User');
$user = ClassRegistry::init('User');
$user->cacheMethods = false;
$ds = $user->getDataSource();
$sub = $ds->buildStatement(
array(
'fields' => array('Table.user'),
'table' => $ds->fullTableName($user),
'alias' => 'Table',
'limit' => 1,
'conditions' => array(
"Table.id > 1"
)
),
$user
);
$user->virtualFields = array(
'sub_test' => $sub
);
$result = $user->field('sub_test', array('id' => 1));
$this->assertNotEmpty($result);
}
/**
* testVirtualFieldsOrder()
*