Browse Source

add case statement to sql function builder

Signed-off-by: Robin Appelman <robin@icewind.nl>
tags/v25.0.0beta1
Robin Appelman 2 years ago
parent
commit
2a68819a67
No account linked to committer's email address

+ 11
- 0
lib/private/DB/QueryBuilder/FunctionBuilder/FunctionBuilder.php View File

@@ -121,4 +121,15 @@ class FunctionBuilder implements IFunctionBuilder {
public function least($x, $y): IQueryFunction {
return new QueryFunction('LEAST(' . $this->helper->quoteColumnName($x) . ', ' . $this->helper->quoteColumnName($y) . ')');
}

public function case(array $whens, $else): IQueryFunction {
if (count($whens) < 1) {
return new QueryFunction($this->helper->quoteColumnName($else));
}

$whenParts = array_map(function (array $when) {
return 'WHEN ' . $this->helper->quoteColumnName($when['when']) . ' THEN ' . $this->helper->quoteColumnName($when['then']);
}, $whens);
return new QueryFunction('CASE ' . implode(' ', $whenParts) . ' ELSE ' . $this->helper->quoteColumnName($else) . ' END');
}
}

+ 12
- 0
lib/public/DB/QueryBuilder/IFunctionBuilder.php View File

@@ -188,4 +188,16 @@ interface IFunctionBuilder {
* @since 18.0.0
*/
public function least($x, $y): IQueryFunction;

/**
* Takes the minimum of multiple values
*
* If you want to get the minimum value of all rows in a column, use `min` instead
*
* @param array<array{"when": string|ILiteral|IParameter|IQueryFunction, "then": string|ILiteral|IParameter|IQueryFunction}> $whens
* @param string|ILiteral|IParameter|IQueryFunction $else
* @return IQueryFunction
* @since 18.0.0
*/
public function case(array $whens, $else): IQueryFunction;
}

+ 17
- 0
tests/lib/DB/QueryBuilder/FunctionBuilderTest.php View File

@@ -501,4 +501,21 @@ class FunctionBuilderTest extends TestCase {
$result->closeCursor();
$this->assertEquals(1, $row);
}

public function testCase() {
$query = $this->connection->getQueryBuilder();

$query->select($query->func()->case([
['when' => $query->expr()->gt($query->expr()->literal(1, IQueryBuilder::PARAM_INT), $query->expr()->literal(2, IQueryBuilder::PARAM_INT)), 'then' => $query->expr()->literal('first')],
['when' => $query->expr()->lt($query->expr()->literal(1, IQueryBuilder::PARAM_INT), $query->expr()->literal(2, IQueryBuilder::PARAM_INT)), 'then' => $query->expr()->literal('second')],
['when' => $query->expr()->eq($query->expr()->literal(1, IQueryBuilder::PARAM_INT), $query->expr()->literal(2, IQueryBuilder::PARAM_INT)), 'then' => $query->expr()->literal('third')],
], $query->createNamedParameter('else')));
$query->from('appconfig')
->setMaxResults(1);

$result = $query->execute();
$row = $result->fetchOne();
$result->closeCursor();
$this->assertEquals('second', $row);
}
}

Loading…
Cancel
Save