Skip to content

Commit 9817bed

Browse files
committed
refactor(database): centralize semantic database exceptions
- Route unique constraint and retryable transaction errors through the database exception factory - Move driver-specific unique constraint checks into connection overrides - Add factory coverage for unique constraint exception classification Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 919c234 commit 9817bed

7 files changed

Lines changed: 130 additions & 54 deletions

File tree

‎system/Database/BaseConnection.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use Closure;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
1818
use CodeIgniter\Database\Exceptions\RetryableTransactionException;
19+
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
1920
use CodeIgniter\Events\Events;
2021
use CodeIgniter\I18n\Time;
2122
use Exception;
@@ -2139,6 +2140,14 @@ public function getLastException(): ?DatabaseException
21392140
return $this->lastException;
21402141
}
21412142

2143+
/**
2144+
* Checks whether the native database error represents a unique constraint violation.
2145+
*/
2146+
protected function isUniqueConstraintViolation(int|string $code, string $message): bool
2147+
{
2148+
return false;
2149+
}
2150+
21422151
/**
21432152
* Checks whether the native database code represents a retryable transaction failure.
21442153
*/
@@ -2155,6 +2164,10 @@ protected function createDatabaseException(
21552164
int|string $code = 0,
21562165
?Throwable $previous = null,
21572166
): DatabaseException {
2167+
if ($this->isUniqueConstraintViolation($code, $message)) {
2168+
return new UniqueConstraintViolationException($message, $code, $previous);
2169+
}
2170+
21582171
if ($this->isRetryableTransactionErrorCode($code)) {
21592172
return new RetryableTransactionException($message, $code, $previous);
21602173
}

‎system/Database/MySQLi/Connection.php‎

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

1616
use CodeIgniter\Database\BaseConnection;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
18-
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
1918
use CodeIgniter\Database\TableName;
2019
use CodeIgniter\Exceptions\LogicException;
2120
use mysqli;
@@ -98,6 +97,15 @@ class Connection extends BaseConnection
9897
*/
9998
protected bool $strictOn = false;
10099

100+
/**
101+
* Checks whether the native database error represents a unique constraint violation.
102+
*/
103+
protected function isUniqueConstraintViolation(int|string $code, string $message): bool
104+
{
105+
// ER_DUP_ENTRY: duplicate key value.
106+
return $code === 1062;
107+
}
108+
101109
/**
102110
* Checks whether the native database code represents a retryable transaction failure.
103111
*/
@@ -326,10 +334,7 @@ protected function execute(string $sql)
326334
'trace' => render_backtrace($e->getTrace()),
327335
]);
328336

329-
// MySQL error 1062: ER_DUP_ENTRY – duplicate key value
330-
$exception = $e->getCode() === 1062
331-
? new UniqueConstraintViolationException($e->getMessage(), $e->getCode(), $e)
332-
: $this->createDatabaseException($e->getMessage(), $e->getCode(), $e);
337+
$exception = $this->createDatabaseException($e->getMessage(), $e->getCode(), $e);
333338

334339
if ($this->DBDebug) {
335340
throw $exception;

‎system/Database/OCI8/Connection.php‎

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

1616
use CodeIgniter\Database\BaseConnection;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
18-
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
1918
use CodeIgniter\Database\Query;
2019
use CodeIgniter\Database\TableName;
2120
use ErrorException;
@@ -115,6 +114,15 @@ class Connection extends BaseConnection
115114
*/
116115
public $lastInsertedTableName;
117116

117+
/**
118+
* Checks whether the native database error represents a unique constraint violation.
119+
*/
120+
protected function isUniqueConstraintViolation(int|string $code, string $message): bool
121+
{
122+
// ORA-00001: unique constraint violated.
123+
return $code === 1;
124+
}
125+
118126
/**
119127
* Checks whether the native database code represents a retryable transaction failure.
120128
*/
@@ -248,11 +256,8 @@ protected function execute(string $sql)
248256
$result = oci_execute($this->stmtId, $this->commitMode) ? $this->stmtId : false;
249257

250258
if ($result === false) {
251-
// ORA-00001: unique constraint violated
252259
$error = $this->error();
253-
$exception = $error['code'] === 1
254-
? new UniqueConstraintViolationException((string) $error['message'], $error['code'])
255-
: $this->createDatabaseException((string) $error['message'], $error['code']);
260+
$exception = $this->createDatabaseException((string) $error['message'], $error['code']);
256261

257262
if ($this->DBDebug) {
258263
throw $exception;
@@ -280,11 +285,8 @@ protected function execute(string $sql)
280285
'trace' => render_backtrace($trace),
281286
]);
282287

283-
// ORA-00001: unique constraint violated
284288
$error = $this->error();
285-
$exception = $error['code'] === 1
286-
? new UniqueConstraintViolationException((string) $error['message'], $error['code'], $e)
287-
: $this->createDatabaseException((string) $error['message'], $error['code'], $e);
289+
$exception = $this->createDatabaseException((string) $error['message'], $error['code'], $e);
288290

289291
if ($this->DBDebug) {
290292
throw $exception;

‎system/Database/Postgre/Connection.php‎

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

1616
use CodeIgniter\Database\BaseConnection;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
18-
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
1918
use CodeIgniter\Database\RawSql;
2019
use CodeIgniter\Database\TableName;
2120
use ErrorException;
@@ -63,6 +62,14 @@ class Connection extends BaseConnection
6362
*/
6463
private ?PgSqlResult $lastFailedResult = null;
6564

65+
/**
66+
* Checks whether the native database error represents a unique constraint violation.
67+
*/
68+
protected function isUniqueConstraintViolation(int|string $code, string $message): bool
69+
{
70+
return $code === '23505';
71+
}
72+
6673
/**
6774
* Checks whether the native database code represents a retryable transaction failure.
6875
*/
@@ -280,9 +287,7 @@ protected function execute(string $sql)
280287
'trace' => render_backtrace($trace),
281288
]);
282289

283-
$exception = $sqlstate === '23505'
284-
? new UniqueConstraintViolationException($message, $sqlstate)
285-
: $this->createDatabaseException($message, $sqlstate);
290+
$exception = $this->createDatabaseException($message, $sqlstate);
286291

287292
if ($this->DBDebug) {
288293
throw $exception;

‎system/Database/SQLSRV/Connection.php‎

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

1616
use CodeIgniter\Database\BaseConnection;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
18-
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
1918
use CodeIgniter\Database\TableName;
2019
use stdClass;
2120

@@ -90,6 +89,28 @@ class Connection extends BaseConnection
9089
*/
9190
protected $_reserved_identifiers = ['*'];
9291

92+
/**
93+
* Checks whether the native database error represents a unique constraint violation.
94+
*/
95+
protected function isUniqueConstraintViolation(int|string $code, string $message): bool
96+
{
97+
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
98+
if (! is_array($errors)) {
99+
return false;
100+
}
101+
102+
foreach ($errors as $error) {
103+
// SQLSTATE 23000 (integrity constraint violation) with SQL Server error
104+
// 2627 (UNIQUE CONSTRAINT or PRIMARY KEY violation) or 2601 (UNIQUE INDEX violation).
105+
if (($error['SQLSTATE'] ?? '') === '23000'
106+
&& in_array($error['code'] ?? 0, [2627, 2601], true)) {
107+
return true;
108+
}
109+
}
110+
111+
return false;
112+
}
113+
93114
/**
94115
* Checks whether the native database code represents a retryable transaction failure.
95116
*/
@@ -554,9 +575,7 @@ protected function execute(string $sql)
554575
]);
555576

556577
$error = $this->error();
557-
$exception = $this->isUniqueConstraintViolation()
558-
? new UniqueConstraintViolationException($message, $error['code'])
559-
: $this->createDatabaseException($message, $error['code']);
578+
$exception = $this->createDatabaseException($message, $error['code']);
560579

561580
if ($this->DBDebug) {
562581
throw $exception;
@@ -568,25 +587,6 @@ protected function execute(string $sql)
568587
return $stmt;
569588
}
570589

571-
private function isUniqueConstraintViolation(): bool
572-
{
573-
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
574-
if (! is_array($errors)) {
575-
return false;
576-
}
577-
578-
foreach ($errors as $error) {
579-
// SQLSTATE 23000 (integrity constraint violation) with SQL Server error
580-
// 2627 (UNIQUE CONSTRAINT or PRIMARY KEY violation) or 2601 (UNIQUE INDEX violation).
581-
if (($error['SQLSTATE'] ?? '') === '23000'
582-
&& in_array($error['code'] ?? 0, [2627, 2601], true)) {
583-
return true;
584-
}
585-
}
586-
587-
return false;
588-
}
589-
590590
/**
591591
* The name of the platform in use (MySQLi, mssql, etc)
592592
*/

‎system/Database/SQLite3/Connection.php‎

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

1616
use CodeIgniter\Database\BaseConnection;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
18-
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
1918
use CodeIgniter\Database\TableName;
2019
use CodeIgniter\Exceptions\InvalidArgumentException;
2120
use Exception;
@@ -67,6 +66,18 @@ class Connection extends BaseConnection
6766
*/
6867
protected ?int $synchronous = null;
6968

69+
/**
70+
* Checks whether the native database error represents a unique constraint violation.
71+
*/
72+
protected function isUniqueConstraintViolation(int|string $code, string $message): bool
73+
{
74+
// SQLite3 reports unique violations in two formats depending on version:
75+
// Modern: "UNIQUE constraint failed: table.column"
76+
// Legacy: "column X is not unique"
77+
return str_contains($message, 'UNIQUE constraint failed')
78+
|| str_contains($message, 'is not unique');
79+
}
80+
7081
/**
7182
* Checks whether the native database code represents a retryable transaction failure.
7283
*/
@@ -180,9 +191,7 @@ protected function execute(string $sql)
180191
]);
181192

182193
$error = $this->error();
183-
$exception = $this->isUniqueConstraintViolation($e->getMessage())
184-
? new UniqueConstraintViolationException($e->getMessage(), $error['code'], $e)
185-
: $this->createDatabaseException($e->getMessage(), $error['code'], $e);
194+
$exception = $this->createDatabaseException($e->getMessage(), $error['code'], $e);
186195

187196
if ($this->DBDebug) {
188197
throw $exception;
@@ -194,15 +203,6 @@ protected function execute(string $sql)
194203
return false;
195204
}
196205

197-
private function isUniqueConstraintViolation(string $message): bool
198-
{
199-
// SQLite3 reports unique violations in two formats depending on version:
200-
// Modern: "UNIQUE constraint failed: table.column"
201-
// Legacy: "column X is not unique"
202-
return str_contains($message, 'UNIQUE constraint failed')
203-
|| str_contains($message, 'is not unique');
204-
}
205-
206206
/**
207207
* Returns the total number of rows affected by this query.
208208
*/

‎tests/system/Database/RetryableTransactionExceptionTest.php‎

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

1616
use CodeIgniter\Database\Exceptions\DatabaseException;
1717
use CodeIgniter\Database\Exceptions\RetryableTransactionException;
18+
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
1819
use CodeIgniter\Database\MySQLi\Connection as MySQLiConnection;
1920
use CodeIgniter\Database\OCI8\Connection as OCI8Connection;
2021
use CodeIgniter\Database\Postgre\Connection as PostgreConnection;
@@ -32,6 +33,56 @@
3233
#[Group('Others')]
3334
final class RetryableTransactionExceptionTest extends CIUnitTestCase
3435
{
36+
#[DataProvider('provideCreatesUniqueConstraintViolationExceptions')]
37+
public function testCreatesUniqueConstraintViolationExceptions(
38+
BaseConnection $db,
39+
int|string $code,
40+
string $message,
41+
): void {
42+
$exception = self::createDatabaseException($db, $message, $code);
43+
44+
$this->assertInstanceOf(UniqueConstraintViolationException::class, $exception);
45+
$this->assertSame($code, $exception->getDatabaseCode());
46+
}
47+
48+
/**
49+
* @return iterable<string, array{BaseConnection, int|string, string}>
50+
*/
51+
public static function provideCreatesUniqueConstraintViolationExceptions(): iterable
52+
{
53+
yield 'MySQLi duplicate key' => [
54+
self::connection(MySQLiConnection::class, 'MySQLi'),
55+
1062,
56+
'Duplicate entry.',
57+
];
58+
59+
yield 'Postgre unique violation' => [
60+
self::connection(PostgreConnection::class, 'Postgre'),
61+
'23505',
62+
'Unique violation.',
63+
];
64+
65+
yield 'SQLite unique constraint' => [
66+
self::connection(SQLite3Connection::class, 'SQLite3'),
67+
19,
68+
'UNIQUE constraint failed: table.column',
69+
];
70+
71+
yield 'SQLite legacy unique constraint' => [
72+
self::connection(SQLite3Connection::class, 'SQLite3'),
73+
19,
74+
'column email is not unique',
75+
];
76+
77+
if (defined('OCI_COMMIT_ON_SUCCESS')) {
78+
yield 'OCI8 unique constraint' => [
79+
self::connection(OCI8Connection::class, 'OCI8'),
80+
1,
81+
'Unique constraint violated.',
82+
];
83+
}
84+
}
85+
3586
#[DataProvider('provideCreatesRetryableTransactionExceptions')]
3687
public function testCreatesRetryableTransactionExceptions(BaseConnection $db, int|string $code): void
3788
{

0 commit comments

Comments
 (0)