Skip to content

Commit 6414157

Browse files
committed
feat(model): add locked row callback helper
- add withLockedRow() for running a callback with a row locked for update - bypass find callbacks for the locked reload while preserving normal callback behavior inside the callback - clean up model state when the locked lookup fails - document transaction, constraint, and driver-lock behavior - add focused unit and live model coverage Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 18ee79c commit 6414157

6 files changed

Lines changed: 497 additions & 0 deletions

File tree

‎system/Model.php‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
use Config\Feature;
3333
use Generator;
3434
use stdClass;
35+
use Throwable;
3536

3637
/**
3738
* The Model class extends BaseModel and provides additional
@@ -573,6 +574,28 @@ public function doesntExist(bool $reset = true, bool $test = false)
573574
return $this->builder()->testMode($test)->doesntExist($reset);
574575
}
575576

577+
/**
578+
* Runs the callback with a row reloaded inside a transaction and locked for update.
579+
*
580+
* @template TReturn
581+
*
582+
* @param callable(object|row_array, static): TReturn $callback
583+
*
584+
* @return false|TReturn|null
585+
*/
586+
public function withLockedRow(int|string $id, callable $callback): mixed
587+
{
588+
return $this->db->transaction(function () use ($id, $callback): mixed {
589+
$row = $this->findLockedRow($id);
590+
591+
if ($row === null) {
592+
return null;
593+
}
594+
595+
return $callback($row, $this);
596+
});
597+
}
598+
576599
/**
577600
* Applies the Model soft-delete constraint before terminal Builder operations.
578601
*/
@@ -590,6 +613,30 @@ private function prepareSoftDeleteQuery(bool $reset): void
590613
: ($this->useSoftDeletes ? false : $this->useSoftDeletes);
591614
}
592615

616+
/**
617+
* Reloads a row with a database lock, without allowing find callbacks to short-circuit it.
618+
*/
619+
private function findLockedRow(int|string $id): mixed
620+
{
621+
$builder = $this->builder();
622+
$tempAllowCallbacks = $this->tempAllowCallbacks;
623+
$this->tempAllowCallbacks = false;
624+
625+
try {
626+
$builder->lockForUpdate();
627+
628+
return $this->find($id);
629+
} catch (Throwable $e) {
630+
$this->builder = null;
631+
$this->tempReturnType = $this->returnType;
632+
$this->tempUseSoftDeletes = $this->useSoftDeletes;
633+
634+
throw $e;
635+
} finally {
636+
$this->tempAllowCallbacks = $tempAllowCallbacks;
637+
}
638+
}
639+
593640
/**
594641
* Iterates over the result set in chunks of the specified size.
595642
*
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
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\Models;
15+
16+
use PHPUnit\Framework\Attributes\Group;
17+
use RuntimeException;
18+
use Tests\Support\Models\EventModel;
19+
use Tests\Support\Models\UserModel;
20+
21+
/**
22+
* @internal
23+
*/
24+
#[Group('DatabaseLive')]
25+
final class WithLockedRowModelTest extends LiveModelTestCase
26+
{
27+
protected function setUp(): void
28+
{
29+
parent::setUp();
30+
31+
if ($this->db->DBDriver === 'SQLite3') {
32+
$this->markTestSkipped('SQLite3 does not support lockForUpdate().');
33+
}
34+
}
35+
36+
public function testWithLockedRowReturnsCallbackResult(): void
37+
{
38+
$inTransaction = false;
39+
$model = $this->createModel(UserModel::class);
40+
41+
$result = $model->withLockedRow(1, static function (object $user, UserModel $model) use (&$inTransaction): string {
42+
$inTransaction = $model->db->inTransaction();
43+
44+
return $user->email;
45+
});
46+
47+
$this->assertSame('derek@world.com', $result);
48+
$this->assertTrue($inTransaction);
49+
$this->assertFalse($this->db->inTransaction());
50+
}
51+
52+
public function testWithLockedRowDoesNotRunCallbackWhenRowIsMissing(): void
53+
{
54+
$callbackRan = false;
55+
$model = $this->createModel(UserModel::class);
56+
57+
$result = $model->withLockedRow(999, static function () use (&$callbackRan): void {
58+
$callbackRan = true;
59+
});
60+
61+
$this->assertNull($result);
62+
$this->assertFalse($callbackRan);
63+
}
64+
65+
public function testWithLockedRowAppliesExistingQueryConstraints(): void
66+
{
67+
$model = $this->createModel(UserModel::class);
68+
69+
$result = $model->where('country', 'CA')->withLockedRow(1, static fn (): string => 'locked');
70+
71+
$this->assertNull($result);
72+
}
73+
74+
public function testWithLockedRowRespectsSoftDeletes(): void
75+
{
76+
$model = $this->createModel(UserModel::class);
77+
$model->delete(1);
78+
79+
$result = $model->withLockedRow(1, static fn (): string => 'locked');
80+
81+
$this->assertNull($result);
82+
}
83+
84+
public function testWithLockedRowCanIncludeSoftDeletedRows(): void
85+
{
86+
$model = $this->createModel(UserModel::class);
87+
$model->delete(1);
88+
89+
$result = $model->withDeleted()->withLockedRow(1, static fn (object $user): string => $user->email);
90+
91+
$this->assertSame('derek@world.com', $result);
92+
}
93+
94+
public function testWithLockedRowRollsBackWhenCallbackThrows(): void
95+
{
96+
$model = $this->createModel(UserModel::class);
97+
98+
try {
99+
$model->withLockedRow(1, static function (object $user, UserModel $model): void {
100+
$model->update($user->id, ['name' => 'Rolled Back']);
101+
102+
throw new RuntimeException('Stop transaction.');
103+
});
104+
} catch (RuntimeException $e) {
105+
$this->assertSame('Stop transaction.', $e->getMessage());
106+
}
107+
108+
$this->seeInDatabase('user', [
109+
'id' => 1,
110+
'name' => 'Derek Jones',
111+
]);
112+
}
113+
114+
public function testWithLockedRowBypassesFindCallbacks(): void
115+
{
116+
$model = $this->createModel(EventModel::class);
117+
$model->beforeFindReturnData = true;
118+
119+
$result = $model->withLockedRow(1, static fn (array $user): string => $user['email']);
120+
121+
$this->assertSame('derek@world.com', $result);
122+
$this->assertFalse($model->hasToken('beforeFind'));
123+
$this->assertFalse($model->hasToken('afterFind'));
124+
}
125+
126+
public function testWithLockedRowRestoresCallbacksBeforeRunningCallback(): void
127+
{
128+
$model = $this->createModel(EventModel::class);
129+
130+
$model->withLockedRow(1, static function (array $user, EventModel $model): void {
131+
$model->update($user['id'], ['name' => 'Locked Update']);
132+
});
133+
134+
$this->assertTrue($model->hasToken('beforeUpdate'));
135+
$this->assertTrue($model->hasToken('afterUpdate'));
136+
}
137+
138+
public function testWithLockedRowDoesNotAddLimitToLockedLookup(): void
139+
{
140+
$model = $this->createModel(UserModel::class);
141+
142+
$model->withLockedRow(1, static fn (): string => 'locked');
143+
144+
$sql = strtoupper((string) $this->db->getLastQuery());
145+
146+
$this->assertStringNotContainsString(' LIMIT ', $sql);
147+
$this->assertStringNotContainsString(' OFFSET ', $sql);
148+
}
149+
}

0 commit comments

Comments
 (0)