Skip to content

Commit

Permalink
Add identifier quoting to table aliases.
Browse files Browse the repository at this point in the history
Postgres & SQLServer get upset when you alias tables to User. This is
going to be pretty common so we should quote table aliases.
  • Loading branch information
markstory committed Nov 1, 2013
1 parent 5f86fef commit 0a90481
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
3 changes: 2 additions & 1 deletion Cake/Database/Query.php
Expand Up @@ -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;
}
Expand Down
17 changes: 16 additions & 1 deletion Cake/Test/TestCase/Database/QueryTest.php
Expand Up @@ -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());
Expand Down Expand Up @@ -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
*
Expand All @@ -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'));

Expand Down

0 comments on commit 0a90481

Please sign in to comment.