Skip to content

Commit 7ff0f73

Browse files
authored
feat: support BackedEnum values in database binds (#10256)
1 parent 874a820 commit 7ff0f73

15 files changed

Lines changed: 159 additions & 20 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace CodeIgniter\Database;
1515

16+
use BackedEnum;
1617
use Closure;
1718
use CodeIgniter\Database\Exceptions\DatabaseException;
1819
use CodeIgniter\Database\Exceptions\DataException;
@@ -3939,7 +3940,7 @@ protected function objectToArray($object)
39393940
$array = [];
39403941

39413942
foreach (get_object_vars($object) as $key => $val) {
3942-
if ((! is_object($val) || $val instanceof RawSql) && ! is_array($val)) {
3943+
if (($val instanceof BackedEnum || ! is_object($val) || $val instanceof RawSql) && ! is_array($val)) {
39433944
$array[$key] = $val;
39443945
}
39453946
}

‎system/Database/BaseConnection.php‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace CodeIgniter\Database;
1515

16+
use BackedEnum;
1617
use Closure;
1718
use CodeIgniter\Database\Exceptions\DatabaseException;
1819
use CodeIgniter\Database\Exceptions\RetryableTransactionException;
@@ -1758,7 +1759,7 @@ abstract public function affectedRows(): int;
17581759
* Escapes data based on type.
17591760
* Sets boolean and null types
17601761
*
1761-
* @param array|bool|float|int|object|string|null $str
1762+
* @param mixed $str
17621763
*
17631764
* @return ($str is array ? array : float|int|string)
17641765
*/
@@ -1768,6 +1769,10 @@ public function escape($str)
17681769
return array_map($this->escape(...), $str);
17691770
}
17701771

1772+
if ($str instanceof BackedEnum) {
1773+
$str = $str->value;
1774+
}
1775+
17711776
if ($str instanceof Stringable) {
17721777
if ($str instanceof RawSql) {
17731778
return $str->__toString();

‎system/Database/BasePreparedQuery.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
namespace CodeIgniter\Database;
1515

1616
use ArgumentCountError;
17+
use BackedEnum;
1718
use CodeIgniter\Database\Exceptions\DatabaseException;
1819
use CodeIgniter\Events\Events;
1920
use CodeIgniter\Exceptions\BadMethodCallException;
@@ -122,6 +123,12 @@ abstract public function _prepare(string $sql, array $options = []);
122123
*/
123124
public function execute(...$data)
124125
{
126+
foreach ($data as $key => $value) {
127+
if ($value instanceof BackedEnum) {
128+
$data[$key] = $value->value;
129+
}
130+
}
131+
125132
// Execute the Query.
126133
$startTime = microtime(true);
127134

‎system/Database/ConnectionInterface.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ public function getLastQuery();
179179
* Escapes data based on type.
180180
* Sets boolean and null types.
181181
*
182-
* @param array|bool|float|int|object|string|null $str
182+
* @param mixed $str
183183
*
184184
* @return ($str is array ? array : float|int|string)
185185
*/

‎system/Database/Postgre/Connection.php‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace CodeIgniter\Database\Postgre;
1515

16+
use BackedEnum;
1617
use CodeIgniter\Database\BaseConnection;
1718
use CodeIgniter\Database\Exceptions\DatabaseException;
1819
use CodeIgniter\Database\RawSql;
@@ -354,7 +355,7 @@ public function affectedRows(): int
354355
*
355356
* Escapes data based on type
356357
*
357-
* @param array|bool|float|int|object|string|null $str
358+
* @param mixed $str
358359
*
359360
* @return ($str is array ? array : float|int|string)
360361
*/
@@ -364,6 +365,10 @@ public function escape($str)
364365
$this->initialize();
365366
}
366367

368+
if ($str instanceof BackedEnum) {
369+
$str = $str->value;
370+
}
371+
367372
if ($str instanceof Stringable) {
368373
if ($str instanceof RawSql) {
369374
return $str->__toString();

‎tests/system/Database/BaseQueryTest.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
use CodeIgniter\Test\Mock\MockConnection;
1818
use PHPUnit\Framework\Attributes\DataProvider;
1919
use PHPUnit\Framework\Attributes\Group;
20+
use Tests\Support\Enum\RoleEnum;
21+
use Tests\Support\Enum\StatusEnum;
2022

2123
/**
2224
* @internal
@@ -242,6 +244,17 @@ public function testBindingAutoEscapesParameters(): void
242244
$this->assertSame($expected, $query->getQuery());
243245
}
244246

247+
public function testBindingBackedEnum(): void
248+
{
249+
$query = new Query($this->db);
250+
251+
$query->setQuery('SELECT * FROM users WHERE status = ? AND role = ?', [StatusEnum::ACTIVE, RoleEnum::ADMIN]);
252+
253+
$expected = "SELECT * FROM users WHERE status = 'active' AND role = 2";
254+
255+
$this->assertSame($expected, $query->getQuery());
256+
}
257+
245258
/**
246259
* @see https://github.com/codeigniter4/CodeIgniter4/issues/5114
247260
*/

‎tests/system/Database/Builder/InsertTest.php‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use CodeIgniter\Test\CIUnitTestCase;
2121
use CodeIgniter\Test\Mock\MockConnection;
2222
use PHPUnit\Framework\Attributes\Group;
23+
use Tests\Support\Enum\StatusEnum;
2324

2425
/**
2526
* @internal
@@ -65,6 +66,34 @@ public function testInsertArray(): void
6566
$this->assertSame($expectedBinds, $builder->getBinds());
6667
}
6768

69+
public function testInsertWithBackedEnum(): void
70+
{
71+
$builder = $this->db->table('jobs');
72+
73+
$builder->testMode()->insert([
74+
'id' => 1,
75+
'status' => StatusEnum::ACTIVE,
76+
], true);
77+
78+
$expectedSQL = 'INSERT INTO "jobs" ("id", "status") VALUES (1, \'active\')';
79+
80+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledInsert()));
81+
}
82+
83+
public function testInsertObjectWithBackedEnum(): void
84+
{
85+
$builder = $this->db->table('jobs');
86+
87+
$builder->testMode()->insert((object) [
88+
'id' => 1,
89+
'status' => StatusEnum::ACTIVE,
90+
], true);
91+
92+
$expectedSQL = 'INSERT INTO "jobs" ("id", "status") VALUES (1, \'active\')';
93+
94+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledInsert()));
95+
}
96+
6897
public function testInsertObject(): void
6998
{
7099
$builder = $this->db->table('jobs');

‎tests/system/Database/Builder/WhereTest.php‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
use PHPUnit\Framework\Attributes\DataProvider;
2626
use PHPUnit\Framework\Attributes\Group;
2727
use stdClass;
28+
use Tests\Support\Enum\RoleEnum;
29+
use Tests\Support\Enum\StatusEnum;
2830

2931
/**
3032
* @internal
@@ -400,6 +402,28 @@ public function testOrWhereSameColumn(): void
400402
$this->assertSame($expectedBinds, $builder->getBinds());
401403
}
402404

405+
public function testWhereWithBackedEnum(): void
406+
{
407+
$builder = $this->db->table('jobs');
408+
409+
$builder->where('status', StatusEnum::ACTIVE);
410+
411+
$expectedSQL = 'SELECT * FROM "jobs" WHERE "status" = \'active\'';
412+
413+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
414+
}
415+
416+
public function testWhereBetweenWithBackedEnums(): void
417+
{
418+
$builder = $this->db->table('jobs');
419+
420+
$builder->whereBetween('role', [RoleEnum::GUEST, RoleEnum::ADMIN]);
421+
422+
$expectedSQL = 'SELECT * FROM "jobs" WHERE "role" BETWEEN 0 AND 2';
423+
424+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
425+
}
426+
403427
#[DataProvider('provideWhereColumnWithOperators')]
404428
public function testWhereColumnWithOperators(string $first, string $operator): void
405429
{
@@ -840,6 +864,17 @@ public function testWhereIn(): void
840864
$this->assertSame($expectedBinds, $builder->getBinds());
841865
}
842866

867+
public function testWhereInWithBackedEnums(): void
868+
{
869+
$builder = $this->db->table('jobs');
870+
871+
$builder->whereIn('status', [StatusEnum::ACTIVE, StatusEnum::INACTIVE]);
872+
873+
$expectedSQL = 'SELECT * FROM "jobs" WHERE "status" IN (\'active\',\'inactive\')';
874+
875+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
876+
}
877+
843878
public function testWhereInSubQuery(): void
844879
{
845880
$expectedSQL = 'SELECT * FROM "jobs" WHERE "id" IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)';

‎tests/system/Database/Live/EscapeTest.php‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
use CodeIgniter\Test\CIUnitTestCase;
1919
use CodeIgniter\Test\DatabaseTestTrait;
2020
use PHPUnit\Framework\Attributes\Group;
21+
use Tests\Support\Enum\RoleEnum;
22+
use Tests\Support\Enum\StatusEnum;
2123

2224
/**
2325
* @internal
@@ -63,6 +65,16 @@ public function testEscapeStringable(): void
6365
$this->assertSame($expected, $sql);
6466
}
6567

68+
public function testEscapeStringBackedEnum(): void
69+
{
70+
$this->assertSame("'active'", $this->db->escape(StatusEnum::ACTIVE));
71+
}
72+
73+
public function testEscapeIntBackedEnum(): void
74+
{
75+
$this->assertSame(2, $this->db->escape(RoleEnum::ADMIN));
76+
}
77+
6678
public function testEscapeString(): void
6779
{
6880
$expected = "SELECT * FROM brands WHERE name = 'O" . $this->char . "'Doules'";
@@ -111,7 +123,7 @@ public function testEscapeLikeStringDirect(): void
111123

112124
public function testEscapeStringArray(): void
113125
{
114-
$stringArray = [' A simple string ', new RawSql('CURRENT_TIMESTAMP()'), false, null];
126+
$stringArray = [' A simple string ', new RawSql('CURRENT_TIMESTAMP()'), false, null, StatusEnum::ACTIVE, RoleEnum::ADMIN];
115127

116128
$escapedString = $this->db->escape($stringArray);
117129

@@ -125,5 +137,7 @@ public function testEscapeStringArray(): void
125137
}
126138

127139
$this->assertSame('NULL', $escapedString[3]);
140+
$this->assertSame("'active'", $escapedString[4]);
141+
$this->assertSame(2, $escapedString[5]);
128142
}
129143
}

‎tests/system/Database/Live/PreparedQueryTest.php‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
use CodeIgniter\Test\DatabaseTestTrait;
2424
use PHPUnit\Framework\Attributes\Group;
2525
use Tests\Support\Database\Seeds\CITestSeeder;
26+
use Tests\Support\Enum\StatusEnum;
2627

2728
/**
2829
* @internal
@@ -286,6 +287,19 @@ public function testExecuteSelectQueryAndCheckTypeAndResult(): void
286287
$this->assertSame($expectedRow, $result->getRowArray());
287288
}
288289

290+
public function testExecuteWithBackedEnum(): void
291+
{
292+
$this->query = $this->db->prepare(static fn ($db) => $db->table('team_members')
293+
->select('person_id')
294+
->where('status', StatusEnum::PENDING)
295+
->get());
296+
297+
$result = $this->query->execute(StatusEnum::ACTIVE);
298+
299+
$this->assertInstanceOf(ResultInterface::class, $result);
300+
$this->assertCount(2, $result->getResultArray());
301+
}
302+
289303
public function testExecuteSelectQueryManualAndCheckTypeAndResult(): void
290304
{
291305
$this->query = $this->db->prepare(static function ($db): Query {

0 commit comments

Comments
 (0)