Skip to content

Commit

Permalink
Automatically set the value type for the case statement
Browse files Browse the repository at this point in the history
  • Loading branch information
Walther Lalk committed Aug 12, 2014
1 parent 21c5b0d commit 5cc3ef0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 21 deletions.
24 changes: 19 additions & 5 deletions src/Database/Expression/CaseExpression.php
Expand Up @@ -113,10 +113,7 @@ protected function _addExpressions($conditions, $trueValues) {
if ($trueValue === 'literal') {
$trueValue = $k;
} elseif (is_string($trueValue) || is_numeric($trueValue)) {
$trueValue = [
'value' => $trueValue,
'type' => null
];
$trueValue = $this->_parseValue($trueValue);
}

$this->_conditions[] = $c;
Expand Down Expand Up @@ -150,7 +147,7 @@ protected function _parseValue($value) {
if (is_string($value) || is_numeric($value)) {
$value = [
'value' => $value,
'type' => null
'type' => is_string($value) ? null : $this->_getType($value)
];
} elseif (is_array($value) && !isset($value['value'])) {
$value = array_keys($value);
Expand All @@ -159,6 +156,23 @@ protected function _parseValue($value) {
return $value;
}

/**
* Gets the correct type for the value
*
* @param mixed $value The value to test
*
* @return null|string
*/
protected function _getType($value) {
if (is_integer($value)) {
return 'integer';
} elseif (is_float($value)) {
return 'float';
}

return null;
}

/**
* Compiles the relevant parts into sql
*
Expand Down
16 changes: 0 additions & 16 deletions tests/TestCase/Database/QueryTest.php
Expand Up @@ -2722,8 +2722,6 @@ public function testDirectIsNull() {
* @return void
*/
public function testSqlCaseStatement() {
$convert = $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver;

$query = new Query($this->connection);
$publishedCase = $query
->newExpr()
Expand All @@ -2738,20 +2736,6 @@ public function testSqlCaseStatement() {
->add(['published' => 'N'])
);

//SQLServer requires the case statements to be converted to int
if ($convert) {
$publishedCase = $query->func()
->convert([
'INT' => 'literal',
$publishedCase
]);
$notPublishedCase = $query->func()
->convert([
'INT' => 'literal',
$notPublishedCase
]);
}

$results = $query
->select([
'published' => $query->func()->sum($publishedCase),
Expand Down

0 comments on commit 5cc3ef0

Please sign in to comment.