Skip to content

Commit ef8944a

Browse files
committed
refactor: refine SQLSRV skip locked support
- Avoid incompatible SQLSRV table hints for lockForUpdate()->skipLocked() - Add live SQLSRV coverage for skip locked execution - Document pessimistic lock and wait modifier driver support - Clarify that existence/count probes do not apply locking modifiers Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent fcc5a4d commit ef8944a

5 files changed

Lines changed: 155 additions & 40 deletions

File tree

‎system/Database/SQLSRV/Builder.php‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,9 @@
3333
*/
3434
class Builder extends BaseBuilder
3535
{
36-
private const LOCK_FOR_UPDATE_HINTS = ['UPDLOCK', 'ROWLOCK'];
37-
private const SHARED_LOCK_HINTS = ['HOLDLOCK', 'ROWLOCK'];
36+
private const LOCK_FOR_UPDATE_HINTS = ['UPDLOCK', 'ROWLOCK'];
37+
private const LOCK_FOR_UPDATE_SKIP_LOCKED_HINTS = ['UPDLOCK', 'READCOMMITTEDLOCK', 'READPAST'];
38+
private const SHARED_LOCK_HINTS = ['HOLDLOCK', 'ROWLOCK'];
3839

3940
/**
4041
* ORDER BY random keyword
@@ -97,9 +98,11 @@ protected function _fromTables(): string
9798
private function compileTableLockHint(): string
9899
{
99100
$hints = match ($this->QBSelectLock) {
100-
self::SELECT_LOCK_FOR_UPDATE => self::LOCK_FOR_UPDATE_HINTS,
101-
self::SELECT_LOCK_SHARED => self::SHARED_LOCK_HINTS,
102-
default => [],
101+
self::SELECT_LOCK_FOR_UPDATE => $this->QBSelectLockWait === self::SELECT_LOCK_WAIT_SKIP_LOCKED
102+
? self::LOCK_FOR_UPDATE_SKIP_LOCKED_HINTS
103+
: self::LOCK_FOR_UPDATE_HINTS,
104+
self::SELECT_LOCK_SHARED => self::SHARED_LOCK_HINTS,
105+
default => [],
103106
};
104107

105108
if ($hints === []) {
@@ -108,12 +111,6 @@ private function compileTableLockHint(): string
108111

109112
if ($this->QBSelectLockWait === self::SELECT_LOCK_WAIT_NOWAIT) {
110113
$hints[] = 'NOWAIT';
111-
} elseif (
112-
$this->QBSelectLock === self::SELECT_LOCK_FOR_UPDATE
113-
&& $this->QBSelectLockWait === self::SELECT_LOCK_WAIT_SKIP_LOCKED
114-
) {
115-
$hints[] = 'READCOMMITTEDLOCK';
116-
$hints[] = 'READPAST';
117114
}
118115

119116
return ' WITH (' . implode(', ', $hints) . ')';

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ public function testExistsWithSQLSRVDoesNotUseOrderByOrLockForUpdate(): void
117117
$expectedSQL = 'SELECT 1 FROM "test"."dbo"."jobs" WHERE "id" > :id: ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY ';
118118

119119
$this->assertSameSql($expectedSQL, $answer);
120-
$this->assertSameSql('SELECT * FROM "test"."dbo"."jobs" WITH (UPDLOCK, ROWLOCK, READCOMMITTEDLOCK, READPAST) WHERE "id" > 3 ORDER BY "id" DESC', $builder->getCompiledSelect(false));
120+
$this->assertSameSql('SELECT * FROM "test"."dbo"."jobs" WITH (UPDLOCK, READCOMMITTEDLOCK, READPAST) WHERE "id" > 3 ORDER BY "id" DESC', $builder->getCompiledSelect(false));
121121
}
122122

123123
public function testExistsWithSQLSRVDoesNotUseOrderByOrSharedLock(): void

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -909,7 +909,7 @@ public function testLockForUpdateWithSQLSRVSkipLocked(): void
909909

910910
$builder = new SQLSRVBuilder('users', $this->db);
911911

912-
$expected = 'SELECT * FROM "test"."dbo"."users" WITH (UPDLOCK, ROWLOCK, READCOMMITTEDLOCK, READPAST)';
912+
$expected = 'SELECT * FROM "test"."dbo"."users" WITH (UPDLOCK, READCOMMITTEDLOCK, READPAST)';
913913

914914
$this->assertSameSql($expected, $builder->lockForUpdate()->skipLocked()->getCompiledSelect());
915915
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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\Database\Live\SQLSRV;
15+
16+
use CodeIgniter\Test\CIUnitTestCase;
17+
use CodeIgniter\Test\DatabaseTestTrait;
18+
use PHPUnit\Framework\Attributes\Group;
19+
use Tests\Support\Database\Seeds\CITestSeeder;
20+
21+
/**
22+
* @internal
23+
*/
24+
#[Group('DatabaseLive')]
25+
final class SelectLockTest extends CIUnitTestCase
26+
{
27+
use DatabaseTestTrait;
28+
29+
protected $refresh = true;
30+
protected $seed = CITestSeeder::class;
31+
32+
protected function setUp(): void
33+
{
34+
parent::setUp();
35+
36+
if ($this->db->DBDriver !== 'SQLSRV') {
37+
$this->markTestSkipped('This test is only for SQLSRV.');
38+
}
39+
}
40+
41+
public function testLockForUpdateSkipLockedExecutes(): void
42+
{
43+
$row = null;
44+
45+
$this->db->transBegin();
46+
47+
try {
48+
$row = $this->db->table('job')
49+
->where('name', 'Developer')
50+
->lockForUpdate()
51+
->skipLocked()
52+
->get()
53+
->getRowArray();
54+
} finally {
55+
$this->db->transRollback();
56+
}
57+
58+
$this->assertIsArray($row);
59+
$this->assertSame('Developer', $row['name']);
60+
}
61+
}

‎user_guide_src/source/database/query_builder.rst‎

Lines changed: 84 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -949,6 +949,75 @@ first parameter.
949949
Pessimistic Locking
950950
********************
951951

952+
.. _query-builder-pessimistic-locking-driver-support:
953+
954+
Driver Support
955+
==============
956+
957+
The following table summarizes Query Builder support for pessimistic locks and
958+
lock-wait modifiers:
959+
960+
.. list-table::
961+
:header-rows: 1
962+
:widths: 38 15 15 15 18 15
963+
964+
* - Query Builder methods
965+
- MySQLi
966+
- Postgre
967+
- OCI8
968+
- SQLSRV
969+
- SQLite3
970+
* - ``lockForUpdate()``
971+
- Yes
972+
- Yes
973+
- Yes
974+
- Yes
975+
- No
976+
* - ``sharedLock()``
977+
- Yes
978+
- Yes
979+
- No
980+
- Yes
981+
- No
982+
* - ``lockForUpdate()->nowait()``
983+
- Yes [1]_
984+
- Yes
985+
- Yes
986+
- Yes
987+
- No
988+
* - ``lockForUpdate()->skipLocked()``
989+
- Yes [2]_
990+
- Yes
991+
- Yes
992+
- Approximate [3]_
993+
- No
994+
* - ``sharedLock()->nowait()``
995+
- No
996+
- Yes
997+
- No
998+
- Yes
999+
- No
1000+
* - ``sharedLock()->skipLocked()``
1001+
- No
1002+
- Yes
1003+
- No
1004+
- No
1005+
- No
1006+
1007+
.. [1] ``NOWAIT`` requires MySQL 8.0.1+ or MariaDB 10.3.0+. CodeIgniter does
1008+
not check the server version before compiling the clause.
1009+
1010+
.. [2] ``SKIP LOCKED`` requires MySQL 8.0.1+ or MariaDB 10.6.0+. CodeIgniter
1011+
does not check the server version before compiling the clause.
1012+
1013+
.. [3] SQLSRV approximates ``skipLocked()`` using SQL Server's
1014+
``READCOMMITTEDLOCK`` and ``READPAST`` table hints. It can still wait on
1015+
locks that ``READPAST`` does not skip, such as page-level locks.
1016+
1017+
.. note:: ``countAllResults()``, ``exists()``, and ``doesntExist()`` do not apply
1018+
pessimistic locks or lock-wait modifiers. Consequently, they report matching
1019+
rows rather than rows currently available for locking.
1020+
9521021
.. _query-builder-shared-lock:
9531022

9541023
Shared Lock
@@ -969,12 +1038,12 @@ Use this method inside a database transaction. Without an explicit transaction,
9691038
the lock is typically released when the ``SELECT`` statement finishes. If the
9701039
same transaction will update the selected rows, use ``lockForUpdate()`` instead.
9711040

972-
This method is supported by the **MySQLi**, **Postgre**, and **SQLSRV**
973-
drivers. Unsupported drivers throw a ``DatabaseException``. ``sharedLock()`` is
974-
not supported with ``union()`` or ``unionAll()``. Some databases restrict which
975-
query shapes can be used with row locking. When CodeIgniter can detect an
976-
unsupported combination, it throws a ``DatabaseException``. See the following
977-
warnings for driver-specific behavior.
1041+
See :ref:`query-builder-pessimistic-locking-driver-support` for supported
1042+
drivers and lock combinations. Unsupported drivers throw a ``DatabaseException``.
1043+
``sharedLock()`` is not supported with ``union()`` or ``unionAll()``. Some
1044+
databases restrict which query shapes can be used with row locking. When
1045+
CodeIgniter can detect an unsupported combination, it throws a
1046+
``DatabaseException``. See the following warnings for driver-specific behavior.
9781047

9791048
.. warning:: MySQLi does not support ``sharedLock()`` with ``fromSubquery()``
9801049
because an outer locking read on a derived table does not lock the underlying
@@ -1011,10 +1080,10 @@ the lock is typically released when the ``SELECT`` statement finishes. The exact
10111080
locking behavior is determined by the database server and transaction isolation
10121081
level.
10131082

1014-
This method is supported by the **MySQLi**, **Postgre**, **OCI8**, and
1015-
**SQLSRV** drivers. Unsupported drivers throw a ``DatabaseException``.
1016-
``lockForUpdate()`` is not supported with ``union()`` or ``unionAll()``.
1017-
Some databases restrict which query shapes can be used with row locking. When
1083+
See :ref:`query-builder-pessimistic-locking-driver-support` for supported
1084+
drivers and lock combinations. Unsupported drivers throw a ``DatabaseException``.
1085+
``lockForUpdate()`` is not supported with ``union()`` or ``unionAll()``. Some
1086+
databases restrict which query shapes can be used with row locking. When
10181087
CodeIgniter can detect an unsupported combination, it throws a
10191088
``DatabaseException``. See the following warnings for driver-specific behavior.
10201089

@@ -1060,18 +1129,10 @@ rows are skipped instead of waited on. This is usually what queue workers want,
10601129
but it is not suitable for general-purpose reads that must see every matching
10611130
row.
10621131

1063-
This method is supported with ``lockForUpdate()`` by the **MySQLi**,
1064-
**Postgre**, **OCI8**, and **SQLSRV** drivers. It is supported with
1065-
``sharedLock()`` by the **Postgre** driver. Unsupported combinations throw a
1132+
See :ref:`query-builder-pessimistic-locking-driver-support` for supported
1133+
drivers and lock combinations. Unsupported combinations throw a
10661134
``DatabaseException``.
10671135

1068-
.. note:: MySQLi support requires a MySQL or MariaDB server version that
1069-
supports ``SKIP LOCKED``.
1070-
1071-
.. warning:: SQLSRV uses SQL Server's ``READCOMMITTEDLOCK`` and ``READPAST``
1072-
table hints for ``lockForUpdate()->skipLocked()``. SQL Server can still wait
1073-
on locks that ``READPAST`` does not skip, such as page-level locks.
1074-
10751136
.. _query-builder-nowait:
10761137

10771138
No Wait
@@ -1095,13 +1156,9 @@ When a row cannot be locked immediately, the database server returns an error
10951156
and CodeIgniter throws a database exception according to the current database
10961157
debug and transaction settings.
10971158

1098-
This method is supported with ``lockForUpdate()`` by the **MySQLi**,
1099-
**Postgre**, **OCI8**, and **SQLSRV** drivers. It is supported with
1100-
``sharedLock()`` by the **Postgre** and **SQLSRV** drivers. Unsupported
1101-
combinations throw a ``DatabaseException``.
1102-
1103-
.. note:: MySQLi support requires a MySQL or MariaDB server version that
1104-
supports ``NOWAIT``.
1159+
See :ref:`query-builder-pessimistic-locking-driver-support` for supported
1160+
drivers and lock combinations. Unsupported combinations throw a
1161+
``DatabaseException``.
11051162

11061163
.. _query-builder-union:
11071164

0 commit comments

Comments
 (0)