Skip to content

Commit f49e1b0

Browse files
committed
feat(database): add query builder lockForUpdate
Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 3a10470 commit f49e1b0

9 files changed

Lines changed: 329 additions & 23 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,13 @@ class BaseBuilder
109109
*/
110110
protected $QBOffset = false;
111111

112+
/**
113+
* QB FOR UPDATE flag
114+
*
115+
* @var bool
116+
*/
117+
protected $QBLockForUpdate = false;
118+
112119
/**
113120
* QB ORDER BY data
114121
*
@@ -1619,6 +1626,16 @@ public function limit(?int $value = null, ?int $offset = 0)
16191626
return $this;
16201627
}
16211628

1629+
/**
1630+
* Locks the selected rows for update.
1631+
*/
1632+
public function lockForUpdate(): static
1633+
{
1634+
$this->QBLockForUpdate = true;
1635+
1636+
return $this;
1637+
}
1638+
16221639
/**
16231640
* Sets the OFFSET value
16241641
*
@@ -1800,20 +1817,26 @@ public function countAllResults(bool $reset = true)
18001817
}
18011818

18021819
// We cannot use a LIMIT when getting the single row COUNT(*) result
1803-
$limit = $this->QBLimit;
1820+
$limit = $this->QBLimit;
1821+
$lockForUpdate = $this->QBLockForUpdate;
18041822

1805-
$this->QBLimit = false;
1823+
$this->QBLimit = false;
1824+
$this->QBLockForUpdate = false;
18061825

1807-
if ($this->QBDistinct === true || ! empty($this->QBGroupBy)) {
1808-
// We need to backup the original SELECT in case DBPrefix is used
1809-
$select = $this->QBSelect;
1810-
$sql = $this->countString . $this->db->protectIdentifiers('numrows') . "\nFROM (\n" . $this->compileSelect() . "\n) CI_count_all_results";
1826+
try {
1827+
if ($this->QBDistinct === true || ! empty($this->QBGroupBy)) {
1828+
// We need to backup the original SELECT in case DBPrefix is used
1829+
$select = $this->QBSelect;
1830+
$sql = $this->countString . $this->db->protectIdentifiers('numrows') . "\nFROM (\n" . $this->compileSelect() . "\n) CI_count_all_results";
18111831

1812-
// Restore SELECT part
1813-
$this->QBSelect = $select;
1814-
unset($select);
1815-
} else {
1816-
$sql = $this->compileSelect($this->countString . $this->db->protectIdentifiers('numrows'));
1832+
// Restore SELECT part
1833+
$this->QBSelect = $select;
1834+
unset($select);
1835+
} else {
1836+
$sql = $this->compileSelect($this->countString . $this->db->protectIdentifiers('numrows'));
1837+
}
1838+
} finally {
1839+
$this->QBLockForUpdate = $lockForUpdate;
18171840
}
18181841

18191842
if ($this->testMode) {
@@ -3158,9 +3181,19 @@ protected function compileSelect($selectOverride = false): string
31583181
$sql = $this->_limit($sql . "\n");
31593182
}
31603183

3184+
$sql .= $this->compileLockForUpdate();
3185+
31613186
return $this->unionInjection($sql);
31623187
}
31633188

3189+
/**
3190+
* Compile the SELECT lock clause.
3191+
*/
3192+
protected function compileLockForUpdate(): string
3193+
{
3194+
return $this->QBLockForUpdate ? "\nFOR UPDATE" : '';
3195+
}
3196+
31643197
/**
31653198
* Checks if the ignore option is supported by
31663199
* the Database Driver for the specific statement.
@@ -3468,17 +3501,18 @@ protected function resetRun(array $qbResetItems)
34683501
protected function resetSelect()
34693502
{
34703503
$this->resetRun([
3471-
'QBSelect' => [],
3472-
'QBJoin' => [],
3473-
'QBWhere' => [],
3474-
'QBGroupBy' => [],
3475-
'QBHaving' => [],
3476-
'QBOrderBy' => [],
3477-
'QBNoEscape' => [],
3478-
'QBDistinct' => false,
3479-
'QBLimit' => false,
3480-
'QBOffset' => false,
3481-
'QBUnion' => [],
3504+
'QBSelect' => [],
3505+
'QBJoin' => [],
3506+
'QBWhere' => [],
3507+
'QBGroupBy' => [],
3508+
'QBHaving' => [],
3509+
'QBOrderBy' => [],
3510+
'QBNoEscape' => [],
3511+
'QBDistinct' => false,
3512+
'QBLimit' => false,
3513+
'QBOffset' => false,
3514+
'QBLockForUpdate' => false,
3515+
'QBUnion' => [],
34823516
]);
34833517

34843518
if ($this->db instanceof BaseConnection) {

‎system/Database/OCI8/Builder.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,18 @@ protected function _limit(string $sql, bool $offsetIgnore = false): string
213213
return $sql . ' OFFSET ' . $offset . ' ROWS FETCH NEXT ' . $this->QBLimit . ' ROWS ONLY';
214214
}
215215

216+
/**
217+
* Compile the SELECT lock clause.
218+
*/
219+
protected function compileLockForUpdate(): string
220+
{
221+
if ($this->QBLockForUpdate && ($this->QBLimit !== false || $this->QBOffset)) {
222+
throw new DatabaseException('OCI8 does not support lockForUpdate() with limit() or offset().');
223+
}
224+
225+
return parent::compileLockForUpdate();
226+
}
227+
216228
/**
217229
* Generates a platform-specific batch update string from the supplied data
218230
*/

‎system/Database/SQLSRV/Builder.php‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
*/
3030
class Builder extends BaseBuilder
3131
{
32+
private const LOCK_FOR_UPDATE_HINT = ' WITH (UPDLOCK, ROWLOCK)';
33+
3234
/**
3335
* ORDER BY random keyword
3436
*
@@ -72,7 +74,17 @@ protected function _fromTables(): string
7274
$from = [];
7375

7476
foreach ($this->QBFrom as $value) {
75-
$from[] = str_starts_with($value, '(SELECT') ? $value : $this->getFullName($value);
77+
if (str_starts_with($value, '(SELECT')) {
78+
if ($this->QBLockForUpdate) {
79+
throw new DatabaseException('SQLSRV does not support lockForUpdate() on subqueries.');
80+
}
81+
82+
$from[] = $value;
83+
84+
continue;
85+
}
86+
87+
$from[] = $this->getFullName($value) . ($this->QBLockForUpdate ? self::LOCK_FOR_UPDATE_HINT : '');
7688
}
7789

7890
return implode(', ', $from);
@@ -633,9 +645,23 @@ protected function compileSelect($selectOverride = false): string
633645
$sql = $this->_limit($sql . "\n");
634646
}
635647

648+
$sql .= $this->compileLockForUpdate();
649+
636650
return $this->unionInjection($sql);
637651
}
638652

653+
/**
654+
* Compile the SELECT lock clause.
655+
*/
656+
protected function compileLockForUpdate(): string
657+
{
658+
if ($this->QBLockForUpdate && $this->QBFrom === []) {
659+
throw new DatabaseException('SQLSRV does not support lockForUpdate() without a FROM table.');
660+
}
661+
662+
return '';
663+
}
664+
639665
/**
640666
* Compiles the select statement based on the other functions called
641667
* and runs the query

‎system/Database/SQLite3/Builder.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,18 @@ class Builder extends BaseBuilder
5555
'insert' => 'OR IGNORE',
5656
];
5757

58+
/**
59+
* Compile the SELECT lock clause.
60+
*/
61+
protected function compileLockForUpdate(): string
62+
{
63+
if ($this->QBLockForUpdate) {
64+
throw new DatabaseException('SQLite3 does not support lockForUpdate().');
65+
}
66+
67+
return '';
68+
}
69+
5870
/**
5971
* Replace statement
6072
*

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

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

1616
use CodeIgniter\Database\BaseBuilder;
17+
use CodeIgniter\Database\SQLSRV\Builder as SQLSRVBuilder;
1718
use CodeIgniter\Test\CIUnitTestCase;
1819
use CodeIgniter\Test\Mock\MockConnection;
1920
use PHPUnit\Framework\Attributes\Group;
@@ -55,6 +56,34 @@ public function testCountAllResults(): void
5556
$this->assertSame($expectedSQL, str_replace("\n", ' ', $answer));
5657
}
5758

59+
public function testCountAllResultsDoesNotUseLockForUpdate(): void
60+
{
61+
$builder = new BaseBuilder('jobs', $this->db);
62+
$builder->testMode();
63+
64+
$answer = $builder->where('id >', 3)->lockForUpdate()->countAllResults(false);
65+
66+
$expectedSQL = 'SELECT COUNT(*) AS "numrows" FROM "jobs" WHERE "id" > :id:';
67+
68+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $answer));
69+
$this->assertSame('SELECT * FROM "jobs" WHERE "id" > 3 FOR UPDATE', str_replace("\n", ' ', $builder->getCompiledSelect(false)));
70+
}
71+
72+
public function testCountAllResultsWithSQLSRVDoesNotUseLockForUpdate(): void
73+
{
74+
$this->db = new MockConnection(['DBDriver' => 'SQLSRV', 'database' => 'test', 'schema' => 'dbo']);
75+
76+
$builder = new SQLSRVBuilder('jobs', $this->db);
77+
$builder->testMode();
78+
79+
$answer = $builder->where('id >', 3)->lockForUpdate()->countAllResults(false);
80+
81+
$expectedSQL = 'SELECT COUNT(*) AS "numrows" FROM "test"."dbo"."jobs" WHERE "id" > :id:';
82+
83+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $answer));
84+
$this->assertSame('SELECT * FROM "test"."dbo"."jobs" WITH (UPDLOCK, ROWLOCK) WHERE "id" > 3', str_replace("\n", ' ', $builder->getCompiledSelect(false)));
85+
}
86+
5887
public function testCountAllResultsWithGroupBy(): void
5988
{
6089
$builder = new BaseBuilder('jobs', $this->db);

0 commit comments

Comments
 (0)