Skip to content

Commit

Permalink
feat: add support for BackedEnums in query params (#171)
Browse files Browse the repository at this point in the history
  • Loading branch information
simPod committed Aug 15, 2022
1 parent 77922e4 commit 8a9beee
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Sql/ValueFormatter.php
Expand Up @@ -4,6 +4,7 @@

namespace SimPod\ClickHouseClient\Sql;

use BackedEnum;
use DateTimeImmutable;
use DateTimeZone;
use SimPod\ClickHouseClient\Exception\UnsupportedValue;
Expand Down Expand Up @@ -57,6 +58,12 @@ public function format(mixed $value, string|null $paramName = null, string|null
return 'NULL';
}

if ($value instanceof BackedEnum) {
return is_string($value->value)
? "'" . Escaper::escape($value->value) . "'"
: (string) $value->value;
}

if ($value instanceof DateTimeImmutable) {
if ($this->dateTimeZone !== null) {
$value = $value->setTimezone($this->dateTimeZone);
Expand Down
10 changes: 10 additions & 0 deletions tests/Sql/Fixture/BackedIntEnum.php
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace SimPod\ClickHouseClient\Tests\Sql\Fixture;

enum BackedIntEnum: int
{
case A = 0;
}
10 changes: 10 additions & 0 deletions tests/Sql/Fixture/BackedStringEnum.php
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace SimPod\ClickHouseClient\Tests\Sql\Fixture;

enum BackedStringEnum: string
{
case A = 'a';
}
12 changes: 12 additions & 0 deletions tests/Sql/ValueFormatterTest.php
Expand Up @@ -9,6 +9,8 @@
use SimPod\ClickHouseClient\Exception\UnsupportedValue;
use SimPod\ClickHouseClient\Sql\Expression;
use SimPod\ClickHouseClient\Sql\ValueFormatter;
use SimPod\ClickHouseClient\Tests\Sql\Fixture\BackedIntEnum;
use SimPod\ClickHouseClient\Tests\Sql\Fixture\BackedStringEnum;
use SimPod\ClickHouseClient\Tests\TestCaseBase;
use stdClass;

Expand Down Expand Up @@ -94,6 +96,16 @@ public function __toString(): string
}
},
];

yield 'String backed enum' => [
"'a'",
BackedStringEnum::A,
];

yield 'Int backed enum' => [
'0',
BackedIntEnum::A,
];
}

/**
Expand Down

0 comments on commit 8a9beee

Please sign in to comment.