Page MenuHomeDevCentral

D3838.id.diff
No OneTemporary

D3838.id.diff

diff --git a/database/src/Result/DatabaseResult.php b/database/src/Result/DatabaseResult.php
--- a/database/src/Result/DatabaseResult.php
+++ b/database/src/Result/DatabaseResult.php
@@ -19,4 +19,23 @@
* @return array|null An array if there is still a row to read; null if not.
*/
public abstract function fetchRow () : ?array;
+
+ /**
+ * Fetches the value from the first column of the first row in the result.
+ *
+ * This is typically used for queries that return a single scalar value
+ * such as SELECT count(*).
+ *
+ * @return mixed|null The value, or null if no more rows.
+ */
+ public function fetchScalar () : mixed {
+ $row = $this->fetchRow();
+
+ if (!$row) {
+ return null;
+ }
+
+ $key = array_key_first($row);
+ return $row[$key];
+ }
}
diff --git a/database/tests/Result/EmptyDatabaseResultTest.php b/database/tests/Result/EmptyDatabaseResultTest.php
--- a/database/tests/Result/EmptyDatabaseResultTest.php
+++ b/database/tests/Result/EmptyDatabaseResultTest.php
@@ -21,6 +21,10 @@
$this->assertEmpty($this->result->fetchRow());
}
+ public function testFetchScalar () : void {
+ $this->assertNull($this->result->fetchScalar());
+ }
+
public function testGetIterator () : void {
$actual = iterator_to_array($this->result->getIterator());
diff --git a/database/tests/Result/MockDatabaseResultTest.php b/database/tests/Result/MockDatabaseResultTest.php
--- a/database/tests/Result/MockDatabaseResultTest.php
+++ b/database/tests/Result/MockDatabaseResultTest.php
@@ -25,6 +25,10 @@
);
}
+ public function testFetchScalar () {
+ $this->assertEquals("strawberry", $this->result->fetchScalar());
+ }
+
public function testNumRows () {
$this->assertEquals(2, $this->result->numRows());
}
diff --git a/database/tests/Result/MySQLiDatabaseResultTest.php b/database/tests/Result/MySQLiDatabaseResultTest.php
--- a/database/tests/Result/MySQLiDatabaseResultTest.php
+++ b/database/tests/Result/MySQLiDatabaseResultTest.php
@@ -49,6 +49,10 @@
$this->assertEquals($expected, $this->result->fetchRow());
}
+ public function testFetchScalar () {
+ $this->assertEquals("1", $this->result->fetchScalar());
+ }
+
public function testNumRows () {
$this->assertEquals(4, $this->result->numRows());
}

File Metadata

Mime Type
text/plain
Expires
Wed, Nov 12, 07:21 (12 h, 4 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3159016
Default Alt Text
D3838.id.diff (2 KB)

Event Timeline