Skip to content
Permalink
Browse files

Add identifier quoting to table aliases.

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 0a90481969b8cce14c2092c68f94ae7f98cb8c6b
Showing with 18 additions and 2 deletions.
  1. +2 −1 Cake/Database/Query.php
  2. +16 −1 Cake/Test/TestCase/Database/QueryTest.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;
}
@@ -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'));

0 comments on commit 0a90481

Please sign in to comment.
You can’t perform that action at this time.