From 5048f30f69a0f11e52178cb966f8f8dd4198e642 Mon Sep 17 00:00:00 2001 From: physikerwelt Date: Wed, 21 May 2014 11:38:56 +0000 Subject: [PATCH] Fix: numFields wrong for sqlite Currently the first row of the result is used to return the number of fields. This fix corrects that calculation, which has returned twice the number of fields before. The reason for that was that the resulting data array has the following form: array() { [0] => value_0 ["field_name0"] =>value_0 [1] => value_1 ["field_name1"] =>value_1 ... Furthermore the constant 0 (int) is returned if the result set is empty. This issue should be corrected in the future, since the number or fields should be answered in a metadata context independent of the data stored in the relation. Bug: 65578 Change-Id: I399c7c857dcbd774cc4eb6102bbfe8a8764b07c9 --- includes/db/DatabaseSqlite.php | 9 +++++++-- .../phpunit/includes/db/DatabaseSqliteTest.php | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/includes/db/DatabaseSqlite.php b/includes/db/DatabaseSqlite.php index 468ed6d686..3e063c6741 100644 --- a/includes/db/DatabaseSqlite.php +++ b/includes/db/DatabaseSqlite.php @@ -342,8 +342,13 @@ class DatabaseSqlite extends DatabaseBase { */ function numFields( $res ) { $r = $res instanceof ResultWrapper ? $res->result : $res; - - return is_array( $r ) ? count( $r[0] ) : 0; + if ( is_array($r) && count( $r ) > 0 ){ + // The size of the result array is twice the number of fields. (Bug: 65578) + return count( $r[0] ) / 2 ; + } else { + // If the result is empty return 0 + return 0; + } } /** diff --git a/tests/phpunit/includes/db/DatabaseSqliteTest.php b/tests/phpunit/includes/db/DatabaseSqliteTest.php index b4c1953ebe..88bf7d99d0 100644 --- a/tests/phpunit/includes/db/DatabaseSqliteTest.php +++ b/tests/phpunit/includes/db/DatabaseSqliteTest.php @@ -431,4 +431,22 @@ class DatabaseSqliteTest extends MediaWikiTestCase { $row = $res->fetchRow(); $this->assertFalse( (bool)$row['a'] ); } + + /** + * @covers DatabaseSqlite::numFields + */ + public function testNumFields() { + $db = new DatabaseSqliteStandalone( ':memory:' ); + + $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ ); + $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Failed to create table a" ); + $res = $db->select( 'a' , '*'); + $this->assertEquals( 0, $db->numFields($res), "expects to get 0 fields for an empty table" ); + $insertion = $db->insert( 'a', array( 'a_1' => 10 ), __METHOD__ ); + $this->assertTrue( $insertion, "Insertion failed" ); + $res = $db->select( 'a' , '*'); + $this->assertEquals( 1, $db->numFields($res), "wrong number of fields" ); + + $this->assertTrue( $db->close(), "closing database" ); + } } -- 2.20.1