Skip to content

Commit e88a817

Browse files
authored
Fix ROLLBACK as the first transaction of a connection (WordPress#537)
## Summary On a fresh connection, rolling back the first transaction breaks the connection: ```sql START TRANSACTION; ROLLBACK; -- SQLSTATE[42S02]: Base table or view not found: 1146 -- Table '_wp_sqlite_empty_result' doesn't exist ``` Statements with an empty result set (`SET`, `CREATE TABLE`, …) used a no-op `INSERT` into a TEMP table that was created on first use. When the first use happened inside a transaction, the rollback dropped the table, but the driver still assumed it existed. This is an **alternative to WordPress#535**. Instead of creating the table again, it **removes the need for the table**. ## Fix PDO needs a statement object even when there is nothing to return. This PR uses an **unknown pragma** for it. SQLite ignores unknown pragmas, so the statement has no columns and no rows. It **needs no table and takes no locks**, so a rollback has nothing to drop, and statements like `SET` still work while another connection writes. ## Row counts PDO SQLite's `rowCount()` reports affected rows only for `INSERT`, `UPDATE`, and `DELETE`. For other statements, it can report the row count of the **last write** on the connection, including the driver's internal writes. The old no-op `INSERT` reset that count after every empty result set, which hid most of these cases. The pragma doesn't reset it. The driver now **reports `0` affected rows for all statements other than `INSERT`, `REPLACE`, `UPDATE`, and `DELETE`**. This also fixes cases that were already broken on `trunk`: - **`SELECT` or `SHOW` without rows** right after a write reported the written rows. - **`DROP VIEW` or `DROP TRIGGER`** right after a write reported the written rows. - **`TRUNCATE TABLE`** on a table with `AUTO_INCREMENT` reported `1`. It now reports `0`, as in MySQL. ## Why not keep the table? The other options are worse than the pragma: - **Create the table again and retry (WordPress#535).** It keeps a flag that can go stale, and depends on SQLite's "no such table" error message. - **Run `CREATE TEMP TABLE IF NOT EXISTS` before every `INSERT`.** It costs about 0.5 µs per empty result, and it doesn't fix the row counts. - **Use another no-op statement.** PDO can't execute a statement with only a comment or `;`. `DROP … IF EXISTS` for a missing table can need a lock to read the schema. ## Tests The new tests cover the bug, the row counts, and the empty result statement: - **Two rollback regression tests**, adapted from WordPress#535. They fail on `trunk` with the error above. - **Two row count tests** for statements that don't write. They fail on `trunk`. - **`test_empty_result_statement`** checks the PDO API of the empty result statement, and that holding an unread one doesn't block `COMMIT` or `DROP TABLE`. Supersedes WordPress#535. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Non-data-changing statements, including `TRUNCATE`, now report zero affected rows rather than carrying over a previous write count. INSERT, REPLACE, UPDATE, and DELETE continue to report their affected-row counts. * Empty-result statements now return consistent results and counts, and no longer block transaction commits or schema changes. * **Tests** * Added coverage for empty results, affected-row counts, and rolling back the first transaction on a connection. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 4d94f39 commit e88a817

2 files changed

Lines changed: 143 additions & 44 deletions

File tree

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

Lines changed: 28 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,6 @@ class WP_MySQL_On_SQLite extends PDO {
8282
*/
8383
const GLOBAL_VARIABLES_TABLE_NAME = self::RESERVED_PREFIX . 'global_variables';
8484

85-
/**
86-
* Name of the connection-private TEMP table used to build empty result sets
87-
* without acquiring a write lock on the database. See create_result_statement_from_data().
88-
*/
89-
private const EMPTY_RESULT_TABLE_NAME = self::RESERVED_PREFIX . 'empty_result';
90-
9185
/**
9286
* The name of the SQLite driver version variable.
9387
*
@@ -678,14 +672,6 @@ class WP_MySQL_On_SQLite extends PDO {
678672
*/
679673
private $is_readonly;
680674

681-
/**
682-
* Whether the TEMP table backing empty result sets has been created on this
683-
* connection. See create_result_statement_from_data().
684-
*
685-
* @var bool
686-
*/
687-
private $empty_result_table_ready = false;
688-
689675
/**
690676
* Type of wrapper transaction that is active for the MySQL query emulation.
691677
*
@@ -1145,8 +1131,8 @@ public function query( string $query, ?int $fetch_mode = null, ...$fetch_mode_ar
11451131
* [GRAMMAR]
11461132
* simpleStatement: selectStatement | showStatement | utilityStatement | ...
11471133
*/
1148-
if ( null !== $child_node && $child_node->has_child_node() ) {
1149-
$statement_node = $child_node->get_first_child_node();
1134+
$statement_node = null !== $child_node ? $child_node->get_first_child_node() : null;
1135+
if ( null !== $statement_node ) {
11501136
if (
11511137
'selectStatement' === $statement_node->rule_name
11521138
|| 'showStatement' === $statement_node->rule_name
@@ -1180,11 +1166,25 @@ public function query( string $query, ?int $fetch_mode = null, ...$fetch_mode_ar
11801166
$this->last_result_statement = $this->create_result_statement_from_data( array(), array() );
11811167
}
11821168

1169+
/*
1170+
* PDO SQLite reports affected rows only for INSERT, UPDATE, and DELETE.
1171+
* For other statements, it can report the row count of the last write,
1172+
* including the driver's internal writes. Use 0 for them instead.
1173+
*
1174+
* [GRAMMAR]
1175+
* simpleStatement: insertStatement | replaceStatement | updateStatement | deleteStatement | ...
1176+
*/
1177+
$reports_affected_rows = null !== $statement_node && in_array(
1178+
$statement_node->rule_name,
1179+
array( 'insertStatement', 'replaceStatement', 'updateStatement', 'deleteStatement' ),
1180+
true
1181+
);
1182+
11831183
$stmt = new WP_MySQL_On_SQLite_Statement(
11841184
$this->last_result_statement,
11851185
$query,
11861186
$this->create_column_meta_resolver( $this->last_column_meta ),
1187-
$this->last_affected_rows
1187+
$reports_affected_rows ? $this->last_affected_rows : 0
11881188
);
11891189
if ( null !== $fetch_mode ) {
11901190
$stmt->setFetchMode( $fetch_mode, ...$fetch_mode_args );
@@ -7738,38 +7738,22 @@ private function flush(): void {
77387738
* @return PDOStatement The corresponding PDO SQLite statement.
77397739
*/
77407740
private function create_result_statement_from_data( array $columns, array $rows ): PDOStatement {
7741+
/*
7742+
* The statement writes nothing, but PDO SQLite can report the row count
7743+
* of the last write for it. Default the affected rows to 0.
7744+
*/
7745+
$this->last_affected_rows = $this->last_affected_rows ?? 0;
7746+
77417747
$pdo = $this->connection->get_pdo();
77427748

77437749
/*
7744-
* With 0 columns, we need to create a PDO statement that has no columns.
7745-
* This can be done using a noop INSERT statement that modifies no data.
7750+
* With 0 columns, we need a PDO statement with no columns and no rows.
7751+
*
7752+
* An unknown pragma has no columns, needs no table, takes no locks,
7753+
* and SQLite ignores it.
77467754
*/
77477755
if ( 0 === count( $columns ) ) {
7748-
/*
7749-
* Build a 0-column statement to represent an empty result set.
7750-
*
7751-
* A no-op "INSERT ... WHERE FALSE" into a regular table still acquires
7752-
* SQLite's write lock, even though it writes nothing. That makes
7753-
* no-write statements such as "SET sql_mode = ..." fatal with
7754-
* "database is locked" whenever another connection holds the write
7755-
* lock. Writing to a connection-private TEMP table uses the temp
7756-
* database, which has no shared lock, so it never contends.
7757-
*/
7758-
if ( ! $this->empty_result_table_ready ) {
7759-
$pdo->exec(
7760-
sprintf(
7761-
'CREATE TEMP TABLE IF NOT EXISTS %s ( placeholder_for_empty_insert )',
7762-
$this->quote_sqlite_identifier( self::EMPTY_RESULT_TABLE_NAME )
7763-
)
7764-
);
7765-
$this->empty_result_table_ready = true;
7766-
}
7767-
return $pdo->query(
7768-
sprintf(
7769-
'INSERT INTO %s ( placeholder_for_empty_insert ) SELECT NULL WHERE FALSE',
7770-
$this->quote_sqlite_identifier( self::EMPTY_RESULT_TABLE_NAME )
7771-
)
7772-
);
7756+
return $pdo->query( 'PRAGMA ' . self::RESERVED_PREFIX . 'empty_result' );
77737757
}
77747758

77757759
/*

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

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,59 @@ function () {
529529
$this->assertSame( array( '00000', null, null ), $stmt->errorInfo() );
530530
}
531531

532+
public function test_empty_result_statement(): void {
533+
// The row count of a previous write must not leak into the empty result.
534+
$this->driver->exec( 'CREATE TABLE t (id INT)' );
535+
$this->driver->exec( 'INSERT INTO t VALUES (1), (2), (3)' );
536+
$stmt = $this->driver->query( 'SET @a = 1' );
537+
538+
// Check the error state and iteration first, as fetching resets the error state.
539+
$this->assertSame( '00000', $stmt->errorCode() );
540+
$this->assertSame( array( '00000', null, null ), $stmt->errorInfo() );
541+
$this->assertSame( array(), iterator_to_array( $stmt ) );
542+
543+
$this->assertSame( 0, $stmt->columnCount() );
544+
$this->assertSame( 0, $stmt->rowCount() );
545+
$this->assertFalse( $stmt->getColumnMeta( 0 ) );
546+
547+
$fetch_modes = array(
548+
PDO::FETCH_BOTH,
549+
PDO::FETCH_NUM,
550+
PDO::FETCH_ASSOC,
551+
PDO::FETCH_NAMED,
552+
PDO::FETCH_OBJ,
553+
PDO::FETCH_COLUMN,
554+
PDO::FETCH_KEY_PAIR,
555+
);
556+
foreach ( $fetch_modes as $mode ) {
557+
$this->assertFalse( $stmt->fetch( $mode ) );
558+
$this->assertSame( array(), $stmt->fetchAll( $mode ) );
559+
}
560+
$this->assertFalse( $stmt->fetchColumn() );
561+
$this->assertFalse( $stmt->fetchObject() );
562+
$this->assertSame( array(), $stmt->fetchAll( PDO::FETCH_GROUP | PDO::FETCH_ASSOC ) );
563+
$this->assertSame( array(), $stmt->fetchAll( PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC ) );
564+
$this->assertSame( array(), $stmt->fetchAll( PDO::FETCH_CLASS, stdClass::class ) );
565+
566+
$this->assertTrue( $stmt->setFetchMode( PDO::FETCH_CLASS, stdClass::class ) );
567+
$this->assertFalse( $stmt->fetch() );
568+
569+
$value = 'unchanged';
570+
$this->assertTrue( $stmt->bindColumn( 1, $value ) );
571+
$this->assertFalse( $stmt->fetch( PDO::FETCH_BOUND ) );
572+
$this->assertSame( 'unchanged', $value );
573+
574+
$this->assertTrue( $stmt->closeCursor() );
575+
$this->assertFalse( $stmt->fetch() );
576+
577+
// Holding an unread statement must not block a commit or a schema change.
578+
$stmt = $this->driver->query( 'SET @a = 1' );
579+
$this->driver->exec( 'START TRANSACTION' );
580+
$this->driver->exec( 'INSERT INTO t VALUES (4)' );
581+
$this->assertSame( 0, $this->driver->exec( 'COMMIT' ) );
582+
$this->assertSame( 0, $this->driver->exec( 'DROP TABLE t' ) );
583+
}
584+
532585
public function test_statement_iteration(): void {
533586
$stmt = $this->driver->query( 'SELECT 1 AS value UNION ALL SELECT 2', PDO::FETCH_ASSOC );
534587

@@ -715,6 +768,45 @@ public function test_exec(): void {
715768
$this->assertEquals( 0, $result );
716769
}
717770

771+
public function test_row_count_of_result_set_without_rows(): void {
772+
// The row count of a previous write must not leak into the result set.
773+
$this->driver->exec( 'CREATE TABLE t (id INT)' );
774+
$this->assertSame( 0, $this->driver->query( 'SELECT * FROM t' )->rowCount() );
775+
776+
$this->driver->exec( 'INSERT INTO t VALUES (1), (2), (3)' );
777+
$this->assertSame( 0, $this->driver->query( 'SELECT * FROM t WHERE id > 3' )->rowCount() );
778+
$this->assertSame( 0, $this->driver->query( 'SELECT 1 WHERE FALSE' )->rowCount() );
779+
$this->assertSame( 0, $this->driver->query( "SHOW TABLES LIKE 'missing'" )->rowCount() );
780+
781+
$this->driver->exec( 'INSERT INTO t VALUES (4), (5), (6)' );
782+
$this->driver->exec( 'SET @a = 1' );
783+
$this->assertSame( 0, $this->driver->query( 'SELECT * FROM t WHERE id > 6' )->rowCount() );
784+
}
785+
786+
public function test_row_count_of_non_dml_statements(): void {
787+
// The row count of the internal writes of CREATE TABLE must not leak.
788+
$this->driver->exec( 'CREATE TABLE t (id INT PRIMARY KEY AUTO_INCREMENT, a INT, b INT)' );
789+
$this->assertSame( 0, $this->driver->exec( 'DROP VIEW IF EXISTS v' ) );
790+
$this->assertSame( 0, $this->driver->exec( 'DROP TRIGGER IF EXISTS tr' ) );
791+
792+
// The row count of a previous write must not leak.
793+
$this->driver->exec( 'INSERT INTO t (a, b) VALUES (1, 1), (2, 2), (3, 3)' );
794+
$this->assertSame( 0, $this->driver->exec( 'DROP VIEW IF EXISTS v' ) );
795+
$this->assertSame( 0, $this->driver->exec( 'DROP TRIGGER IF EXISTS tr' ) );
796+
797+
// TRUNCATE reports 0 affected rows in MySQL, regardless of the deleted rows.
798+
$this->assertSame( 0, $this->driver->exec( 'TRUNCATE TABLE t' ) );
799+
800+
// DML statements still report their affected rows.
801+
$this->assertSame( 3, $this->driver->exec( 'INSERT INTO t (a, b) VALUES (1, 1), (2, 2), (3, 3)' ) );
802+
$this->assertSame( 1, $this->driver->exec( 'REPLACE INTO t (id, a, b) VALUES (4, 4, 4)' ) );
803+
$this->assertSame( 2, $this->driver->exec( 'UPDATE t SET b = 0 WHERE a > 2' ) );
804+
$this->driver->exec( 'CREATE TABLE u (id INT)' );
805+
$this->driver->exec( 'INSERT INTO u VALUES (1), (2)' );
806+
$this->assertSame( 2, $this->driver->exec( 'DELETE t FROM t JOIN u ON t.id = u.id' ) );
807+
$this->assertSame( 2, $this->driver->exec( 'DELETE FROM t' ) );
808+
}
809+
718810
public function test_last_insert_id(): void {
719811
$this->assertSame( '0', $this->driver->lastInsertId() );
720812

@@ -888,6 +980,29 @@ public function test_rollback(): void {
888980
$this->assertTrue( $result );
889981
}
890982

983+
public function test_rollback_statement_as_first_transaction_on_connection(): void {
984+
// Roll back the first transaction on the connection.
985+
$this->driver->exec( 'START TRANSACTION' );
986+
$this->driver->exec( 'ROLLBACK' );
987+
$this->assertFalse( $this->driver->inTransaction() );
988+
989+
// Statements with empty result sets keep working after the rollback.
990+
$this->driver->exec( 'START TRANSACTION' );
991+
$this->driver->exec( 'CREATE TABLE t (id INT)' );
992+
$this->driver->exec( 'ROLLBACK' );
993+
$this->assertSame( 0, $this->driver->exec( 'CREATE TABLE t (id INT)' ) );
994+
}
995+
996+
public function test_rollback_method_as_first_transaction_on_connection(): void {
997+
// Roll back the first transaction on the connection.
998+
$this->driver->beginTransaction();
999+
$this->driver->exec( 'CREATE TABLE t (id INT)' );
1000+
$this->assertTrue( $this->driver->rollBack() );
1001+
1002+
// Statements with empty result sets keep working after the rollback.
1003+
$this->assertSame( 0, $this->driver->exec( 'CREATE TABLE t (id INT)' ) );
1004+
}
1005+
8911006
public function test_rollback_no_active_transaction(): void {
8921007
$this->expectException( PDOException::class );
8931008
$this->expectExceptionMessage( 'There is no active transaction' );

0 commit comments

Comments
 (0)