Skip to content

Commit

Permalink
Fix empty query expressions for generating invalid SQL.
Browse files Browse the repository at this point in the history
Using an empty QueryExpression should not generate invalid SQL.
Instead it should be a noop.

Refs #6568
  • Loading branch information
markstory committed May 27, 2015
1 parent 13bdda3 commit 0584e60
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/Database/Expression/QueryExpression.php
Expand Up @@ -403,16 +403,22 @@ public function count()
*/
public function sql(ValueBinder $generator)
{
$len = $this->count();
if ($len === 0) {
return '';
}
$conjunction = $this->_conjunction;
$template = ($this->count() === 1) ? '%s' : '(%s)';
$template = ($len === 1) ? '%s' : '(%s)';
$parts = [];
foreach ($this->_conditions as $part) {
if ($part instanceof Query) {
$part = '(' . $part->sql($generator) . ')';
} elseif ($part instanceof ExpressionInterface) {
$part = $part->sql($generator);
}
$parts[] = $part;
if (strlen($part)) {
$parts[] = $part;
}
}
return sprintf($template, implode(" $conjunction ", $parts));
}
Expand Down
52 changes: 52 additions & 0 deletions tests/TestCase/Database/Expression/QueryExpressionTest.php
Expand Up @@ -37,4 +37,56 @@ public function testAndOrCalls()
$this->assertInstanceOf($expected, $expr->and([]));
$this->assertInstanceOf($expected, $expr->or([]));
}

/**
* Test SQL generation with one element
*
* @return void
*/
public function testSqlGenerationOneClause()
{
$expr = new QueryExpression();
$binder = new ValueBinder();
$expr->add(['Users.username' => 'sally'], ['Users.username' => 'string']);

$result = $expr->sql($binder);
$this->assertEquals('Users.username = :c0', $result);
}

/**
* Test SQL generation with many elements
*
* @return void
*/
public function testSqlGenerationMultipleClauses()
{
$expr = new QueryExpression();
$binder = new ValueBinder();
$expr->add(
[
'Users.username' => 'sally',
'Users.active' => 1,
],
[
'Users.username' => 'string',
'Users.active' => 'boolean'
]
);

$result = $expr->sql($binder);
$this->assertEquals('(Users.username = :c0 AND Users.active = :c1)', $result);
}

/**
* Test that empty expressions don't emit invalid SQL.
*
* @return void
*/
public function testSqlWhenEmpty()
{
$expr = new QueryExpression();
$binder = new ValueBinder();
$result = $expr->sql($binder);
$this->assertEquals('', $result);
}
}
2 changes: 1 addition & 1 deletion tests/TestCase/ORM/QueryTest.php
Expand Up @@ -1876,7 +1876,7 @@ public function testContainAssociationWithEmptyConditions()
]);
$query = $articles->find('all')->contain(['Authors']);
$result = $query->toArray();
$this->assertCount(4, $result);
$this->assertCount(3, $result);
}

/**
Expand Down

0 comments on commit 0584e60

Please sign in to comment.