Fix: numFields wrong for sqlite
authorphysikerwelt <wiki@physikerwelt.de>
Wed, 21 May 2014 11:38:56 +0000 (11:38 +0000)
committerphysikerwelt <wiki@physikerwelt.de>
Wed, 21 May 2014 13:09:13 +0000 (13:09 +0000)
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
tests/phpunit/includes/db/DatabaseSqliteTest.php

index 468ed6d..3e063c6 100644 (file)
@@ -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;
+               }
        }
 
        /**
index b4c1953..88bf7d9 100644 (file)
@@ -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" );
+       }
 }