diff --git a/tests/TestCase/Database/QueryTest.php b/tests/TestCase/Database/QueryTest.php index b3adbf0ed4a..7cad345e8f2 100644 --- a/tests/TestCase/Database/QueryTest.php +++ b/tests/TestCase/Database/QueryTest.php @@ -2716,6 +2716,77 @@ public function testDirectIsNull() { $this->assertEquals(['name' => 'larry'], $results->fetch('assoc')); } +/** + * Tests that case statements work correctly for various use-cases. + * + * @return void + */ + public function testSqlCaseStatement() { + $query = new Query($this->connection); + $publishedCase = $query + ->newExpr() + ->addCase($query + ->newExpr() + ->add(['published' => 'Y']) + ); + $notPublishedCase = $query + ->newExpr() + ->addCase($query + ->newExpr() + ->add(['published' => 'N']) + ); + $results = $query + ->select([ + 'published' => $query->func()->sum($publishedCase), + 'not_published' => $query->func()->sum($notPublishedCase) + ]) + ->from(['comments']) + ->execute() + ->fetchAll('assoc'); + + $this->assertEquals(5, $results[0]['published']); + $this->assertEquals(1, $results[0]['not_published']); + + $query = new Query($this->connection); + $query + ->insert(['article_id', 'user_id', 'comment', 'published']) + ->into('comments') + ->values([ + 'article_id' => 2, + 'user_id' => 1, + 'comment' => 'In limbo', + 'published' => 'L' + ]) + ->execute(); + + $query = new Query($this->connection); + $conditions = [ + $query + ->newExpr() + ->add(['published' => 'Y']), + $query + ->newExpr() + ->add(['published' => 'N']) + ]; + $trueValues = [ + 'Published', + 'Not published' + ]; + $results = $query + ->select([ + 'id', + 'comment', + 'status' => $query->newExpr()->addCase($conditions, $trueValues, 'None') + ]) + ->from(['comments']) + ->execute() + ->fetchAll('assoc'); + + $this->assertEquals('Published', $results[2]['status']); + $this->assertEquals('Not published', $results[3]['status']); + $this->assertEquals('None', $results[6]['status']); + } + /** * Assertion for comparing a table's contents with what is in it. *