mirror of
https://github.com/silverstripe/silverstripe-postgresql
synced 2024-10-22 17:05:45 +02:00
FIX: Return correct types in PostgreSQLQuery
Fixes https://github.com/silverstripe/silverstripe-postgresql/issues/90 Helps fix https://github.com/silverstripe/silverstripe-framework/issues/7039
This commit is contained in:
parent
4c6034f350
commit
72787ae83e
@ -18,6 +18,23 @@ class PostgreSQLQuery extends Query
|
||||
*/
|
||||
private $handle;
|
||||
|
||||
private $columnNames = [];
|
||||
|
||||
/**
|
||||
* Mapping of postgresql types to PHP types
|
||||
* Note that the bool => int mapping is by design, designed to mimic MySQL's behaviour
|
||||
* @var array
|
||||
*/
|
||||
protected static $typeMapping = [
|
||||
'bool' => 'int',
|
||||
'int2' => 'int',
|
||||
'int4' => 'int',
|
||||
'int8' => 'int',
|
||||
'float4' => 'float',
|
||||
'float8' => 'float',
|
||||
'numeric' => 'float',
|
||||
];
|
||||
|
||||
/**
|
||||
* Hook the result-set given into a Query class, suitable for use by sapphire.
|
||||
* @param resource $handle the internal Postgres handle that is points to the resultset.
|
||||
@ -25,6 +42,11 @@ class PostgreSQLQuery extends Query
|
||||
public function __construct($handle)
|
||||
{
|
||||
$this->handle = $handle;
|
||||
|
||||
$numColumns = pg_num_fields($handle);
|
||||
for ($i = 0; $i<$numColumns; $i++) {
|
||||
$this->columnNames[$i] = pg_field_name($handle, $i);
|
||||
}
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
@ -37,7 +59,7 @@ class PostgreSQLQuery extends Query
|
||||
public function seek($row)
|
||||
{
|
||||
pg_result_seek($this->handle, $row);
|
||||
return pg_fetch_assoc($this->handle);
|
||||
return $this->nextRecord();
|
||||
}
|
||||
|
||||
public function numRecords()
|
||||
@ -47,6 +69,24 @@ class PostgreSQLQuery extends Query
|
||||
|
||||
public function nextRecord()
|
||||
{
|
||||
return pg_fetch_assoc($this->handle);
|
||||
$row = pg_fetch_array($this->handle, null, PGSQL_NUM);
|
||||
|
||||
// Correct non-string types
|
||||
if ($row) {
|
||||
$record = [];
|
||||
|
||||
foreach ($row as $i => $v) {
|
||||
$k = $this->columnNames[$i];
|
||||
$record[$k] = $v;
|
||||
$type = pg_field_type($this->handle, $i);
|
||||
if (isset(self::$typeMapping[$type])) {
|
||||
settype($record[$k], self::$typeMapping[$type]);
|
||||
}
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user