Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
- New #408, #410: Implement `DMLQueryBuilder::upsertReturning()` method (@Tigrov)
- Enh #412: Reduce binding parameters (@Tigrov)
- Chg #414: Rename `DMLQueryBuilder::insertWithReturningPks()` to `DMLQueryBuilder::insertReturningPks()` (@Tigrov)
- Enh #415: Implement `CaseExpressionBuilder` class (@Tigrov)

## 1.3.0 March 21, 2024

Expand Down
65 changes: 65 additions & 0 deletions src/Builder/CaseExpressionBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Db\Pgsql\Builder;

use InvalidArgumentException;
use Yiisoft\Db\Expression\CaseExpression;
use Yiisoft\Db\Expression\ExpressionInterface;
use Yiisoft\Db\Schema\Column\ColumnInterface;

use function is_string;

/**
* Builds expressions for {@see CaseExpression}.
*/
final class CaseExpressionBuilder extends \Yiisoft\Db\Expression\CaseExpressionBuilder
{
public function build(ExpressionInterface $expression, array &$params = []): string
{
$whenClauses = $expression->getWhen();

if (empty($whenClauses)) {
throw new InvalidArgumentException('The CASE expression must have at least one WHEN clause.');
}

$sql = 'CASE';

$case = $expression->getCase();

if ($case !== null) {
$caseTypeHint = $this->buildTypeHint($expression->getCaseType());
$sql .= ' ' . $this->buildConditionWithTypeHint($case, $caseTypeHint, $params);
} else {
$caseTypeHint = '';
}

foreach ($whenClauses as $when) {
$sql .= ' WHEN ' . $this->buildConditionWithTypeHint($when->condition, $caseTypeHint, $params);
$sql .= ' THEN ' . $this->buildResult($when->result, $params);
}

if ($expression->hasElse()) {
$sql .= ' ELSE ' . $this->buildResult($expression->getElse(), $params);
}

return $sql . ' END';
}

private function buildConditionWithTypeHint(mixed $condition, string $typeHint, array &$params): string
{
$builtCondition = $this->buildCondition($condition, $params);

return $typeHint !== '' ? "($builtCondition)$typeHint" : $builtCondition;
}

private function buildTypeHint(string|ColumnInterface $type): string
{
if (is_string($type)) {
return $type === '' ? '' : "::$type";
}

return '::' . $this->queryBuilder->getColumnDefinitionBuilder()->buildType($type);
}
}
3 changes: 3 additions & 0 deletions src/DQLQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
namespace Yiisoft\Db\Pgsql;

use Yiisoft\Db\Expression\ArrayExpression;
use Yiisoft\Db\Expression\CaseExpression;
use Yiisoft\Db\Expression\JsonExpression;
use Yiisoft\Db\Expression\StructuredExpression;
use Yiisoft\Db\Pgsql\Builder\ArrayExpressionBuilder;
use Yiisoft\Db\Pgsql\Builder\ArrayOverlapsConditionBuilder;
use Yiisoft\Db\Pgsql\Builder\CaseExpressionBuilder;
use Yiisoft\Db\Pgsql\Builder\JsonOverlapsConditionBuilder;
use Yiisoft\Db\Pgsql\Builder\LikeConditionBuilder;
use Yiisoft\Db\Pgsql\Builder\StructuredExpressionBuilder;
Expand Down Expand Up @@ -51,6 +53,7 @@ protected function defaultExpressionBuilders(): array
JsonOverlapsCondition::class => JsonOverlapsConditionBuilder::class,
StructuredExpression::class => StructuredExpressionBuilder::class,
LikeCondition::class => LikeConditionBuilder::class,
CaseExpression::class => CaseExpressionBuilder::class,
];
}
}
58 changes: 58 additions & 0 deletions tests/Provider/QueryBuilderProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
use Yiisoft\Db\Constant\DataType;
use Yiisoft\Db\Constant\PseudoType;
use Yiisoft\Db\Expression\ArrayExpression;
use Yiisoft\Db\Expression\CaseExpression;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Pgsql\Column\ColumnBuilder;
use Yiisoft\Db\Pgsql\Column\IntegerColumn;
use Yiisoft\Db\Pgsql\Tests\Support\TestTrait;
use Yiisoft\Db\Query\Query;

Expand Down Expand Up @@ -511,4 +513,60 @@ public static function prepareValue(): array

return $values;
}

public static function caseExpressionBuilder(): array
{
$data = parent::caseExpressionBuilder();

$db = self::getDb();
$serverVersion = $db->getServerInfo()->getVersion();
$db->close();

if (version_compare($serverVersion, '10', '<')) {
$data['without case expression'] = [
(new CaseExpression())
->addWhen(['=', 'column_name', 1], $paramA = new Param('a', DataType::STRING))
->addWhen(
'"column_name" = 2',
$db->select(new Expression(
':pv2::text',
[':pv2' => $paramB = new Param('b', DataType::STRING)],
)),
),
'CASE WHEN "column_name" = :qp0 THEN :qp1 WHEN "column_name" = 2 THEN (SELECT :pv2::text) END',
[':qp0' => 1, ':qp1' => $paramA, ':pv2' => $paramB],
'b',
];
}

return [
...$data,
'without case and type hint' => [
(new CaseExpression())->caseType('int')
->addWhen(true, "'a'"),
"CASE WHEN TRUE THEN 'a' END",
[],
'a',
],
'with case and type hint' => [
(new CaseExpression('1 + 1', 'int'))
->addWhen(1, "'a'")
->else("'b'"),
"CASE (1 + 1)::int WHEN (1)::int THEN 'a' ELSE 'b' END",
[],
'b',
],
'with case and type hint with column' => [
(new CaseExpression('1 + 1', new IntegerColumn()))
->addWhen(1, $paramA = new Param('a', DataType::STRING))
->else($paramB = new Param('b', DataType::STRING)),
'CASE (1 + 1)::integer WHEN (1)::integer THEN :qp0 ELSE :qp1 END',
[
':qp0' => $paramA,
':qp1' => $paramB,
],
'b',
],
];
}
}
11 changes: 11 additions & 0 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Yiisoft\Db\Driver\Pdo\PdoConnectionInterface;
use Yiisoft\Db\Exception\IntegrityException;
use Yiisoft\Db\Exception\NotSupportedException;
use Yiisoft\Db\Expression\CaseExpression;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Expression\ExpressionInterface;
use Yiisoft\Db\Pgsql\Tests\Provider\QueryBuilderProvider;
Expand Down Expand Up @@ -576,4 +577,14 @@ public function testPrepareValue(string $expected, mixed $value): void
{
parent::testPrepareValue($expected, $value);
}

#[DataProviderExternal(QueryBuilderProvider::class, 'caseExpressionBuilder')]
public function testCaseExpressionBuilder(
CaseExpression $case,
string $expectedSql,
array $expectedParams,
string|int $expectedResult,
): void {
parent::testCaseExpressionBuilder($case, $expectedSql, $expectedParams, $expectedResult);
}
}
2 changes: 1 addition & 1 deletion tests/Support/TestTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ protected function getDsn(): string
return $this->dsn;
}

protected function getDriverName(): string
protected static function getDriverName(): string
{
return 'pgsql';
}
Expand Down
Loading