Skip to content

Commit 919c234

Browse files
committed
refactor(database): use retryable transaction exception
- Replace the public retryable transaction classifier with a named exception - Classify retryable driver errors through the database exception factory - Update docs and tests for exception-based retry handling Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 3fe354d commit 919c234

12 files changed

Lines changed: 100 additions & 63 deletions

File tree

‎system/Database/BaseConnection.php‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use Closure;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
18+
use CodeIgniter\Database\Exceptions\RetryableTransactionException;
1819
use CodeIgniter\Events\Events;
1920
use CodeIgniter\I18n\Time;
2021
use Exception;
@@ -2139,20 +2140,26 @@ public function getLastException(): ?DatabaseException
21392140
}
21402141

21412142
/**
2142-
* Checks whether the exception represents a retryable transaction failure.
2143+
* Checks whether the native database code represents a retryable transaction failure.
21432144
*/
2144-
public function isRetryableTransactionException(Throwable $exception): bool
2145+
protected function isRetryableTransactionErrorCode(int|string $code): bool
21452146
{
2146-
return $exception instanceof DatabaseException
2147-
&& $this->isRetryableTransactionErrorCode($exception->getDatabaseCode());
2147+
return false;
21482148
}
21492149

21502150
/**
2151-
* Checks whether the native database code represents a retryable transaction failure.
2151+
* Creates the appropriate database exception for a native database error.
21522152
*/
2153-
protected function isRetryableTransactionErrorCode(int|string $code): bool
2154-
{
2155-
return false;
2153+
protected function createDatabaseException(
2154+
string $message,
2155+
int|string $code = 0,
2156+
?Throwable $previous = null,
2157+
): DatabaseException {
2158+
if ($this->isRetryableTransactionErrorCode($code)) {
2159+
return new RetryableTransactionException($message, $code, $previous);
2160+
}
2161+
2162+
return new DatabaseException($message, $code, $previous);
21562163
}
21572164

21582165
/**

‎system/Database/ConnectionInterface.php‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313

1414
namespace CodeIgniter\Database;
1515

16-
use Throwable;
17-
1816
/**
1917
* @template TConnection
2018
* @template TResult
@@ -151,11 +149,6 @@ public function afterRollback(callable $callback): static;
151149
*/
152150
public function transaction(callable $callback): mixed;
153151

154-
/**
155-
* Checks whether the exception represents a retryable transaction failure.
156-
*/
157-
public function isRetryableTransactionException(Throwable $exception): bool;
158-
159152
/**
160153
* Returns an instance of the query builder for this connection.
161154
*
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Database\Exceptions;
15+
16+
class RetryableTransactionException extends DatabaseException
17+
{
18+
}

‎system/Database/MySQLi/Connection.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ protected function execute(string $sql)
329329
// MySQL error 1062: ER_DUP_ENTRY – duplicate key value
330330
$exception = $e->getCode() === 1062
331331
? new UniqueConstraintViolationException($e->getMessage(), $e->getCode(), $e)
332-
: new DatabaseException($e->getMessage(), $e->getCode(), $e);
332+
: $this->createDatabaseException($e->getMessage(), $e->getCode(), $e);
333333

334334
if ($this->DBDebug) {
335335
throw $exception;

‎system/Database/OCI8/Connection.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ protected function execute(string $sql)
252252
$error = $this->error();
253253
$exception = $error['code'] === 1
254254
? new UniqueConstraintViolationException((string) $error['message'], $error['code'])
255-
: new DatabaseException((string) $error['message'], $error['code']);
255+
: $this->createDatabaseException((string) $error['message'], $error['code']);
256256

257257
if ($this->DBDebug) {
258258
throw $exception;
@@ -284,7 +284,7 @@ protected function execute(string $sql)
284284
$error = $this->error();
285285
$exception = $error['code'] === 1
286286
? new UniqueConstraintViolationException((string) $error['message'], $error['code'], $e)
287-
: new DatabaseException((string) $error['message'], $error['code'], $e);
287+
: $this->createDatabaseException((string) $error['message'], $error['code'], $e);
288288

289289
if ($this->DBDebug) {
290290
throw $exception;

‎system/Database/Postgre/Connection.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ protected function execute(string $sql)
282282

283283
$exception = $sqlstate === '23505'
284284
? new UniqueConstraintViolationException($message, $sqlstate)
285-
: new DatabaseException($message, $sqlstate);
285+
: $this->createDatabaseException($message, $sqlstate);
286286

287287
if ($this->DBDebug) {
288288
throw $exception;

‎system/Database/SQLSRV/Connection.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@ protected function execute(string $sql)
556556
$error = $this->error();
557557
$exception = $this->isUniqueConstraintViolation()
558558
? new UniqueConstraintViolationException($message, $error['code'])
559-
: new DatabaseException($message, $error['code']);
559+
: $this->createDatabaseException($message, $error['code']);
560560

561561
if ($this->DBDebug) {
562562
throw $exception;

‎system/Database/SQLite3/Connection.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ protected function execute(string $sql)
182182
$error = $this->error();
183183
$exception = $this->isUniqueConstraintViolation($e->getMessage())
184184
? new UniqueConstraintViolationException($e->getMessage(), $error['code'], $e)
185-
: new DatabaseException($e->getMessage(), $error['code'], $e);
185+
: $this->createDatabaseException($e->getMessage(), $error['code'], $e);
186186

187187
if ($this->DBDebug) {
188188
throw $exception;

‎tests/system/Database/RetryableTransactionExceptionTest.php‎

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

1616
use CodeIgniter\Database\Exceptions\DatabaseException;
17-
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
17+
use CodeIgniter\Database\Exceptions\RetryableTransactionException;
1818
use CodeIgniter\Database\MySQLi\Connection as MySQLiConnection;
1919
use CodeIgniter\Database\OCI8\Connection as OCI8Connection;
2020
use CodeIgniter\Database\Postgre\Connection as PostgreConnection;
@@ -24,26 +24,27 @@
2424
use CodeIgniter\Test\Mock\MockConnection;
2525
use PHPUnit\Framework\Attributes\DataProvider;
2626
use PHPUnit\Framework\Attributes\Group;
27-
use RuntimeException;
27+
use ReflectionMethod;
2828

2929
/**
3030
* @internal
3131
*/
3232
#[Group('Others')]
3333
final class RetryableTransactionExceptionTest extends CIUnitTestCase
3434
{
35-
#[DataProvider('provideRecognizesRetryableTransactionExceptions')]
36-
public function testRecognizesRetryableTransactionExceptions(BaseConnection $db, int|string $code): void
35+
#[DataProvider('provideCreatesRetryableTransactionExceptions')]
36+
public function testCreatesRetryableTransactionExceptions(BaseConnection $db, int|string $code): void
3737
{
38-
$exception = new DatabaseException('Retryable transaction failure.', $code);
38+
$exception = self::createDatabaseException($db, 'Retryable transaction failure.', $code);
3939

40-
$this->assertTrue($db->isRetryableTransactionException($exception));
40+
$this->assertInstanceOf(RetryableTransactionException::class, $exception);
41+
$this->assertSame($code, $exception->getDatabaseCode());
4142
}
4243

4344
/**
4445
* @return iterable<string, array{BaseConnection, int|string}>
4546
*/
46-
public static function provideRecognizesRetryableTransactionExceptions(): iterable
47+
public static function provideCreatesRetryableTransactionExceptions(): iterable
4748
{
4849
yield 'MySQLi deadlock' => [self::connection(MySQLiConnection::class, 'MySQLi'), 1213];
4950

@@ -66,18 +67,18 @@ public static function provideRecognizesRetryableTransactionExceptions(): iterab
6667
}
6768
}
6869

69-
#[DataProvider('provideRejectsNonRetryableTransactionExceptions')]
70-
public function testRejectsNonRetryableTransactionExceptions(BaseConnection $db, int|string $code): void
70+
#[DataProvider('provideCreatesBaseDatabaseExceptionsForNonRetryableErrors')]
71+
public function testCreatesBaseDatabaseExceptionsForNonRetryableErrors(BaseConnection $db, int|string $code): void
7172
{
72-
$exception = new DatabaseException('Non-retryable transaction failure.', $code);
73+
$exception = self::createDatabaseException($db, 'Non-retryable transaction failure.', $code);
7374

74-
$this->assertFalse($db->isRetryableTransactionException($exception));
75+
$this->assertNotInstanceOf(RetryableTransactionException::class, $exception);
7576
}
7677

7778
/**
7879
* @return iterable<string, array{BaseConnection, int|string}>
7980
*/
80-
public static function provideRejectsNonRetryableTransactionExceptions(): iterable
81+
public static function provideCreatesBaseDatabaseExceptionsForNonRetryableErrors(): iterable
8182
{
8283
yield 'Base connection default' => [self::connection(MockConnection::class, 'MockDriver'), 1213];
8384

@@ -110,28 +111,37 @@ public static function provideRejectsNonRetryableTransactionExceptions(): iterab
110111
}
111112
}
112113

113-
public function testRejectsNonDatabaseExceptions(): void
114+
public function testQueryThrowsRetryableTransactionExceptionFromDriverExecutionPath(): void
114115
{
115-
$db = self::connection(MySQLiConnection::class, 'MySQLi');
116+
$db = $this->getMockBuilder(MySQLiConnection::class)
117+
->setConstructorArgs([self::config('MySQLi')])
118+
->onlyMethods(['connect', 'execute'])
119+
->getMock();
116120

117-
$this->assertFalse($db->isRetryableTransactionException(new RuntimeException('Not a database exception.')));
118-
}
121+
$db->method('connect')->willReturn(mysqli_init());
122+
$db->method('execute')->willThrowException(
123+
self::createDatabaseException($db, 'Deadlock found when trying to get lock.', 1213),
124+
);
119125

120-
public function testRejectsUniqueConstraintViolationExceptions(): void
121-
{
122-
$db = self::connection(MySQLiConnection::class, 'MySQLi');
126+
$this->expectException(RetryableTransactionException::class);
123127

124-
$this->assertFalse($db->isRetryableTransactionException(
125-
new UniqueConstraintViolationException('Duplicate key.', 1062),
126-
));
128+
$db->query('SELECT * FROM test');
127129
}
128130

129131
/**
130132
* @param class-string<BaseConnection> $connectionClass
131133
*/
132134
private static function connection(string $connectionClass, string $driver): BaseConnection
133135
{
134-
return new $connectionClass([
136+
return new $connectionClass(self::config($driver));
137+
}
138+
139+
/**
140+
* @return array<string, mixed>
141+
*/
142+
private static function config(string $driver): array
143+
{
144+
return [
135145
'DSN' => '',
136146
'hostname' => 'localhost',
137147
'username' => '',
@@ -145,6 +155,16 @@ private static function connection(string $connectionClass, string $driver): Bas
145155
'encrypt' => false,
146156
'compress' => false,
147157
'failover' => [],
148-
]);
158+
];
159+
}
160+
161+
private static function createDatabaseException(
162+
BaseConnection $db,
163+
string $message,
164+
int|string $code,
165+
): DatabaseException {
166+
$method = new ReflectionMethod($db, 'createDatabaseException');
167+
168+
return $method->invoke($db, $message, $code);
149169
}
150170
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ Interface Changes
4343
**NOTE:** If you've implemented your own classes that implement these interfaces from scratch, you will need to
4444
update your implementations to include the new methods or method changes to ensure compatibility.
4545

46-
- **Database:** ``CodeIgniter\Database\ConnectionInterface`` now requires the ``afterCommit()``, ``afterRollback()``, ``inTransaction()``, ``isRetryableTransactionException()``, and ``transaction()`` methods.
46+
- **Database:** ``CodeIgniter\Database\ConnectionInterface`` now requires the ``afterCommit()``, ``afterRollback()``, ``inTransaction()`` and ``transaction()`` methods.
4747
- **Logging:** ``CodeIgniter\Log\Handlers\HandlerInterface::handle()`` now requires a third parameter ``array $context = []``. Any custom log handler that overrides ``handle()`` - whether implementing ``HandlerInterface`` directly or extending a built-in handler class - must add the parameter to its ``handle()`` method signature.
4848
- **Security:** The ``SecurityInterface``'s ``verify()`` method now has a native return type of ``static``.
4949

@@ -202,7 +202,7 @@ Database
202202

203203
- Added ``afterCommit()`` and ``afterRollback()`` transaction callbacks to database connections. These callbacks run after the outermost transaction commits or rolls back. See :ref:`transactions-transaction-callbacks`.
204204
- Added ``inTransaction()`` to database connections to check whether the connection is inside an active CodeIgniter-managed transaction. See :ref:`transactions-checking-transaction-state`.
205-
- Added ``isRetryableTransactionException()`` to database connections to identify driver-specific retryable transaction failures such as deadlocks and serialization failures. See :ref:`transactions-retryable-exceptions`.
205+
- Added ``RetryableTransactionException`` for driver-specific retryable transaction failures such as deadlocks and serialization failures. See :ref:`transactions-retryable-exceptions`.
206206
- Added the ``transaction()`` method to database connections to run a callback inside a transaction. See :ref:`transactions-closure`.
207207
- Added ``trustServerCertificate`` option to ``SQLSRV`` database connections in ``Config\Database``. Set it to ``true`` to trust the server certificate without CA validation when using encrypted connections.
208208

0 commit comments

Comments
 (0)