Skip to content

Commit

Permalink
Merge pull request #12049 from cakephp/issue-12038
Browse files Browse the repository at this point in the history
Add identifier quoting for fields with spaces.
  • Loading branch information
lorenzo committed May 5, 2018
2 parents 0fb1cc7 + c51f6d1 commit 80428db
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/Database/SqlDialectTrait.php
Expand Up @@ -46,28 +46,35 @@ public function quoteIdentifier($identifier)
return $this->_startQuote . $identifier . $this->_endQuote;
}

// string.string
if (preg_match('/^[\w-]+\.[^ \*]*$/', $identifier)) {
// string.string
$items = explode('.', $identifier);

return $this->_startQuote . implode($this->_endQuote . '.' . $this->_startQuote, $items) . $this->_endQuote;
}

// string.*
if (preg_match('/^[\w-]+\.\*$/', $identifier)) {
// string.*
return $this->_startQuote . str_replace('.*', $this->_endQuote . '.*', $identifier);
}

if (preg_match('/^([\w-]+)\((.*)\)$/', $identifier, $matches)) {
// Functions
// Functions
return $matches[1] . '(' . $this->quoteIdentifier($matches[2]) . ')';
}

// Alias.field AS thing
if (preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+AS\s*([\w-]+)$/i', $identifier, $matches)) {
if (preg_match('/^([\w-]+(\.[\w-\s]+|\(.*\))*)\s+AS\s*([\w-]+)$/i', $identifier, $matches)) {
return $this->quoteIdentifier($matches[1]) . ' AS ' . $this->quoteIdentifier($matches[3]);
}

// string.string with spaces
if (preg_match('/^[\w-_]+\.[\w-_\s]+[\w_]*/', $identifier)) {
$items = explode('.', $identifier);

return $this->_startQuote . implode($this->_endQuote . '.' . $this->_startQuote, $items) . $this->_endQuote;
}

if (preg_match('/^[\w-_\s]*[\w-_]+/', $identifier)) {
return $this->_startQuote . $identifier . $this->_endQuote;
}
Expand Down
12 changes: 12 additions & 0 deletions tests/TestCase/Database/ConnectionTest.php
Expand Up @@ -765,6 +765,18 @@ public function testQuoteIdentifier()
$expected = '"Model".*';
$this->assertEquals($expected, $result);

$result = $connection->quoteIdentifier('Items.No_ 2');
$expected = '"Items"."No_ 2"';
$this->assertEquals($expected, $result);

$result = $connection->quoteIdentifier('Items.No_ 2 thing');
$expected = '"Items"."No_ 2 thing"';
$this->assertEquals($expected, $result);

$result = $connection->quoteIdentifier('Items.No_ 2 thing AS thing');
$expected = '"Items"."No_ 2 thing" AS "thing"';
$this->assertEquals($expected, $result);

$result = $connection->quoteIdentifier('MTD()');
$expected = 'MTD()';
$this->assertEquals($expected, $result);
Expand Down

0 comments on commit 80428db

Please sign in to comment.