Skip to content

Commit 41d5fe4

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

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
@@ -110,6 +110,13 @@ class BaseBuilder
110110
*/
111111
protected $QBOffset = false;
112112

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

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

18031820
// We cannot use a LIMIT when getting the single row COUNT(*) result
1804-
$limit = $this->QBLimit;
1821+
$limit = $this->QBLimit;
1822+
$lockForUpdate = $this->QBLockForUpdate;
18051823

1806-
$this->QBLimit = false;
1824+
$this->QBLimit = false;
1825+
$this->QBLockForUpdate = false;
18071826

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

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

18201843
if ($this->testMode) {
@@ -3223,9 +3246,19 @@ protected function compileSelect($selectOverride = false): string
32233246
$sql = $this->_limit($sql . "\n");
32243247
}
32253248

3249+
$sql .= $this->compileLockForUpdate();
3250+
32263251
return $this->unionInjection($sql);
32273252
}
32283253

3254+
/**
3255+
* Compile the SELECT lock clause.
3256+
*/
3257+
protected function compileLockForUpdate(): string
3258+
{
3259+
return $this->QBLockForUpdate ? "\nFOR UPDATE" : '';
3260+
}
3261+
32293262
/**
32303263
* Checks if the ignore option is supported by
32313264
* the Database Driver for the specific statement.
@@ -3533,17 +3566,18 @@ protected function resetRun(array $qbResetItems)
35333566
protected function resetSelect()
35343567
{
35353568
$this->resetRun([
3536-
'QBSelect' => [],
3537-
'QBJoin' => [],
3538-
'QBWhere' => [],
3539-
'QBGroupBy' => [],
3540-
'QBHaving' => [],
3541-
'QBOrderBy' => [],
3542-
'QBNoEscape' => [],
3543-
'QBDistinct' => false,
3544-
'QBLimit' => false,
3545-
'QBOffset' => false,
3546-
'QBUnion' => [],
3569+
'QBSelect' => [],
3570+
'QBJoin' => [],
3571+
'QBWhere' => [],
3572+
'QBGroupBy' => [],
3573+
'QBHaving' => [],
3574+
'QBOrderBy' => [],
3575+
'QBNoEscape' => [],
3576+
'QBDistinct' => false,
3577+
'QBLimit' => false,
3578+
'QBOffset' => false,
3579+
'QBLockForUpdate' => false,
3580+
'QBUnion' => [],
35473581
]);
35483582

35493583
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
@@ -33,6 +33,8 @@
3333
*/
3434
class Builder extends BaseBuilder
3535
{
36+
private const LOCK_FOR_UPDATE_HINT = ' WITH (UPDLOCK, ROWLOCK)';
37+
3638
/**
3739
* ORDER BY random keyword
3840
*
@@ -76,7 +78,17 @@ protected function _fromTables(): string
7678
$from = [];
7779

7880
foreach ($this->QBFrom as $value) {
79-
$from[] = str_starts_with($value, '(SELECT') ? $value : $this->getFullName($value);
81+
if (str_starts_with($value, '(SELECT')) {
82+
if ($this->QBLockForUpdate) {
83+
throw new DatabaseException('SQLSRV does not support lockForUpdate() on subqueries.');
84+
}
85+
86+
$from[] = $value;
87+
88+
continue;
89+
}
90+
91+
$from[] = $this->getFullName($value) . ($this->QBLockForUpdate ? self::LOCK_FOR_UPDATE_HINT : '');
8092
}
8193

8294
return implode(', ', $from);
@@ -677,9 +689,23 @@ protected function compileSelect($selectOverride = false): string
677689
$sql = $this->_limit($sql . "\n");
678690
}
679691

692+
$sql .= $this->compileLockForUpdate();
693+
680694
return $this->unionInjection($sql);
681695
}
682696

697+
/**
698+
* Compile the SELECT lock clause.
699+
*/
700+
protected function compileLockForUpdate(): string
701+
{
702+
if ($this->QBLockForUpdate && $this->QBFrom === []) {
703+
throw new DatabaseException('SQLSRV does not support lockForUpdate() without a FROM table.');
704+
}
705+
706+
return '';
707+
}
708+
683709
/**
684710
* Compiles the select statement based on the other functions called
685711
* 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)