diff --git a/lib/Cake/Model/Datasource/DboSource.php b/lib/Cake/Model/Datasource/DboSource.php index 80c351202..2e8e6574c 100644 --- a/lib/Cake/Model/Datasource/DboSource.php +++ b/lib/Cake/Model/Datasource/DboSource.php @@ -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; } diff --git a/lib/Cake/Test/Case/Model/ModelReadTest.php b/lib/Cake/Test/Case/Model/ModelReadTest.php index b684f06d0..255371253 100644 --- a/lib/Cake/Test/Case/Model/ModelReadTest.php +++ b/lib/Cake/Test/Case/Model/ModelReadTest.php @@ -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->find('first'); + $this->assertNotEmpty($result); + } + /** * testVirtualFieldsOrder() *