Skip to content

Commit 0a375cc

Browse files
committed
Fix rowCount() of result sets without rows
For a statement that returns a result set but no rows, PDO SQLite's rowCount() reports the row count of the last write on the connection. The driver passed that value through, so an empty SELECT after a write reported the written rows. This includes the driver's internal writes, such as the information schema rows written by CREATE TABLE. Report 0 for all statements that return a result set, as it already was for result sets with rows. Until the previous commit, the no-op INSERT used for empty result sets reset the counter after statements like SET or CREATE TABLE, which hid some of these cases.
1 parent 6cc331b commit 0a375cc

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,18 @@ public function columnCount(): int {
229229
* @return int The number of rows affected by the statement.
230230
*/
231231
public function rowCount(): int {
232-
return $this->affected_rows ?? $this->statement->rowCount();
232+
if ( null !== $this->affected_rows ) {
233+
return $this->affected_rows;
234+
}
235+
236+
/*
237+
* PDO SQLite reports the row count of the last write for statements
238+
* that return a result set but no rows, so we can't use it for them.
239+
*/
240+
if ( $this->statement->columnCount() > 0 ) {
241+
return 0;
242+
}
243+
return $this->statement->rowCount();
233244
}
234245

235246
/**

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,21 @@ public function test_exec(): void {
767767
$this->assertEquals( 0, $result );
768768
}
769769

770+
public function test_row_count_of_result_set_without_rows(): void {
771+
// The row count of a previous write must not leak into the result set.
772+
$this->driver->exec( 'CREATE TABLE t (id INT)' );
773+
$this->assertSame( 0, $this->driver->query( 'SELECT * FROM t' )->rowCount() );
774+
775+
$this->driver->exec( 'INSERT INTO t VALUES (1), (2), (3)' );
776+
$this->assertSame( 0, $this->driver->query( 'SELECT * FROM t WHERE id > 3' )->rowCount() );
777+
$this->assertSame( 0, $this->driver->query( 'SELECT 1 WHERE FALSE' )->rowCount() );
778+
$this->assertSame( 0, $this->driver->query( "SHOW TABLES LIKE 'missing'" )->rowCount() );
779+
780+
$this->driver->exec( 'INSERT INTO t VALUES (4), (5), (6)' );
781+
$this->driver->exec( 'SET @a = 1' );
782+
$this->assertSame( 0, $this->driver->query( 'SELECT * FROM t WHERE id > 6' )->rowCount() );
783+
}
784+
770785
public function test_last_insert_id(): void {
771786
$this->assertSame( '0', $this->driver->lastInsertId() );
772787

0 commit comments

Comments
 (0)