Skip to content

Commit 3700723

Browse files
authored
fix(database): properly serialize enum values when calling toRawSql (#1564)
1 parent a0acdbd commit 3700723

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

packages/database/src/RawSql.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
namespace Tempest\Database;
44

5+
use BackedEnum;
56
use Tempest\Database\Config\DatabaseDialect;
67
use Tempest\Support\Str\ImmutableString;
8+
use UnitEnum;
79

810
final class RawSql
911
{
@@ -104,6 +106,14 @@ private function formatValueForSql(mixed $value): string
104106
return (string) $value;
105107
}
106108

109+
if ($value instanceof BackedEnum) {
110+
return $value->value;
111+
}
112+
113+
if ($value instanceof UnitEnum) {
114+
return $value->name;
115+
}
116+
107117
return "'" . str_replace("'", "''", (string) $value) . "'";
108118
}
109119
}

tests/Integration/Database/QueryTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
use Tests\Tempest\Fixtures\Migrations\CreatePublishersTable;
1111
use Tests\Tempest\Fixtures\Modules\Books\Models\Author;
1212
use Tests\Tempest\Integration\FrameworkIntegrationTestCase;
13+
use Tests\Tempest\Integration\Validator\BackedEnumFixture;
14+
use Tests\Tempest\Integration\Validator\UnitEnumFixture;
1315

1416
/**
1517
* @internal
@@ -31,4 +33,18 @@ public function test_with_bindings(): void
3133
new Query('DELETE FROM authors WHERE name = :name')->execute(name: 'A');
3234
$this->assertCount(0, new Query('SELECT * FROM authors WHERE name = ?')->fetch('A'));
3335
}
36+
37+
public function test_raw_sql_enum_value(): void
38+
{
39+
$this->assertTrue(
40+
new Query('?', [UnitEnumFixture::FOO])
41+
->toRawSql()
42+
->equals(UnitEnumFixture::FOO->name),
43+
);
44+
$this->assertTrue(
45+
new Query('?', [BackedEnumFixture::FOO])
46+
->toRawSql()
47+
->equals(BackedEnumFixture::FOO->value),
48+
);
49+
}
3450
}

0 commit comments

Comments
 (0)