diff --git a/Cake/Database/Query.php b/Cake/Database/Query.php index 469cd321ef2..d2bf98fe3a5 100644 --- a/Cake/Database/Query.php +++ b/Cake/Database/Query.php @@ -511,10 +511,11 @@ public function from($tables = [], $overwrite = false) { protected function _buildFromPart($parts, $generator) { $select = ' FROM %s'; $normalized = []; + $driver = $this->connection()->driver(); $parts = $this->_stringifyExpressions($parts, $generator); foreach ($parts as $k => $p) { if (!is_numeric($k)) { - $p = $p . ' ' . $k; + $p = $p . ' AS ' . $driver->quoteIdentifier($k); } $normalized[] = $p; } diff --git a/Cake/Test/TestCase/Database/QueryTest.php b/Cake/Test/TestCase/Database/QueryTest.php index ae4ffcd4041..d5797e0cf90 100644 --- a/Cake/Test/TestCase/Database/QueryTest.php +++ b/Cake/Test/TestCase/Database/QueryTest.php @@ -95,7 +95,7 @@ public function testSelectFieldsFromTable() { $this->assertEquals(array('body' => 'Second Article Body', 'author_id' => 3, 'name' => 'nate'), $result->fetch('assoc')); $this->assertEquals(array('body' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'), $result->fetch('assoc')); - //Overwrite tables and only fetch from authors + // Overwrite tables and only fetch from authors $result = $query->select('name', true)->from('authors', true)->order(['name' => 'desc'], true)->execute(); $this->assertEquals(array('nate'), $result->fetch()); $this->assertEquals(array('mariano'), $result->fetch()); @@ -133,6 +133,20 @@ public function testSelectAliasedFieldsFromTable() { $this->assertEquals(array('text' => 'Second Article Body', 'two' => 2, 'three' => 5), $result->fetch('assoc')); } +/** + * Test that table aliases are quoted. + * + * @return void + */ + public function testSelectAliasTablesAreQuoted() { + $query = new Query($this->connection); + $query = $query->select(['text' => 'a.body', 'a.author_id']) + ->from(['a' => 'articles']); + + $sql = $query->sql(); + $this->assertRegExp('/articles AS [`"]a[`"]/', $sql); + } + /** * Tests that tables can also be aliased and referenced in the select clause using such alias * @@ -142,6 +156,7 @@ public function testSelectAliasedTables() { $query = new Query($this->connection); $result = $query->select(['text' => 'a.body', 'a.author_id']) ->from(['a' => 'articles'])->execute(); + $this->assertEquals(['text' => 'First Article Body', 'author_id' => 1], $result->fetch('assoc')); $this->assertEquals(['text' => 'Second Article Body', 'author_id' => 3], $result->fetch('assoc'));