Skip to content

Commit

Permalink
Fixed issue with QueryExpression not parenthesizing correctly subquer…
Browse files Browse the repository at this point in the history
…ies.
  • Loading branch information
lorenzo committed May 17, 2015
1 parent 9e59980 commit 5575940
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Database/Expression/QueryExpression.php
Expand Up @@ -16,6 +16,7 @@

use Cake\Database\ExpressionInterface;
use Cake\Database\Expression\IdentifierExpression;
use Cake\Database\Query;
use Cake\Database\TypeMapTrait;
use Cake\Database\ValueBinder;
use Countable;
Expand Down Expand Up @@ -406,7 +407,9 @@ public function sql(ValueBinder $generator)
$template = ($this->count() === 1) ? '%s' : '(%s)';
$parts = [];
foreach ($this->_conditions as $part) {
if ($part instanceof ExpressionInterface) {
if ($part instanceof Query) {
$part = '(' . $part->sql($generator) . ')';
} elseif ($part instanceof ExpressionInterface) {
$part = $part->sql($generator);
}
$parts[] = $part;
Expand Down
24 changes: 24 additions & 0 deletions tests/TestCase/ORM/QueryRegressionTest.php
Expand Up @@ -839,4 +839,28 @@ public function testMatchingWithNoFields()
->toList();
$this->assertEquals([2], $results);
}

/**
* Tests that using a subquery as part of an expression will not make invalid SQL
*
* @return void
*/
public function testSubqueryInSelectExpression() {
$table = TableRegistry::get('Comments');
$ratio = $table->find()
->select(function ($query) use ($table) {
$allCommentsCount = $table->find()->select($query->func()->count('*'));
$countToFloat = $query->newExpr([$query->func()->count('*'), '1.0'])->type('*');
return [
'ratio' => $query
->newExpr($countToFloat)
->add($allCommentsCount)
->type('/')
];
})
->where(['user_id' => 1])
->first()
->ratio;
$this->assertEquals(0.5, $ratio);
}
}

0 comments on commit 5575940

Please sign in to comment.