Skip to content

Commit f581e83

Browse files
chubes4JanJakes
andauthored
Allow configuring the SQLite busy timeout with SQLITE_BUSY_TIMEOUT (#558)
## Summary SQLite lets only one connection write at a time. When another connection holds the lock, SQLite waits up to the **busy timeout** and then fails with `SQLSTATE[HY000]: General error: 5 database is locked`. `WP_SQLite_Connection` already sets a busy timeout of 10 seconds, but neither `WP_MySQL_On_SQLite` nor the plugin let you change it. This shows up on hosts that serve one site from several PHP processes. Writes take turns without trouble, but a request that holds a write transaction past the timeout makes every other writer fail instead of wait. WordPress Studio runs a pool of native PHP workers per site and hits this case: a long transaction in one worker fails a concurrent `wpdb->insert()` in another, on GET and POST requests alike. A development host would rather wait longer than show the user an error. ## Changes The busy timeout can now be configured, always in **milliseconds**, the unit SQLite uses for it: - **`SQLITE_BUSY_TIMEOUT` constant.** The plugin reads an optional `SQLITE_BUSY_TIMEOUT` constant from `wp-config.php`, the same way it reads `SQLITE_JOURNAL_MODE`. For example, `define( 'SQLITE_BUSY_TIMEOUT', 60000 );` waits up to 60 seconds, and `0` fails immediately. - **`sqlite_busy_timeout` driver option.** `WP_MySQL_On_SQLite` accepts a `sqlite_busy_timeout` option and passes it to the connection. Like `sqlite_journal_mode` and `sqlite_synchronous`, it is named after its SQLite PRAGMA and takes the same values. Without it, the default of **10000 ms** applies, as before. - **Validation.** A value that is not an integer from 0 to 2147483647 throws an `InvalidArgumentException`, like an invalid journal mode. A mistake such as an empty value can no longer silently turn into "don't wait at all". - **Renamed connection option.** The internal `WP_SQLite_Connection` option `timeout` (seconds) is now `busy_timeout` (milliseconds), and `DEFAULT_SQLITE_TIMEOUT` is now `DEFAULT_SQLITE_BUSY_TIMEOUT`. The connection sets the timeout with `PRAGMA busy_timeout` instead of `PDO::ATTR_TIMEOUT`, which only accepts whole seconds and overflows to no wait at all for very large values. The constant isn't in the plugin readme yet. Like `SQLITE_JOURNAL_MODE`, it will be documented with the other configuration options later. ## Testing End to end in WordPress Studio, with the first version of this PR (which used seconds) applied to the bundled plugin: one request held a write transaction for 45s while another worker wrote. | | Second writer | |---|---| | Default timeout | fails after about 19s, "database is locked" | | `SQLITE_BUSY_TIMEOUT` set to 60 seconds | waits 44s, then succeeds (GET and POST) | Closes #548. --- AI assistance: the Pi coding agent, run by Homeboy, implemented the change and tests (served model not recorded). Claude Opus via Pi reviewed it, ran the end-to-end check in Studio, and wrote this description. Chris Huber reviewed before opening. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * SQLite lock-wait duration can now be configured with `sqlite_busy_timeout`, in milliseconds. The default is 10,000 milliseconds, and the setting is applied when connecting to or initializing the database. * Values must be whole numbers from 0 to 2,147,483,647; invalid values produce an error. * **Tests** * Added coverage for timeout configuration, invalid values, and how long writes wait when another connection holds a lock. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Jan Jakeš <jan@jakes.pro>
1 parent c7d6963 commit f581e83

8 files changed

Lines changed: 168 additions & 17 deletions

File tree

‎packages/mysql-on-sqlite/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ version and configuring the SQLite connection:
7676
| --- | --- | --- |
7777
| `mysql_version` | MySQL version to emulate, represented as an integer | `80038` |
7878
| `sqlite_pdo` | Existing PDO SQLite connection | A new connection for `path` |
79+
| `sqlite_busy_timeout` | SQLite busy timeout in milliseconds | `10000` |
7980
| `sqlite_journal_mode` | SQLite journal mode | `WAL` |
8081
| `sqlite_synchronous` | SQLite synchronous setting | `NORMAL` in WAL mode; otherwise the SQLite default |
8182

‎packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,11 +795,13 @@ class WP_MySQL_On_SQLite extends PDO {
795795
*
796796
* @type int $mysql_version Optional. MySQL version to emulate. Default 80038.
797797
* @type PDO|null $sqlite_pdo Optional. Existing PDO SQLite connection.
798+
* @type int|null $sqlite_busy_timeout Optional. SQLite busy timeout in milliseconds.
799+
* Default 10000.
798800
* @type string|null $sqlite_journal_mode Optional. SQLite journal mode. Default 'WAL'.
799801
* @type string|int|null $sqlite_synchronous Optional. SQLite synchronous setting.
800802
* }
801803
*
802-
* @throws InvalidArgumentException When the MySQL version is invalid.
804+
* @throws InvalidArgumentException When the MySQL version or an SQLite option is invalid.
803805
* @throws WP_MySQL_On_SQLite_Exception When the driver initialization fails.
804806
*/
805807
public function __construct(
@@ -876,6 +878,7 @@ function ( $key ) {
876878
}
877879

878880
$connection_options = array(
881+
'busy_timeout' => $options['sqlite_busy_timeout'] ?? null,
879882
'journal_mode' => $options['sqlite_journal_mode'] ?? null,
880883
'synchronous' => $options['sqlite_synchronous'] ?? null,
881884
'pdo_options' => $connection_pdo_options,

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-connection.php‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
*/
1818
class WP_SQLite_Connection {
1919
/**
20-
* The default timeout in seconds for SQLite to wait for a writable lock.
20+
* The default time in milliseconds for SQLite to wait for a lock.
2121
*/
22-
const DEFAULT_SQLITE_TIMEOUT = 10;
22+
const DEFAULT_SQLITE_BUSY_TIMEOUT = 10000;
2323

2424
/**
2525
* The supported SQLite journal modes.
@@ -76,8 +76,8 @@ class WP_SQLite_Connection {
7676
* Must be set when PDO instance is not provided.
7777
* @type PDO|null $pdo Optional. PDO instance with SQLite connection.
7878
* If not provided, a new PDO instance will be created.
79-
* @type int|null $timeout Optional. SQLite timeout in seconds.
80-
* The time to wait for a writable lock.
79+
* @type int|null $busy_timeout Optional. SQLite busy timeout in milliseconds.
80+
* The time to wait for a lock. Defaults to 10000.
8181
* @type string|null $journal_mode Optional. SQLite journal mode. Defaults to WAL.
8282
* @type string|int|null $synchronous Optional. SQLite synchronous setting. Defaults to
8383
* NORMAL when the effective journal mode is WAL.
@@ -107,13 +107,14 @@ public function __construct( array $options ) {
107107
// Throw exceptions on error.
108108
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
109109

110-
// Configure SQLite timeout.
111-
if ( isset( $options['timeout'] ) && is_int( $options['timeout'] ) ) {
112-
$timeout = $options['timeout'];
113-
} else {
114-
$timeout = self::DEFAULT_SQLITE_TIMEOUT;
110+
// Configure SQLite busy timeout. SQLite stores it as a 32-bit signed integer.
111+
$busy_timeout = $options['busy_timeout'] ?? self::DEFAULT_SQLITE_BUSY_TIMEOUT;
112+
if ( ! is_int( $busy_timeout ) || $busy_timeout < 0 || $busy_timeout > 2147483647 ) {
113+
throw new InvalidArgumentException(
114+
'Invalid SQLite busy timeout. It must be an integer from 0 to 2147483647.'
115+
);
115116
}
116-
$this->pdo->setAttribute( PDO::ATTR_TIMEOUT, $timeout );
117+
$this->query( 'PRAGMA busy_timeout = ' . $busy_timeout );
117118

118119
// Configure SQLite journal mode. Default to WAL for best throughput.
119120
$effective_journal_mode = null;

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Concurrency_Tests.php‎

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,11 @@ public function testSetQuerySucceedsWhileAnotherConnectionHoldsWriteLock(): void
133133
// Connection B with zero timeout — any lock conflict fails immediately.
134134
$conn_b = new WP_SQLite_Connection(
135135
array(
136-
'path' => $this->db_path,
137-
'timeout' => 0,
136+
'path' => $this->db_path,
137+
'busy_timeout' => 0,
138138
)
139139
);
140140
$driver_b = $this->create_driver( $conn_b );
141-
$conn_b->get_pdo()->setAttribute( PDO::ATTR_TIMEOUT, 0 );
142141

143142
// SET writes nothing, so it must not contend for the write lock.
144143
$result = $driver_b->query( "SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION'" );
@@ -149,6 +148,20 @@ public function testSetQuerySucceedsWhileAnotherConnectionHoldsWriteLock(): void
149148
}
150149
}
151150

151+
public function testWriteQueryFailsImmediatelyWithZeroBusyTimeoutWhileAnotherConnectionHoldsWriteLock(): void {
152+
$elapsed = $this->measure_write_failure_under_write_lock( 0 );
153+
154+
// Far below the 10 second default.
155+
$this->assertLessThan( 1, $elapsed );
156+
}
157+
158+
public function testWriteQueryWaitsForBusyTimeoutWhileAnotherConnectionHoldsWriteLock(): void {
159+
$elapsed = $this->measure_write_failure_under_write_lock( 200 );
160+
161+
$this->assertGreaterThanOrEqual( 0.2, $elapsed );
162+
$this->assertLessThan( 5, $elapsed );
163+
}
164+
152165
private function assertReadOnlyQuerySucceedsUnderWriteLock( string $query ): void {
153166
// Connection A: set up the database.
154167
$conn_a = new WP_SQLite_Connection( array( 'path' => $this->db_path ) );
@@ -163,12 +176,11 @@ private function assertReadOnlyQuerySucceedsUnderWriteLock( string $query ): voi
163176
// Connection B with zero timeout — any lock conflict fails immediately.
164177
$conn_b = new WP_SQLite_Connection(
165178
array(
166-
'path' => $this->db_path,
167-
'timeout' => 0,
179+
'path' => $this->db_path,
180+
'busy_timeout' => 0,
168181
)
169182
);
170183
$driver_b = $this->create_driver( $conn_b );
171-
$conn_b->get_pdo()->setAttribute( PDO::ATTR_TIMEOUT, 0 );
172184

173185
$result = $driver_b->query( $query );
174186

@@ -178,6 +190,43 @@ private function assertReadOnlyQuerySucceedsUnderWriteLock( string $query ): voi
178190
}
179191
}
180192

193+
/**
194+
* Run a write query while another connection holds the write lock.
195+
*
196+
* @param int $busy_timeout Busy timeout of the writing connection in milliseconds.
197+
* @return float Time in seconds until the write query failed.
198+
*/
199+
private function measure_write_failure_under_write_lock( int $busy_timeout ): float {
200+
// Connection A: set up the database and hold a write transaction.
201+
$conn_a = new WP_SQLite_Connection( array( 'path' => $this->db_path ) );
202+
$driver_a = $this->create_driver( $conn_a );
203+
$driver_a->query( 'CREATE TABLE t (id INT, name VARCHAR(255))' );
204+
$driver_a->query( "INSERT INTO t VALUES (1, 'Alice')" );
205+
206+
// Simulate another PHP process holding a write transaction.
207+
$conn_a->get_pdo()->exec( 'BEGIN IMMEDIATE' );
208+
209+
try {
210+
$driver_b = new WP_MySQL_On_SQLite(
211+
sprintf( 'mysql-on-sqlite:path=%s;dbname=wp', $this->db_path ),
212+
null,
213+
null,
214+
array( 'sqlite_busy_timeout' => $busy_timeout )
215+
);
216+
217+
$start = microtime( true );
218+
try {
219+
$driver_b->query( "INSERT INTO t VALUES (2, 'Bob')" );
220+
} catch ( PDOException $e ) {
221+
$this->assertStringContainsString( 'database is locked', $e->getMessage() );
222+
return microtime( true ) - $start;
223+
}
224+
$this->fail( 'The write query did not fail while another connection held the write lock.' );
225+
} finally {
226+
$conn_a->get_pdo()->exec( 'ROLLBACK' );
227+
}
228+
}
229+
181230
private function create_in_memory_driver(): WP_MySQL_On_SQLite {
182231
$pdo_class = PHP_VERSION_ID >= 80400 ? Pdo\Sqlite::class : PDO::class;
183232
$pdo = new $pdo_class( 'sqlite::memory:' );
@@ -192,6 +241,7 @@ private function create_driver( WP_SQLite_Connection $connection ): WP_MySQL_On_
192241
null,
193242
array(
194243
'sqlite_pdo' => $connection->get_pdo(),
244+
'sqlite_busy_timeout' => (int) $connection->query( 'PRAGMA busy_timeout' )->fetchColumn(),
195245
'sqlite_journal_mode' => $connection->query( 'PRAGMA journal_mode' )->fetchColumn(),
196246
)
197247
);

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_PDO_API_Tests.php‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,43 @@ public function test_journal_mode_and_synchronous_driver_options(): void {
379379
}
380380
}
381381

382+
public function test_busy_timeout_driver_option(): void {
383+
$driver = new WP_MySQL_On_SQLite(
384+
'mysql-on-sqlite:path=:memory:;dbname=wp',
385+
null,
386+
null,
387+
array(
388+
'sqlite_busy_timeout' => 2500,
389+
)
390+
);
391+
392+
$this->assertSame(
393+
2500,
394+
(int) $driver->get_sqlite_pdo()->query( 'PRAGMA busy_timeout' )->fetchColumn()
395+
);
396+
}
397+
398+
public function test_busy_timeout_defaults_to_the_connection_default(): void {
399+
$driver = new WP_MySQL_On_SQLite( 'mysql-on-sqlite:path=:memory:;dbname=wp' );
400+
401+
$this->assertSame(
402+
WP_SQLite_Connection::DEFAULT_SQLITE_BUSY_TIMEOUT,
403+
(int) $driver->get_sqlite_pdo()->query( 'PRAGMA busy_timeout' )->fetchColumn()
404+
);
405+
}
406+
407+
public function test_rejects_invalid_busy_timeout(): void {
408+
$this->expectException( InvalidArgumentException::class );
409+
$this->expectExceptionMessage( 'Invalid SQLite busy timeout. It must be an integer from 0 to 2147483647.' );
410+
411+
new WP_MySQL_On_SQLite(
412+
'mysql-on-sqlite:path=:memory:;dbname=wp',
413+
null,
414+
null,
415+
array( 'sqlite_busy_timeout' => '10000' )
416+
);
417+
}
418+
382419
public function test_query(): void {
383420
$result = $this->driver->query( "SELECT 1, 'abc'" );
384421
$this->assertInstanceOf( WP_MySQL_On_SQLite_Statement::class, $result );

‎packages/mysql-on-sqlite/tests/WP_SQLite_Connection_Tests.php‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,59 @@ public function testDriverKeepsConfiguredJournalMode(): void {
189189
$this->assertSame( 'delete', $this->get_journal_mode( $driver->get_connection() ) );
190190
}
191191

192+
public function testDefaultBusyTimeout(): void {
193+
$connection = new WP_SQLite_Connection( array( 'path' => $this->db_path ) );
194+
195+
$this->assertSame( '10000', $this->get_busy_timeout( $connection ) );
196+
}
197+
198+
public function testBusyTimeoutAcceptsZero(): void {
199+
$connection = new WP_SQLite_Connection(
200+
array(
201+
'path' => $this->db_path,
202+
'busy_timeout' => 0,
203+
)
204+
);
205+
206+
$this->assertSame( '0', $this->get_busy_timeout( $connection ) );
207+
}
208+
209+
public function testBusyTimeoutAcceptsMaximumValue(): void {
210+
$connection = new WP_SQLite_Connection(
211+
array(
212+
'path' => $this->db_path,
213+
'busy_timeout' => 2147483647,
214+
)
215+
);
216+
217+
$this->assertSame( '2147483647', $this->get_busy_timeout( $connection ) );
218+
}
219+
220+
/**
221+
* @dataProvider provideInvalidBusyTimeouts
222+
*/
223+
public function testInvalidBusyTimeoutThrows( $busy_timeout ): void {
224+
$this->expectException( InvalidArgumentException::class );
225+
$this->expectExceptionMessage( 'Invalid SQLite busy timeout. It must be an integer from 0 to 2147483647.' );
226+
new WP_SQLite_Connection(
227+
array(
228+
'path' => $this->db_path,
229+
'busy_timeout' => $busy_timeout,
230+
)
231+
);
232+
}
233+
234+
public function provideInvalidBusyTimeouts(): array {
235+
return array(
236+
'string' => array( '10000' ),
237+
'float' => array( 10000.0 ),
238+
'boolean' => array( false ),
239+
'array' => array( array( 10000 ) ),
240+
'negative' => array( -1 ),
241+
'above maximum' => array( 2147483648 ),
242+
);
243+
}
244+
192245
/**
193246
* Create the database file first, and then make its directory read-only,
194247
* so that the WAL sidecar files ("-wal", "-shm") cannot be created.
@@ -216,4 +269,8 @@ private function get_journal_mode( WP_SQLite_Connection $connection ): string {
216269
private function get_synchronous( WP_SQLite_Connection $connection ): string {
217270
return (string) $connection->query( 'PRAGMA synchronous' )->fetchColumn();
218271
}
272+
273+
private function get_busy_timeout( WP_SQLite_Connection $connection ): string {
274+
return (string) $connection->query( 'PRAGMA busy_timeout' )->fetchColumn();
275+
}
219276
}

‎packages/plugin-sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-db.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,7 @@ public function db_connect( $allow_bail = true ) {
453453
try {
454454
$options = array(
455455
'sqlite_journal_mode' => defined( 'SQLITE_JOURNAL_MODE' ) ? SQLITE_JOURNAL_MODE : null,
456+
'sqlite_busy_timeout' => defined( 'SQLITE_BUSY_TIMEOUT' ) ? SQLITE_BUSY_TIMEOUT : null,
456457
);
457458
$dbh = new WP_MySQL_On_SQLite(
458459
sprintf(

‎packages/plugin-sqlite-database-integration/wp-includes/sqlite/install-functions.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ function sqlite_make_db_sqlite() {
3030
null,
3131
array(
3232
'sqlite_journal_mode' => defined( 'SQLITE_JOURNAL_MODE' ) ? SQLITE_JOURNAL_MODE : null,
33+
'sqlite_busy_timeout' => defined( 'SQLITE_BUSY_TIMEOUT' ) ? SQLITE_BUSY_TIMEOUT : null,
3334
)
3435
);
3536
$translator->setAttribute( PDO::ATTR_STRINGIFY_FETCHES, true ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO

0 commit comments

Comments
 (0)