Skip to content
This repository was archived by the owner on Sep 11, 2026. It is now read-only.

Commit 026e2ed

Browse files
gcsecseyadamziel
andauthored
Don't take a write lock for SET statements (fixes "database is locked" on connect) (WordPress#443)
Related to STU-1821 ## What changed Every WordPress request runs `SET SESSION sql_mode = …` at bootstrap (via `wpdb::set_sql_mode()`). This statement changes only session state and writes nothing to the database, but the driver acquires an SQLite write lock for it. Under concurrent access, this makes an otherwise read-only request fatal with `database is locked` (`SQLITE_BUSY`) the moment any other connection holds the write lock. This PR fixes the two places the `SET` path takes a write lock (`WP_PDO_MySQL_On_SQLite`): 1. **The wrapper transaction.** `query()` opens `BEGIN IMMEDIATE` (a RESERVED/write lock) for every non-`SELECT` statement, and `SET` was treated as a write. → `SET` is now detected as read-only, so it opens a deferred `BEGIN` (SHARED) instead — the same treatment `SHOW`/`DESCRIBE` already receive (WordPress#361). 2. **The empty-result builder.** `create_result_statement_from_data()` fabricates a 0-column result with a no-op `INSERT … WHERE FALSE` against a regular table. SQLite acquires a write lock for *any* DML, even one that inserts zero rows, so this re-took a write lock right after the wrapper committed. → The 0-column statement is now built with a no-op `INSERT` into a connection-private **`TEMP` table**, whose temp database has no shared lock. Both changes are required: with only (1), the fatal simply moves from the `BEGIN IMMEDIATE` to the no-op `INSERT`. ## Why This is a direct follow-up to WordPress#361 (which stopped `SELECT`/`SHOW`/`DESCRIBE` from taking write locks and closed WordPress#318). `SET` was left on the write path. Because `set_sql_mode()` runs on every connection, the impact is broad: a single slow request holding a write transaction (a background WooCommerce/Jetpack write, an import, a long render on a heavy site) makes every concurrent request fail at connect, not only concurrent writers. SQLite is single-writer by design, but statements that perform no writes should never contend for the write lock. Journal mode does not address this on its own: it reproduces identically under both `DELETE` and `WAL` (WAL still serialises writers). ## Reproduction Deterministic, single process, two driver connections to one file: ```php $path = tempnam( sys_get_temp_dir(), 'sqlite' ); @Unlink( $path ); $make = fn() => new WP_SQLite_Driver( new WP_SQLite_Connection( array( 'path' => $path ) ), 'db' ); // Build both connections first, so B's schema setup doesn't run under the lock. $a = $make(); $a->query( 'CREATE TABLE t ( id INTEGER PRIMARY KEY )' ); $b = $make(); $b->execute_sqlite_query( 'PRAGMA busy_timeout = 1500' ); // fail fast on a lock // A holds a write lock. $a->query( 'START TRANSACTION' ); $a->query( 'INSERT INTO t ( id ) VALUES ( 1 )' ); // B runs the connect-time statement. It writes nothing, so it must not block. $b->query( "SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION'" ); // Before this PR: throws "database is locked". After: returns immediately. ``` **Before:** `WP_SQLite_Driver_Exception: … database is locked`, first in `begin_wrapper_transaction()`, or after fixing only (1), in `create_result_statement_from_data()`. **After:** the `SET` returns immediately while A still holds its write lock. This also reproduces end-to-end in a multi-worker WordPress install (eg. PHP-FPM with more than one workers) under concurrent requests, where one slow request holding a write transaction makes concurrent page loads fatal at `set_sql_mode`. ## Tests Two regression tests added to `WP_SQLite_Driver_Concurrency_Tests`: - `testSetQueryOpensReadOnlyTransaction`: `SET` opens `BEGIN`, not `BEGIN IMMEDIATE`. - `testSetQuerySucceedsWhileAnotherConnectionHoldsWriteLock`: with another connection holding `BEGIN IMMEDIATE` and `timeout = 0`, `SET` completes instead of throwing `SQLITE_BUSY`. Both fail on `trunk` and pass with this change. ## Notes / risk - **The 0-column contract is preserved.** `WP_SQLite_Driver::query()` returns `fetchAll()` when `columnCount() > 0`, otherwise `rowCount()`. The replacement empty-result statement keeps `columnCount() === 0`, so writes and `SET` still return their affected-row count (not an empty array). Verified: running a representative `CREATE`/`INSERT`/`SELECT`/`COUNT`/`UPDATE`/`DELETE`/`SET` sequence produces byte-identical results before and after. - **Bonus:** real writes (`INSERT`/`UPDATE`/`DELETE`) also fabricate their empty result through this path, which previously meant a second, redundant write-lock acquisition after the real write. That redundant lock is now gone, slightly reducing lock pressure for all writes. - **Temp-table lifetime.** The `TEMP` table is created once per connection (guarded by a flag); `TEMP` tables live for the connection's lifetime. A reviewer preferring maximum robustness over the micro-optimisation could drop the flag and always issue the idempotent `CREATE TEMP TABLE IF NOT EXISTS`. --------- Co-authored-by: Adam Zieliński <adam@adamziel.com>
1 parent 86a9113 commit 026e2ed

2 files changed

Lines changed: 80 additions & 2 deletions

File tree

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

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@ class WP_PDO_MySQL_On_SQLite extends PDO {
4343
*/
4444
const GLOBAL_VARIABLES_TABLE_NAME = self::RESERVED_PREFIX . 'global_variables';
4545

46+
/**
47+
* Name of the connection-private TEMP table used to build empty result sets
48+
* without acquiring a write lock on the database. See create_result_statement_from_data().
49+
*/
50+
const EMPTY_RESULT_TABLE_NAME = self::RESERVED_PREFIX . 'empty_result';
51+
4652
/**
4753
* The name of the SQLite driver version variable.
4854
*
@@ -527,6 +533,14 @@ class WP_PDO_MySQL_On_SQLite extends PDO {
527533
*/
528534
private $is_readonly;
529535

536+
/**
537+
* Whether the TEMP table backing empty result sets has been created on this
538+
* connection. See create_result_statement_from_data().
539+
*
540+
* @var bool
541+
*/
542+
private $empty_result_table_ready = false;
543+
530544
/**
531545
* Type of wrapper transaction that is active for the MySQL query emulation.
532546
*
@@ -920,6 +934,12 @@ public function query( string $query, ?int $fetch_mode = null, ...$fetch_mode_ar
920934
if (
921935
'selectStatement' === $statement_node->rule_name
922936
|| 'showStatement' === $statement_node->rule_name
937+
// Supported SET statements mutate only connection-local driver state
938+
// (sql_mode, user variables, etc.) or fail before touching SQLite.
939+
// They do not write to the SQLite database, so they must not take a
940+
// write lock. Use a deferred BEGIN instead of BEGIN IMMEDIATE.
941+
// This mirrors the SHOW/DESCRIBE handling.
942+
|| 'setStatement' === $statement_node->rule_name
923943
) {
924944
$this->is_readonly = true;
925945
} elseif ( 'utilityStatement' === $statement_node->rule_name ) {
@@ -7003,10 +7023,29 @@ private function create_result_statement_from_data( array $columns, array $rows
70037023
* This can be done using a noop INSERT statement that modifies no data.
70047024
*/
70057025
if ( 0 === count( $columns ) ) {
7026+
/*
7027+
* Build a 0-column statement to represent an empty result set.
7028+
*
7029+
* A no-op "INSERT ... WHERE FALSE" into a regular table still acquires
7030+
* SQLite's write lock, even though it writes nothing. That makes
7031+
* no-write statements such as "SET sql_mode = ..." fatal with
7032+
* "database is locked" whenever another connection holds the write
7033+
* lock. Writing to a connection-private TEMP table uses the temp
7034+
* database, which has no shared lock, so it never contends.
7035+
*/
7036+
if ( ! $this->empty_result_table_ready ) {
7037+
$pdo->exec(
7038+
sprintf(
7039+
'CREATE TEMP TABLE IF NOT EXISTS %s ( placeholder_for_empty_insert )',
7040+
$this->quote_sqlite_identifier( self::EMPTY_RESULT_TABLE_NAME )
7041+
)
7042+
);
7043+
$this->empty_result_table_ready = true;
7044+
}
70067045
return $pdo->query(
70077046
sprintf(
7008-
'INSERT INTO %s (rowid) SELECT NULL WHERE FALSE',
7009-
$this->quote_sqlite_identifier( self::GLOBAL_VARIABLES_TABLE_NAME )
7047+
'INSERT INTO %s ( placeholder_for_empty_insert ) SELECT NULL WHERE FALSE',
7048+
$this->quote_sqlite_identifier( self::EMPTY_RESULT_TABLE_NAME )
70107049
)
70117050
);
70127051
}

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,45 @@ public function testDescribeQuerySucceedsWhileAnotherConnectionHoldsWriteLock():
9797
$this->assertReadOnlyQuerySucceedsUnderWriteLock( 'DESCRIBE t' );
9898
}
9999

100+
public function testSetQueryOpensReadOnlyTransaction(): void {
101+
$driver = $this->create_in_memory_driver();
102+
$driver->query( 'CREATE TABLE t (id INT, name VARCHAR(255))' );
103+
104+
$driver->query( "SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION'" );
105+
106+
$this->assertSame( 'BEGIN', $driver->get_last_sqlite_queries()[0]['sql'] );
107+
}
108+
109+
public function testSetQuerySucceedsWhileAnotherConnectionHoldsWriteLock(): void {
110+
// Connection A: set up the database and hold a write transaction.
111+
$conn_a = new WP_SQLite_Connection( array( 'path' => $this->db_path ) );
112+
$driver_a = new WP_SQLite_Driver( $conn_a, 'wp' );
113+
$driver_a->query( 'CREATE TABLE t (id INT, name VARCHAR(255))' );
114+
$driver_a->query( "INSERT INTO t VALUES (1, 'Alice')" );
115+
116+
// Simulate another PHP process holding a write transaction.
117+
$conn_a->get_pdo()->exec( 'BEGIN IMMEDIATE' );
118+
119+
try {
120+
// Connection B with zero timeout — any lock conflict fails immediately.
121+
$conn_b = new WP_SQLite_Connection(
122+
array(
123+
'path' => $this->db_path,
124+
'timeout' => 0,
125+
)
126+
);
127+
$driver_b = new WP_SQLite_Driver( $conn_b, 'wp' );
128+
$conn_b->get_pdo()->setAttribute( PDO::ATTR_TIMEOUT, 0 );
129+
130+
// SET writes nothing, so it must not contend for the write lock.
131+
$result = $driver_b->query( "SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION'" );
132+
133+
$this->assertSame( 0, $result );
134+
} finally {
135+
$conn_a->get_pdo()->exec( 'ROLLBACK' );
136+
}
137+
}
138+
100139
private function assertReadOnlyQuerySucceedsUnderWriteLock( string $query ): void {
101140
// Connection A: set up the database.
102141
$conn_a = new WP_SQLite_Connection( array( 'path' => $this->db_path ) );

0 commit comments

Comments
 (0)