Skip to content

Commit 5cc3ef0

Browse files
author
Walther Lalk
committed
Automatically set the value type for the case statement
1 parent 21c5b0d commit 5cc3ef0

File tree

2 files changed

+19
-21
lines changed

2 files changed

+19
-21
lines changed

src/Database/Expression/CaseExpression.php

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,7 @@ protected function _addExpressions($conditions, $trueValues) {
113113
if ($trueValue === 'literal') {
114114
$trueValue = $k;
115115
} elseif (is_string($trueValue) || is_numeric($trueValue)) {
116-
$trueValue = [
117-
'value' => $trueValue,
118-
'type' => null
119-
];
116+
$trueValue = $this->_parseValue($trueValue);
120117
}
121118

122119
$this->_conditions[] = $c;
@@ -150,7 +147,7 @@ protected function _parseValue($value) {
150147
if (is_string($value) || is_numeric($value)) {
151148
$value = [
152149
'value' => $value,
153-
'type' => null
150+
'type' => is_string($value) ? null : $this->_getType($value)
154151
];
155152
} elseif (is_array($value) && !isset($value['value'])) {
156153
$value = array_keys($value);
@@ -159,6 +156,23 @@ protected function _parseValue($value) {
159156
return $value;
160157
}
161158

159+
/**
160+
* Gets the correct type for the value
161+
*
162+
* @param mixed $value The value to test
163+
*
164+
* @return null|string
165+
*/
166+
protected function _getType($value) {
167+
if (is_integer($value)) {
168+
return 'integer';
169+
} elseif (is_float($value)) {
170+
return 'float';
171+
}
172+
173+
return null;
174+
}
175+
162176
/**
163177
* Compiles the relevant parts into sql
164178
*

tests/TestCase/Database/QueryTest.php

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2722,8 +2722,6 @@ public function testDirectIsNull() {
27222722
* @return void
27232723
*/
27242724
public function testSqlCaseStatement() {
2725-
$convert = $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver;
2726-
27272725
$query = new Query($this->connection);
27282726
$publishedCase = $query
27292727
->newExpr()
@@ -2738,20 +2736,6 @@ public function testSqlCaseStatement() {
27382736
->add(['published' => 'N'])
27392737
);
27402738

2741-
//SQLServer requires the case statements to be converted to int
2742-
if ($convert) {
2743-
$publishedCase = $query->func()
2744-
->convert([
2745-
'INT' => 'literal',
2746-
$publishedCase
2747-
]);
2748-
$notPublishedCase = $query->func()
2749-
->convert([
2750-
'INT' => 'literal',
2751-
$notPublishedCase
2752-
]);
2753-
}
2754-
27552739
$results = $query
27562740
->select([
27572741
'published' => $query->func()->sum($publishedCase),

0 commit comments

Comments
 (0)