1
0
mirror of https://github.com/dg/dibi.git synced 2025-02-24 10:53:17 +01:00
php-dibi/dibi/libs/DibiResult.php

664 lines
14 KiB
PHP
Raw Normal View History

2008-07-17 03:51:29 +00:00
<?php
/**
2010-09-14 18:40:41 +02:00
* This file is part of the "dibi" - smart database abstraction layer.
2012-01-02 20:24:16 +01:00
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
2008-07-17 03:51:29 +00:00
*/
/**
2010-08-03 22:48:44 +02:00
* dibi result set.
2008-07-17 03:51:29 +00:00
*
* <code>
* $result = dibi::query('SELECT * FROM [table]');
*
* $row = $result->fetch();
* $value = $result->fetchSingle();
* $table = $result->fetchAll();
* $pairs = $result->fetchPairs();
* $assoc = $result->fetchAssoc('id');
* $assoc = $result->fetchAssoc('active,#,id');
*
* unset($result);
* </code>
*
2010-09-14 18:40:41 +02:00
* @author David Grudl
2012-01-03 04:50:11 +01:00
* @package dibi
2010-04-22 12:12:11 +02:00
*
* @property-read mixed $resource
* @property-read IDibiResultDriver $driver
2010-04-22 12:12:11 +02:00
* @property-read int $rowCount
* @property-read DibiResultIterator $iterator
* @property string $rowClass
* @property-read DibiResultInfo $info
2008-07-17 03:51:29 +00:00
*/
class DibiResult extends DibiObject implements IDataSource
2008-07-17 03:51:29 +00:00
{
/** @var array IDibiResultDriver */
2008-07-17 03:51:29 +00:00
private $driver;
2008-10-28 15:24:47 +00:00
/** @var array Translate table */
private $types = array();
2008-07-17 03:51:29 +00:00
/** @var DibiResultInfo */
private $meta;
2008-07-17 03:51:29 +00:00
2008-10-28 15:24:47 +00:00
/** @var bool Already fetched? Used for allowance for first seek(0) */
2008-07-17 03:51:29 +00:00
private $fetched = FALSE;
2008-10-30 15:40:17 +00:00
/** @var string returned object class */
2010-02-24 02:43:15 +01:00
private $rowClass = 'DibiRow';
2008-10-30 15:40:17 +00:00
/** @var Callback returned object factory*/
private $rowFactory;
2012-01-18 21:08:34 +01:00
/** @var array format */
private $formats = array();
2008-07-17 03:51:29 +00:00
/**
* @param IDibiResultDriver
2008-07-17 03:51:29 +00:00
*/
2012-01-18 21:08:34 +01:00
public function __construct($driver)
2008-07-17 03:51:29 +00:00
{
$this->driver = $driver;
$this->detectTypes();
2008-07-17 03:51:29 +00:00
}
/**
2012-01-19 00:12:08 +01:00
* @deprecated
2008-07-17 03:51:29 +00:00
*/
final public function getResource()
{
2012-01-19 00:12:08 +01:00
return $this->getResultDriver()->getResultResource();
2008-07-17 03:51:29 +00:00
}
2009-09-09 17:01:30 +02:00
/**
* Frees the resources allocated for this result set.
* @return void
*/
final public function free()
{
if ($this->driver !== NULL) {
$this->driver->free();
$this->driver = $this->meta = NULL;
}
}
/**
* Safe access to property $driver.
* @return IDibiResultDriver
2011-07-01 07:58:27 +02:00
* @throws RuntimeException
2009-09-09 17:01:30 +02:00
*/
2012-01-19 00:12:08 +01:00
final public function getResultDriver()
2009-09-09 17:01:30 +02:00
{
if ($this->driver === NULL) {
2011-07-01 07:58:27 +02:00
throw new RuntimeException('Result-set was released from memory.');
2009-09-09 17:01:30 +02:00
}
return $this->driver;
}
/********************* rows ****************d*g**/
2008-07-17 03:51:29 +00:00
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
*/
final public function seek($row)
{
2012-01-19 00:12:08 +01:00
return ($row !== 0 || $this->fetched) ? (bool) $this->getResultDriver()->seek($row) : TRUE;
2008-07-17 03:51:29 +00:00
}
/**
2009-09-09 17:01:30 +02:00
* Required by the Countable interface.
2008-07-17 03:51:29 +00:00
* @return int
*/
2009-09-09 17:01:30 +02:00
final public function count()
{
2012-01-19 00:12:08 +01:00
return $this->getResultDriver()->getRowCount();
}
/**
2009-09-09 17:01:30 +02:00
* Returns the number of rows in a result set.
* @return int
*/
2009-09-09 17:01:30 +02:00
final public function getRowCount()
2008-07-17 03:51:29 +00:00
{
2012-01-19 00:12:08 +01:00
return $this->getResultDriver()->getRowCount();
2008-07-17 03:51:29 +00:00
}
/**
2009-09-09 17:01:30 +02:00
* Required by the IteratorAggregate interface.
* @return DibiResultIterator
2008-07-17 03:51:29 +00:00
*/
final public function getIterator()
2008-07-17 03:51:29 +00:00
{
return new DibiResultIterator($this);
2008-07-17 03:51:29 +00:00
}
2009-09-09 17:01:30 +02:00
/********************* fetching rows ****************d*g**/
2008-07-17 03:51:29 +00:00
2008-10-30 15:40:17 +00:00
/**
* Set fetched object class. This class should extend the DibiRow class.
* @param string
2013-07-02 18:42:55 +02:00
* @return self
2008-10-30 15:40:17 +00:00
*/
public function setRowClass($class)
{
2010-02-24 02:43:15 +01:00
$this->rowClass = $class;
return $this;
2008-10-30 15:40:17 +00:00
}
/**
* Returns fetched object class name.
* @return string
*/
public function getRowClass()
{
2010-02-24 02:43:15 +01:00
return $this->rowClass;
2008-10-30 15:40:17 +00:00
}
/**
* Set a factory to create fetched object instances. These should extend the DibiRow class.
* @param callback
2013-07-02 18:42:55 +02:00
* @return self
*/
public function setRowFactory($callback)
{
$this->rowFactory = $callback;
return $this;
}
2008-07-17 03:51:29 +00:00
/**
* Fetches the row at current position, process optional type conversion.
* and moves the internal cursor to the next position
* @return DibiRow|FALSE array on success, FALSE if no next record
2008-07-17 03:51:29 +00:00
*/
final public function fetch()
2008-07-17 03:51:29 +00:00
{
2012-01-19 00:12:08 +01:00
$row = $this->getResultDriver()->fetch(TRUE);
if (!is_array($row)) {
return FALSE;
2008-07-17 03:51:29 +00:00
}
$this->fetched = TRUE;
$this->normalize($row);
if ($this->rowFactory) {
return call_user_func($this->rowFactory, $row);
} elseif ($this->rowClass) {
$row = new $this->rowClass($row);
}
return $row;
2008-07-17 03:51:29 +00:00
}
/**
* Like fetch(), but returns only first field.
* @return mixed value on success, FALSE if no next record
*/
final public function fetchSingle()
2008-07-17 03:51:29 +00:00
{
2012-01-19 00:12:08 +01:00
$row = $this->getResultDriver()->fetch(TRUE);
if (!is_array($row)) {
return FALSE;
2008-07-17 03:51:29 +00:00
}
$this->fetched = TRUE;
$this->normalize($row);
return reset($row);
2008-07-17 03:51:29 +00:00
}
/**
* Fetches all records from table.
* @param int offset
* @param int limit
2013-10-24 21:15:48 +02:00
* @return DibiRow[]
2008-07-17 03:51:29 +00:00
*/
final public function fetchAll($offset = NULL, $limit = NULL)
2008-07-17 03:51:29 +00:00
{
$limit = $limit === NULL ? -1 : (int) $limit;
$this->seek((int) $offset);
$row = $this->fetch();
2013-07-02 18:42:55 +02:00
if (!$row) {
return array(); // empty result set
}
2008-07-17 03:51:29 +00:00
$data = array();
do {
2013-07-02 18:42:55 +02:00
if ($limit === 0) {
break;
}
$limit--;
$data[] = $row;
} while ($row = $this->fetch());
2008-07-17 03:51:29 +00:00
return $data;
}
/**
* Fetches all records from table and returns associative tree.
* Examples:
* - associative descriptor: col1[]col2->col3
* builds a tree: $tree[$val1][$index][$val2]->col3[$val3] = {record}
* - associative descriptor: col1|col2->col3=col4
* builds a tree: $tree[$val1][$val2]->col3[$val3] = val4
2008-07-17 03:51:29 +00:00
* @param string associative descriptor
* @return DibiRow
2008-07-17 03:51:29 +00:00
* @throws InvalidArgumentException
*/
final public function fetchAssoc($assoc)
2008-07-17 03:51:29 +00:00
{
if (strpos($assoc, ',') !== FALSE) {
return $this->oldFetchAssoc($assoc);
}
2008-07-17 03:51:29 +00:00
$this->seek(0);
$row = $this->fetch();
2013-07-02 18:42:55 +02:00
if (!$row) {
return array(); // empty result set
}
2008-07-17 03:51:29 +00:00
$data = NULL;
$assoc = preg_split('#(\[\]|->|=|\|)#', $assoc, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
2008-07-17 03:51:29 +00:00
// check columns
foreach ($assoc as $as) {
// offsetExists ignores NULL in PHP 5.2.1, isset() surprisingly NULL accepts
if ($as !== '[]' && $as !== '=' && $as !== '->' && $as !== '|' && !property_exists($row, $as)) {
2008-07-17 03:51:29 +00:00
throw new InvalidArgumentException("Unknown column '$as' in associative descriptor.");
}
}
if ($as === '->') { // must not be last
array_pop($assoc);
}
if (empty($assoc)) {
$assoc[] = '[]';
}
// make associative tree
do {
$x = & $data;
// iterative deepening
foreach ($assoc as $i => $as) {
if ($as === '[]') { // indexed-array node
$x = & $x[];
} elseif ($as === '=') { // "value" node
$x = $row->{$assoc[$i+1]};
continue 2;
} elseif ($as === '->') { // "object" node
if ($x === NULL) {
$x = clone $row;
$x = & $x->{$assoc[$i+1]};
$x = NULL; // prepare child node
} else {
$x = & $x->{$assoc[$i+1]};
}
} elseif ($as !== '|') { // associative-array node
$x = & $x[$row->$as];
}
}
if ($x === NULL) { // build leaf
$x = $row;
}
} while ($row = $this->fetch());
unset($x);
return $data;
}
/**
* @deprecated
*/
private function oldFetchAssoc($assoc)
{
$this->seek(0);
$row = $this->fetch();
2013-07-02 18:42:55 +02:00
if (!$row) {
return array(); // empty result set
}
$data = NULL;
$assoc = explode(',', $assoc);
2008-07-17 03:51:29 +00:00
// strip leading = and @
$leaf = '@'; // gap
2008-07-17 03:51:29 +00:00
$last = count($assoc) - 1;
while ($assoc[$last] === '=' || $assoc[$last] === '@') {
$leaf = $assoc[$last];
unset($assoc[$last]);
$last--;
if ($last < 0) {
$assoc[] = '#';
break;
}
}
do {
$x = & $data;
foreach ($assoc as $i => $as) {
if ($as === '#') { // indexed-array node
$x = & $x[];
} elseif ($as === '=') { // "record" node
if ($x === NULL) {
2010-04-26 20:44:17 +02:00
$x = $row->toArray();
2008-07-17 03:51:29 +00:00
$x = & $x[ $assoc[$i+1] ];
$x = NULL; // prepare child node
} else {
$x = & $x[ $assoc[$i+1] ];
}
} elseif ($as === '@') { // "object" node
if ($x === NULL) {
$x = clone $row;
2008-07-17 03:51:29 +00:00
$x = & $x->{$assoc[$i+1]};
$x = NULL; // prepare child node
} else {
$x = & $x->{$assoc[$i+1]};
}
} else { // associative-array node
2009-10-06 16:51:27 +02:00
$x = & $x[$row->$as];
2008-07-17 03:51:29 +00:00
}
}
if ($x === NULL) { // build leaf
if ($leaf === '=') {
2010-04-26 20:44:17 +02:00
$x = $row->toArray();
} else {
$x = $row;
}
2008-07-17 03:51:29 +00:00
}
} while ($row = $this->fetch());
2008-07-17 03:51:29 +00:00
unset($x);
return $data;
}
/**
* Fetches all records from table like $key => $value pairs.
* @param string associative key
* @param string value
* @return array
* @throws InvalidArgumentException
*/
final public function fetchPairs($key = NULL, $value = NULL)
2008-07-17 03:51:29 +00:00
{
$this->seek(0);
$row = $this->fetch();
2013-07-02 18:42:55 +02:00
if (!$row) {
return array(); // empty result set
}
2008-07-17 03:51:29 +00:00
$data = array();
if ($value === NULL) {
if ($key !== NULL) {
throw new InvalidArgumentException("Either none or both columns must be specified.");
}
// autodetect
2010-04-26 20:44:17 +02:00
$tmp = array_keys($row->toArray());
2008-07-17 03:51:29 +00:00
$key = $tmp[0];
if (count($row) < 2) { // indexed-array
do {
$data[] = $row[$key];
} while ($row = $this->fetch());
return $data;
}
2008-07-17 03:51:29 +00:00
$value = $tmp[1];
} else {
if (!property_exists($row, $value)) {
2008-07-17 03:51:29 +00:00
throw new InvalidArgumentException("Unknown value column '$value'.");
}
if ($key === NULL) { // indexed-array
do {
$data[] = $row[$value];
} while ($row = $this->fetch());
2008-07-17 03:51:29 +00:00
return $data;
}
if (!property_exists($row, $key)) {
2008-07-17 03:51:29 +00:00
throw new InvalidArgumentException("Unknown key column '$key'.");
}
}
do {
$data[ (string) $row[$key] ] = $row[$value];
} while ($row = $this->fetch());
2008-07-17 03:51:29 +00:00
return $data;
}
/********************* column types ****************d*g**/
2009-09-09 17:01:30 +02:00
2008-07-17 03:51:29 +00:00
/**
* Autodetect column types.
* @return void
2008-07-17 03:51:29 +00:00
*/
private function detectTypes()
2008-07-17 03:51:29 +00:00
{
$cache = DibiColumnInfo::getTypeCache();
try {
2012-01-19 00:12:08 +01:00
foreach ($this->getResultDriver()->getResultColumns() as $col) {
$this->types[$col['name']] = $cache->{$col['nativetype']};
}
} catch (DibiNotSupportedException $e) {}
2008-07-17 03:51:29 +00:00
}
/**
* Converts values to specified type and format.
* @param array
* @return void
*/
private function normalize(array & $row)
{
foreach ($this->types as $key => $type) {
if (!isset($row[$key])) { // NULL
continue;
}
$value = $row[$key];
if ($value === FALSE || $type === dibi::TEXT) {
} elseif ($type === dibi::INTEGER) {
$row[$key] = is_float($tmp = $value * 1) ? $value : $tmp;
} elseif ($type === dibi::FLOAT) {
$row[$key] = str_replace(',', '.', ltrim((string) ($tmp = (float) $value), '0')) === ltrim(rtrim(rtrim($value, '0'), '.'), '0') ? $tmp : $value;
} elseif ($type === dibi::BOOL) {
$row[$key] = ((bool) $value) && $value !== 'f' && $value !== 'F';
} elseif ($type === dibi::DATE || $type === dibi::DATETIME) {
if ((int) $value !== 0 || substr((string) $value, 0, 3) === '00:') { // '', NULL, FALSE, '0000-00-00', ...
$value = new DibiDateTime($value);
$row[$key] = empty($this->formats[$type]) ? $value : $value->format($this->formats[$type]);
}
} elseif ($type === dibi::BINARY) {
2012-01-19 00:12:08 +01:00
$row[$key] = $this->getResultDriver()->unescape($value, $type);
}
}
}
2008-07-17 03:51:29 +00:00
/**
* Define column type.
* @param string column
* @param string type (use constant Dibi::*)
2013-07-02 18:42:55 +02:00
* @return self
2008-07-17 03:51:29 +00:00
*/
final public function setType($col, $type)
2008-07-17 03:51:29 +00:00
{
$this->types[$col] = $type;
return $this;
2008-07-17 03:51:29 +00:00
}
/**
* Returns column type.
* @return string
2008-07-17 03:51:29 +00:00
*/
final public function getType($col)
{
2010-02-24 02:43:15 +01:00
return isset($this->types[$col]) ? $this->types[$col] : NULL;
2008-07-17 03:51:29 +00:00
}
2012-01-18 21:08:34 +01:00
/**
* Sets data format.
* @param string type (use constant Dibi::*)
* @param string format
2013-07-02 18:42:55 +02:00
* @return self
2012-01-18 21:08:34 +01:00
*/
final public function setFormat($type, $format)
{
$this->formats[$type] = $format;
return $this;
}
/**
* Returns data format.
* @return string
*/
final public function getFormat($type)
{
return isset($this->formats[$type]) ? $this->formats[$type] : NULL;
}
/********************* meta info ****************d*g**/
2008-07-17 03:51:29 +00:00
2009-09-09 17:01:30 +02:00
/**
* Returns a meta information about the current result set.
* @return DibiResultInfo
2009-09-09 17:01:30 +02:00
*/
public function getInfo()
2009-09-09 17:01:30 +02:00
{
if ($this->meta === NULL) {
2012-01-19 00:12:08 +01:00
$this->meta = new DibiResultInfo($this->getResultDriver());
2009-09-09 17:01:30 +02:00
}
return $this->meta;
}
2008-07-17 03:51:29 +00:00
/**
* @deprecated
2008-07-17 03:51:29 +00:00
*/
final public function getColumns()
2008-07-17 03:51:29 +00:00
{
return $this->getInfo()->getColumns();
}
2009-09-09 17:01:30 +02:00
/********************* misc tools ****************d*g**/
2008-07-17 03:51:29 +00:00
/**
* Displays complete result set as HTML or text table for debug purposes.
2008-07-17 03:51:29 +00:00
* @return void
*/
final public function dump()
{
$i = 0;
$this->seek(0);
if (PHP_SAPI === 'cli') {
$hasColors = (substr(getenv('TERM'), 0, 5) === 'xterm');
$maxLen = 0;
while ($row = $this->fetch()) {
if ($i === 0) {
foreach ($row as $col => $foo) {
$len = mb_strlen($col);
2013-07-02 18:42:55 +02:00
$maxLen = max($len, $maxLen);
}
}
2008-07-17 03:51:29 +00:00
if ($hasColors) {
echo "\033[1;37m#row: $i\033[0m\n";
} else {
echo "#row: $i\n";
2008-07-17 03:51:29 +00:00
}
foreach ($row as $col => $val) {
$spaces = $maxLen - mb_strlen($col) + 2;
echo "$col" . str_repeat(" ", $spaces) . "$val\n";
}
2008-07-17 03:51:29 +00:00
echo "\n";
$i++;
2008-07-17 03:51:29 +00:00
}
2013-07-02 18:42:55 +02:00
if ($i === 0) {
echo "empty result set\n";
}
echo "\n";
2008-07-17 03:51:29 +00:00
} else {
while ($row = $this->fetch()) {
if ($i === 0) {
echo "\n<table class=\"dump\">\n<thead>\n\t<tr>\n\t\t<th>#row</th>\n";
foreach ($row as $col => $foo) {
echo "\t\t<th>" . htmlSpecialChars($col) . "</th>\n";
}
echo "\t</tr>\n</thead>\n<tbody>\n";
}
echo "\t<tr>\n\t\t<th>", $i, "</th>\n";
foreach ($row as $col) {
//if (is_object($col)) $col = $col->__toString();
echo "\t\t<td>", htmlSpecialChars($col), "</td>\n";
}
echo "\t</tr>\n";
$i++;
}
if ($i === 0) {
echo '<p><em>empty result set</em></p>';
} else {
echo "</tbody>\n</table>\n";
}
2008-07-17 03:51:29 +00:00
}
}
}