Skip to content

Commit b6c6b72

Browse files
committed
refactor: cover additional constraint violations
Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 6052a33 commit b6c6b72

5 files changed

Lines changed: 131 additions & 13 deletions

File tree

‎system/Database/MySQLi/Connection.php‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -111,26 +111,36 @@ protected function isUniqueConstraintViolation(int|string $code, string $message
111111
*/
112112
protected function isForeignKeyConstraintViolation(int|string $code, string $message): bool
113113
{
114-
// ER_ROW_IS_REFERENCED_2, ER_NO_REFERENCED_ROW_2.
115-
return in_array($code, [1451, 1452], true);
114+
// ER_NO_REFERENCED_ROW, ER_ROW_IS_REFERENCED, ER_ROW_IS_REFERENCED_2, ER_NO_REFERENCED_ROW_2.
115+
return in_array($code, [1216, 1217, 1451, 1452], true);
116116
}
117117

118118
/**
119119
* Checks whether the native database error represents a NOT NULL constraint violation.
120120
*/
121121
protected function isNotNullConstraintViolation(int|string $code, string $message): bool
122122
{
123-
// ER_BAD_NULL_ERROR: column cannot be null.
124-
return $code === 1048;
123+
// ER_BAD_NULL_ERROR, ER_BAD_NULL_ERROR_NOT_IGNORED: column cannot be null.
124+
return in_array($code, [1048, 3673], true);
125125
}
126126

127127
/**
128128
* Checks whether the native database error represents a CHECK constraint violation.
129129
*/
130130
protected function isCheckConstraintViolation(int|string $code, string $message): bool
131131
{
132-
// ER_CHECK_CONSTRAINT_VIOLATED: check constraint is violated.
133-
return $code === 3819;
132+
if ($code === 3819) {
133+
return true;
134+
}
135+
136+
// MariaDB reports CHECK failures as ER_CONSTRAINT_FAILED, while MySQL uses 4025 for other errors.
137+
if ($code !== 4025) {
138+
return false;
139+
}
140+
141+
$message = strtolower($message);
142+
143+
return str_contains($message, 'constraint') && str_contains($message, 'failed');
134144
}
135145

136146
/**

‎system/Database/OCI8/Connection.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,8 @@ protected function isForeignKeyConstraintViolation(int|string $code, string $mes
137137
*/
138138
protected function isNotNullConstraintViolation(int|string $code, string $message): bool
139139
{
140-
// ORA-01400: cannot insert NULL.
141-
return (int) $code === 1400;
140+
// ORA-01400: cannot insert NULL; ORA-01407: cannot update to NULL.
141+
return in_array((int) $code, [1400, 1407], true);
142142
}
143143

144144
/**

‎tests/system/Database/ConstraintViolationExceptionTest.php‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,20 +85,48 @@ public static function provideCreatesConstraintViolationExceptions(): iterable
8585
ForeignKeyConstraintViolationException::class,
8686
];
8787

88+
yield 'MySQLi foreign key parent row referenced legacy code' => [
89+
self::connection(MySQLiConnection::class, 'MySQLi'),
90+
1217,
91+
'Cannot delete or update a parent row: a foreign key constraint fails.',
92+
ForeignKeyConstraintViolationException::class,
93+
];
94+
95+
yield 'MySQLi foreign key child row missing parent legacy code' => [
96+
self::connection(MySQLiConnection::class, 'MySQLi'),
97+
1216,
98+
'Cannot add or update a child row: a foreign key constraint fails.',
99+
ForeignKeyConstraintViolationException::class,
100+
];
101+
88102
yield 'MySQLi not null' => [
89103
self::connection(MySQLiConnection::class, 'MySQLi'),
90104
1048,
91105
"Column 'name' cannot be null",
92106
NotNullConstraintViolationException::class,
93107
];
94108

109+
yield 'MySQLi not null ignored' => [
110+
self::connection(MySQLiConnection::class, 'MySQLi'),
111+
3673,
112+
"Column 'name' cannot be null",
113+
NotNullConstraintViolationException::class,
114+
];
115+
95116
yield 'MySQLi check' => [
96117
self::connection(MySQLiConnection::class, 'MySQLi'),
97118
3819,
98119
"Check constraint 'positive_amount' is violated.",
99120
CheckConstraintViolationException::class,
100121
];
101122

123+
yield 'MySQLi check MariaDB' => [
124+
self::connection(MySQLiConnection::class, 'MySQLi'),
125+
4025,
126+
'CONSTRAINT `positive_amount` failed.',
127+
CheckConstraintViolationException::class,
128+
];
129+
102130
yield 'Postgre foreign key' => [
103131
self::connection(PostgreConnection::class, 'Postgre'),
104132
'23503',
@@ -247,6 +275,13 @@ public static function provideCreatesConstraintViolationExceptions(): iterable
247275
NotNullConstraintViolationException::class,
248276
];
249277

278+
yield 'OCI8 not null update' => [
279+
self::connection(OCI8Connection::class, 'OCI8'),
280+
1407,
281+
'Cannot update to NULL.',
282+
NotNullConstraintViolationException::class,
283+
];
284+
250285
yield 'OCI8 check' => [
251286
self::connection(OCI8Connection::class, 'OCI8'),
252287
2290,
@@ -265,6 +300,15 @@ public function testCreatesBaseDatabaseExceptionForNonConstraintError(): void
265300
$this->assertNotInstanceOf(ConstraintViolationException::class, $exception);
266301
}
267302

303+
public function testCreatesBaseDatabaseExceptionForMySQLiNonConstraint4025(): void
304+
{
305+
$exception = self::connection(MySQLiConnection::class, 'MySQLi')
306+
->createDatabaseException('InnoDB autoextend size is out of range.', 4025);
307+
308+
$this->assertInstanceOf(DatabaseException::class, $exception);
309+
$this->assertNotInstanceOf(ConstraintViolationException::class, $exception);
310+
}
311+
268312
#[DataProvider('provideCreatesBaseDatabaseExceptionForSqlsrvConstraintVendorCodeWithNonConstraintSqlstate')]
269313
public function testCreatesBaseDatabaseExceptionForSqlsrvConstraintVendorCodeWithNonConstraintSqlstate(string $code): void
270314
{

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

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,12 @@
1313

1414
namespace CodeIgniter\Database\Live;
1515

16+
use CodeIgniter\Database\Exceptions\ForeignKeyConstraintViolationException;
1617
use CodeIgniter\Database\Exceptions\NotNullConstraintViolationException;
18+
use CodeIgniter\Database\Forge;
1719
use CodeIgniter\Test\CIUnitTestCase;
1820
use CodeIgniter\Test\DatabaseTestTrait;
21+
use Config\Database;
1922
use PHPUnit\Framework\Attributes\Group;
2023
use Tests\Support\Database\Seeds\CITestSeeder;
2124

@@ -27,13 +30,19 @@ final class ConstraintViolationExceptionTest extends CIUnitTestCase
2730
{
2831
use DatabaseTestTrait;
2932

30-
protected $refresh = true;
31-
protected $seed = CITestSeeder::class;
33+
private ?Forge $forge = null;
34+
protected $refresh = true;
35+
protected $seed = CITestSeeder::class;
3236

3337
protected function tearDown(): void
3438
{
3539
$this->enableDBDebug();
3640

41+
if ($this->forge instanceof Forge) {
42+
$this->forge->dropTable('cv_child', true);
43+
$this->forge->dropTable('cv_parent', true);
44+
}
45+
3746
parent::tearDown();
3847
}
3948

@@ -50,6 +59,30 @@ public function testThrowsNotNullConstraintViolationExceptionWithDebugEnabled():
5059
]);
5160
}
5261

62+
public function testThrowsNotNullConstraintViolationExceptionForUpdateWithDebugEnabled(): void
63+
{
64+
$this->enableDBDebug();
65+
66+
$this->expectException(NotNullConstraintViolationException::class);
67+
68+
$this->db->table('user')
69+
->where('id', 1)
70+
->update(['name' => null]);
71+
}
72+
73+
public function testThrowsForeignKeyConstraintViolationExceptionWithDebugEnabled(): void
74+
{
75+
$this->enableDBDebug();
76+
$this->createForeignKeyTables();
77+
78+
$this->expectException(ForeignKeyConstraintViolationException::class);
79+
80+
$this->db->table('cv_child')->insert([
81+
'id' => 1,
82+
'parent_id' => 999,
83+
]);
84+
}
85+
5386
public function testStoresNotNullConstraintViolationExceptionWithDebugDisabled(): void
5487
{
5588
$this->disableDBDebug();
@@ -63,4 +96,35 @@ public function testStoresNotNullConstraintViolationExceptionWithDebugDisabled()
6396
$this->assertFalse($result);
6497
$this->assertInstanceOf(NotNullConstraintViolationException::class, $this->db->getLastException());
6598
}
99+
100+
private function createForeignKeyTables(): void
101+
{
102+
$this->forge = Database::forge($this->DBGroup);
103+
104+
$this->forge->dropTable('cv_child', true);
105+
$this->forge->dropTable('cv_parent', true);
106+
107+
$this->forge->addField([
108+
'id' => ['type' => 'INTEGER', 'constraint' => 3],
109+
]);
110+
$this->forge->addKey('id', true);
111+
$this->forge->createTable('cv_parent');
112+
113+
$this->forge->addField([
114+
'id' => ['type' => 'INTEGER', 'constraint' => 3],
115+
'parent_id' => ['type' => 'INTEGER', 'constraint' => 3],
116+
]);
117+
$this->forge->addKey('id', true);
118+
$this->forge->addForeignKey(
119+
'parent_id',
120+
'cv_parent',
121+
'id',
122+
'',
123+
'',
124+
$this->db->DBDriver === 'SQLite3' ? '' : 'fk_cv_child_parent',
125+
);
126+
$this->forge->createTable('cv_child');
127+
128+
$this->db->enableForeignKeyChecks();
129+
}
66130
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
<?php
22

3-
use CodeIgniter\Database\Exceptions\ConstraintViolationException;
3+
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
44

55
$inserted = $db->table('users')->insert(['email' => 'duplicate@example.com']);
66

7-
if (! $inserted && $db->getLastException() instanceof ConstraintViolationException) {
8-
// Handle the constraint violation.
7+
if (! $inserted && $db->getLastException() instanceof UniqueConstraintViolationException) {
8+
// Handle duplicate key violation.
99
}

0 commit comments

Comments
 (0)