Optimised keyedColumn() and map() for MySQLQuery (#6424)

* Optimised keyedColumn() and map() for MySQL

* WS

* Add unit tests for map() and keyedColumn()
This commit is contained in:
Mike Cochrane 2016-12-20 23:57:37 +13:00 committed by Daniel Hensby
parent 1c76148b1c
commit 4c6936834e
2 changed files with 54 additions and 0 deletions

View File

@ -60,4 +60,40 @@ class MySQLQuery extends Query
return false;
}
}
/**
* Return an array containing all values in the leftmost column, where the keys are the
* same as the values.
*
* @return array
*/
public function keyedColumn()
{
$column = [];
if (is_object($this->handle)) {
foreach ($this->handle->fetch_all(MYSQLI_ASSOC) as $record) {
$val = $record[key($record)];
$column[$val] = $val;
}
}
return $column;
}
/**
* Return a map from the first column to the second column.
*
* @return array
*/
public function map()
{
$column = [];
if (is_object($this->handle)) {
foreach ($this->handle->fetch_all(MYSQLI_ASSOC) as $record) {
$key = reset($record);
$val = next($record);
$column[$key] = $val;
}
}
return $column;
}
}

View File

@ -336,6 +336,24 @@ class DataQueryTest extends SapphireTest
$this->resetDBSchema(true);
}
public function testMap()
{
$fixtures = DataQueryTest\ObjectC::get();
$expected = array();
foreach ($fixtures as $fixture) {
$expected[$fixture->ID] = $fixture->Title;
$fixture->destroy();
}
$result = DB::query("SELECT \"ID\", \"Title\" FROM \"DataQueryTest_C\"")->map();
$this->assertEquals($expected, $result);
}
public function testKeyedColumn()
{
$result = DB::query("SELECT \"Title\" FROM \"DataQueryTest_C\"")->keyedColumn();
$this->assertEquals(['First' => 'First', 'Second' => 'Second', 'Last' => 'Last'], $result);
}
/**
* Tests that getFinalisedQuery can include all tables
*/