1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-12 09:04:24 +02:00

BIG REFACTORING!

* DibiDriver -> DibiConnection
This commit is contained in:
David Grudl
2007-11-12 06:41:59 +00:00
parent ea00d5d37d
commit 22c27f678a
16 changed files with 1052 additions and 1335 deletions

View File

@@ -20,14 +20,14 @@
/**
* dibi Common Driver
* dibi connection
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
abstract class DibiDriver extends NObject
class DibiConnection extends NObject
{
/**
* Current connection configuration
@@ -36,33 +36,47 @@ abstract class DibiDriver extends NObject
private $config;
/**
* Connection resource
* @var resource
*/
private $connection;
/**
* Describes how convert some datatypes to SQL command
* DibiDriverInterface
* @var array
*/
public $formats = array(
'TRUE' => "1", // boolean true
'FALSE' => "0", // boolean false
'date' => "'Y-m-d'", // format used by date()
'datetime' => "'Y-m-d H:i:s'", // format used by date()
);
private $driver;
/**
* Is connected?
* @var bool
*/
private $connected = FALSE;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @param array|string connection parameters
* @throws DibiException
*/
public function __construct(array $config)
public function __construct($config)
{
// DSN string
if (is_string($config)) {
parse_str($config, $config);
}
if (!isset($config['driver'])) {
$config['driver'] = dibi::$defaultDriver;
}
$class = "Dibi$config[driver]Driver";
if (!class_exists($class)) {
include_once __FILE__ . "/../../drivers/$config[driver].php";
if (!class_exists($class)) {
throw new DibiException("Unable to create instance of dibi driver class '$class'.");
}
}
$this->config = $config;
$this->driver = new $class;
if (empty($config['lazy'])) {
$this->connect();
@@ -88,9 +102,10 @@ abstract class DibiDriver extends NObject
*
* @return void
*/
final public function connect()
final protected function connect()
{
$this->connection = $this->doConnect();
$this->driver->connect($this->config);
$this->connected = TRUE;
dibi::notify('connected');
}
@@ -103,9 +118,11 @@ abstract class DibiDriver extends NObject
*/
final public function disconnect()
{
$this->doDisconnect();
$this->connection = NULL;
dibi::notify('disconnected');
if ($this->connected) {
$this->driver->disconnect();
$this->connected = FALSE;
dibi::notify('disconnected');
}
}
@@ -113,7 +130,7 @@ abstract class DibiDriver extends NObject
/**
* Returns configuration variable. If no $key is passed, returns the entire array.
*
* @see DibiDriver::__construct
* @see self::__construct
* @param string
* @param mixed default value to use if key not found
* @return mixed
@@ -133,18 +150,36 @@ abstract class DibiDriver extends NObject
/**
* Apply configuration alias or default values
*
* @param array connect configuration
* @param string key
* @param string alias key
* @return void
*/
public static function alias(&$config, $key, $alias=NULL)
{
if (isset($config[$key])) return;
if ($alias !== NULL && isset($config[$alias])) {
$config[$key] = $config[$alias];
unset($config[$alias]);
} else {
$config[$key] = NULL;
}
}
/**
* Returns the connection resource
*
* @return resource
*/
final public function getConnection()
final public function getResource()
{
if ($this->connection === NULL) {
$this->connect();
}
return $this->connection;
return $this->driver->getResource();
}
@@ -160,7 +195,7 @@ abstract class DibiDriver extends NObject
{
if (!is_array($args)) $args = func_get_args();
$trans = new DibiTranslator($this);
$trans = new DibiTranslator($this->driver);
if ($trans->translate($args)) {
return $this->nativeQuery($trans->sql);
} else {
@@ -180,7 +215,7 @@ abstract class DibiDriver extends NObject
{
if (!is_array($args)) $args = func_get_args();
$trans = new DibiTranslator($this);
$trans = new DibiTranslator($this->driver);
$ok = $trans->translate($args);
dibi::dump($trans->sql);
return $ok;
@@ -197,74 +232,30 @@ abstract class DibiDriver extends NObject
*/
final public function nativeQuery($sql)
{
if (!$this->connected) $this->connect();
dibi::notify('beforeQuery', $this, $sql);
$res = $this->doQuery($sql);
$res = $this->driver->query($sql);
$res = $res ? new DibiResult(clone $this->driver) : TRUE; // backward compatibility - will be changed to NULL
dibi::notify('afterQuery', $this, $res);
// backward compatibility - will be removed!
return $res instanceof DibiResult ? $res : TRUE;
return $res;
}
/**
* Apply configuration alias or default values
*
* @param array connect configuration
* @param string key
* @param string alias key
* @return void
*/
protected static function alias(&$config, $key, $alias=NULL)
{
if (isset($config[$key])) return;
if ($alias !== NULL && isset($config[$alias])) {
$config[$key] = $config[$alias];
unset($config[$alias]);
} else {
$config[$key] = NULL;
}
}
/**
* Internal: Connects to a database
*
* @throws DibiException
* @return resource
*/
abstract protected function doConnect();
/**
* Internal: Disconnects from a database
*
* @throws DibiException
* @return void
*/
abstract protected function doDisconnect();
/**
* Internal: Executes the SQL query
*
* @param string SQL statement.
* @return DibiResult Result set object
* @throws DibiDatabaseException
*/
abstract protected function doQuery($sql);
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query
*
* @return int number of rows or FALSE on error
*/
abstract public function affectedRows();
public function affectedRows()
{
$rows = $this->driver->affectedRows();
return $rows < 0 ? FALSE : $rows;
}
@@ -273,7 +264,11 @@ abstract class DibiDriver extends NObject
*
* @return int|FALSE int on success or FALSE on failure
*/
abstract public function insertId();
public function insertId($sequence = NULL)
{
$id = $this->driver->insertId($sequence);
return $id < 1 ? FALSE : $id;
}
@@ -281,7 +276,12 @@ abstract class DibiDriver extends NObject
* Begins a transaction (if supported).
* @return void
*/
abstract public function begin();
public function begin()
{
if (!$this->connected) $this->connect();
$this->driver->begin();
dibi::notify('begin', $this);
}
@@ -289,7 +289,12 @@ abstract class DibiDriver extends NObject
* Commits statements in a transaction.
* @return void
*/
abstract public function commit();
public function commit()
{
if (!$this->connected) $this->connect();
$this->driver->commit();
dibi::notify('commit', $this);
}
@@ -297,7 +302,65 @@ abstract class DibiDriver extends NObject
* Rollback changes in a transaction.
* @return void
*/
abstract public function rollback();
public function rollback()
{
if (!$this->connected) $this->connect();
$this->driver->rollback();
dibi::notify('rollback', $this);
}
/**
* Escapes the string
*
* @param string unescaped string
* @return string escaped and optionally quoted string
*/
public function escape($value)
{
return $this->driver->format($value, dibi::FIELD_TEXT);
}
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return $this->driver->format($value, dibi::IDENTIFIER);
}
/**
* Injects LIMIT/OFFSET to the SQL query
*
* @param string &$sql The SQL query that will be modified.
* @param int $limit
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset)
{
$this->driver->applyLimit($sql, $limit, $offset);
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
}
@@ -312,45 +375,4 @@ abstract class DibiDriver extends NObject
/**
* Escapes the string
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
*/
abstract public function escape($value, $appendQuotes = TRUE);
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
abstract public function delimite($value);
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
abstract public function getDibiReflection();
/**
* Injects LIMIT/OFFSET to the SQL query
*
* @param string &$sql The SQL query that will be modified.
* @param int $limit
* @param int $offset
* @return void
*/
abstract public function applyLimit(&$sql, $limit, $offset = 0);
} // class DibiDriver
}

View File

@@ -67,11 +67,7 @@ class DibiDatabaseException extends DibiException
public function __toString()
{
$s = parent::__toString();
if ($this->sql) {
$s .= "\nSQL: " . $this->sql;
}
return $s;
return parent::__toString() . ($this->sql ? "\nSQL: " . $this->sql : '');
}

View File

@@ -58,14 +58,14 @@ final class DibiLogger extends NObject
* @param mixed
* @return void
*/
public function handler($event, $driver, $arg)
public function handler($event, $connection, $arg)
{
if ($event === 'afterQuery' && $this->logQueries) {
$this->write(
"OK: " . dibi::$sql
. ($arg instanceof DibiResult ? ";\n-- rows: " . $arg->rowCount() : '')
. "\n-- takes: " . sprintf('%0.3f', dibi::$elapsedTime * 1000) . ' ms'
. "\n-- driver: " . $driver->getConfig('driver')
. "\n-- driver: " . $connection->getConfig('driver')
. "\n-- " . date('Y-m-d H:i:s')
. "\n\n"
);
@@ -83,7 +83,7 @@ final class DibiLogger extends NObject
$this->write(
"ERROR: $message"
. "\n-- SQL: " . dibi::$sql
. "\n-- driver: " //. $driver->getConfig('driver')
. "\n-- driver: " //. $connection->getConfig('driver')
. ";\n-- " . date('Y-m-d H:i:s')
. "\n\n"
);

View File

@@ -40,8 +40,14 @@
* @package dibi
* @version $Revision$ $Date$
*/
abstract class DibiResult extends NObject implements IteratorAggregate, Countable
class DibiResult extends NObject implements IteratorAggregate, Countable
{
/**
* DibiDriverInterface
* @var array
*/
private $driver;
/**
* Describes columns types
* @var array
@@ -54,18 +60,6 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/
protected $meta;
/**
* Resultset resource
* @var resource
*/
protected $resource;
/**
* Is buffered (seekable and countable)?
* @var bool
*/
protected $buffered;
/**
* Already fetched? Used for allowance for first seek(0)
* @var bool
@@ -86,21 +80,20 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
public function __construct($resource, $buffered)
public function __construct($driver)
{
$this->resource = $resource;
$this->buffered = $buffered;
$this->driver = $driver;
}
/**
* Returns the resultset resource
*
* @return resource
* @return mixed
*/
final public function getResource()
{
return $this->resource;
return $this->driver->getResultResource();
}
@@ -118,11 +111,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
return TRUE;
}
if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
return $this->doSeek($row);
$this->driver->seek($row);
}
@@ -134,54 +123,11 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/
final public function rowCount()
{
if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
return $this->doRowCount();
return $this->driver->rowCount();
}
/**
* Internal: Moves cursor position without fetching row
*
* @param int the 0-based cursor pos to seek to
* @return void
* @throws DibiException
*/
abstract protected function doSeek($row);
/**
* Internal: Returns the number of rows in a result set
*
* @return int
*/
abstract protected function doRowCount();
/**
* Internal: Frees the resources allocated for this result set
*
* @return void
*/
abstract protected function doFree();
/**
* Fetches the row at current position and moves the internal cursor to the next position
* internal usage only
*
* @return array|FALSE array on success, FALSE if no next record
*/
abstract protected function doFetch();
/**
* Fetches the row at current position, process optional type conversion
* and moves the internal cursor to the next position
@@ -190,7 +136,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/
final public function fetch()
{
$row = $this->doFetch();
$row = $this->driver->fetch();
if (!is_array($row)) return FALSE;
$this->fetched = TRUE;
@@ -215,7 +161,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/
final function fetchSingle()
{
$row = $this->doFetch();
$row = $this->driver->fetch();
if (!is_array($row)) return FALSE;
$this->fetched = TRUE;
@@ -395,7 +341,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/
public function __destruct()
{
@$this->doFree();
@$this->driver->free();
}
@@ -403,7 +349,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
final public function setType($field, $type = NULL)
{
if ($field === TRUE) {
$this->detectTypes();
$this->buildMeta();
} elseif (is_array($field)) {
$this->convert = $field;
@@ -434,14 +380,10 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
return $value;
}
if ($type === dibi::FIELD_DATE) {
if ($type === dibi::FIELD_DATE || $type === dibi::FIELD_DATETIME) {
return strtotime($value); // !!! not good
}
if ($type === dibi::FIELD_DATETIME) {
return strtotime($value); // !!! not good
}
return $value;
}
@@ -454,10 +396,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/
final public function getFields()
{
// lazy init
if ($this->meta === NULL) {
$this->buildMeta();
}
$this->buildMeta();
return array_keys($this->meta);
}
@@ -471,10 +410,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/
final public function getMetaData($field)
{
// lazy init
if ($this->meta === NULL) {
$this->buildMeta();
}
$this->buildMeta();
return isset($this->meta[$field]) ? $this->meta[$field] : FALSE;
}
@@ -485,22 +421,18 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*
* @return void
*/
final protected function detectTypes()
final protected function buildMeta()
{
if ($this->meta === NULL) {
$this->buildMeta();
$this->meta = $this->driver->buildMeta();
foreach ($this->meta as $name => $info) {
$this->convert[$name] = $info['type'];
}
}
}
/**
* @return void
*/
abstract protected function buildMeta();
/**
* Displays complete result-set as HTML table for debug purposes
*
@@ -553,4 +485,4 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
}
} // class DibiResult
}

View File

@@ -124,5 +124,4 @@ final class DibiResultIterator implements Iterator
}
} // class DibiResultIterator
}

View File

@@ -35,7 +35,7 @@ final class DibiTranslator extends NObject
/** @var string NOT USED YET */
public $mask;
/** @var DibiDriver */
/** @var DibiDriverInterface */
private $driver;
/** @var string last modifier */
@@ -55,7 +55,7 @@ final class DibiTranslator extends NObject
public function __construct(DibiDriver $driver)
public function __construct(DibiDriverInterface $driver)
{
$this->driver = $driver;
}
@@ -105,7 +105,7 @@ final class DibiTranslator extends NObject
if (is_string($arg) && (!$mod || $mod === 'sql')) {
$mod = FALSE;
// will generate new mod
$mask[] = $sql[] = $this->formatValue($arg, 'sql');
/*$mask[] =*/ $sql[] = $this->formatValue($arg, 'sql');
continue;
}
@@ -117,13 +117,13 @@ final class DibiTranslator extends NObject
$mod = $commandIns ? 'v' : 'a';
} else {
$mod = $commandIns ? 'l' : 'a';
if ($lastArr === $i - 1) $mask[] = $sql[] = ',';
if ($lastArr === $i - 1) /*$mask[] =*/ $sql[] = ',';
}
$lastArr = $i;
}
// default processing
$mask[] = '?';
//$mask[] = '?';
if (!$comment) {
$sql[] = $this->formatValue($arg, $mod);
}
@@ -132,7 +132,7 @@ final class DibiTranslator extends NObject
if ($comment) $sql[] = "\0";
//$this->mask = implode(' ', $mask);
/*$this->mask = implode(' ', $mask);*/
$this->sql = implode(' ', $sql);
@@ -218,15 +218,13 @@ final class DibiTranslator extends NObject
switch ($modifier) {
case 's': // string
return $this->driver->escape($value);
return $this->driver->format($value, dibi::FIELD_TEXT);
case 'sn': // string or NULL
return $value == '' ? 'NULL' : $this->driver->escape($value);
return $value == '' ? 'NULL' : $this->driver->format($value, dibi::FIELD_TEXT); // notice two equal signs
case 'b': // boolean
return $value
? $this->driver->formats['TRUE']
: $this->driver->formats['FALSE'];
return $this->driver->format($value, dibi::FIELD_BOOL);
case 'i': // signed int
case 'u': // unsigned int, ignored
@@ -244,14 +242,10 @@ final class DibiTranslator extends NObject
return (string) ($value + 0);
case 'd': // date
return date($this->driver->formats['date'], is_string($value)
? strtotime($value)
: $value);
return $this->driver->format(is_string($value) ? strtotime($value) : $value, dibi::FIELD_DATE);
case 't': // datetime
return date($this->driver->formats['datetime'], is_string($value)
? strtotime($value)
: $value);
return $this->driver->format(is_string($value) ? strtotime($value) : $value, dibi::FIELD_DATETIME);
case 'n': // identifier name
return $this->delimite($value);
@@ -306,13 +300,13 @@ final class DibiTranslator extends NObject
// without modifier procession
if (is_string($value))
return $this->driver->escape($value);
return $this->driver->format($value, dibi::FIELD_TEXT);
if (is_int($value) || is_float($value))
return (string) $value; // something like -9E-005 is accepted by SQL
if (is_bool($value))
return $value ? $this->driver->formats['TRUE'] : $this->driver->formats['FALSE'];
return $this->driver->format($value, dibi::FIELD_BOOL);
if ($value === NULL)
return 'NULL';
@@ -388,10 +382,10 @@ final class DibiTranslator extends NObject
return $this->delimite($matches[2]);
if ($matches[3]) // SQL strings: '....'
return $this->driver->escape( str_replace("''", "'", $matches[4]));
return $this->driver->format( str_replace("''", "'", $matches[4]), dibi::FIELD_TEXT);
if ($matches[5]) // SQL strings: "..."
return $this->driver->escape( str_replace('""', '"', $matches[6]));
return $this->driver->format( str_replace('""', '"', $matches[6]), dibi::FIELD_TEXT);
if ($matches[9]) { // string quote
@@ -415,7 +409,7 @@ final class DibiTranslator extends NObject
if (strpos($value, ':') !== FALSE) {
$value = strtr($value, dibi::getSubst());
}
return $this->driver->delimite($value);
return $this->driver->format($value, dibi::IDENTIFIER);
}