1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-04 05:07:36 +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

@@ -33,7 +33,8 @@ if (version_compare(PHP_VERSION , '5.1.0', '<')) {
// libraries // libraries
require_once __FILE__ . '/../libs/NObject.php'; require_once __FILE__ . '/../libs/NObject.php';
require_once __FILE__ . '/../libs/DibiException.php'; require_once __FILE__ . '/../libs/DibiException.php';
require_once __FILE__ . '/../libs/DibiDriver.php'; require_once __FILE__ . '/../libs/DibiConnection.php';
require_once __FILE__ . '/../libs/DibiDriverInterface.php';
require_once __FILE__ . '/../libs/DibiResult.php'; require_once __FILE__ . '/../libs/DibiResult.php';
require_once __FILE__ . '/../libs/DibiResultIterator.php'; require_once __FILE__ . '/../libs/DibiResultIterator.php';
require_once __FILE__ . '/../libs/DibiTranslator.php'; require_once __FILE__ . '/../libs/DibiTranslator.php';
@@ -43,26 +44,6 @@ require_once __FILE__ . '/../libs/DibiLogger.php';
/**
* Interface for user variable, used for generating SQL
* @package dibi
*/
interface DibiVariableInterface
{
/**
* Format for SQL
*
* @param object destination DibiDriver
* @param string optional modifier
* @return string SQL code
*/
public function toSQL($driver, $modifier = NULL);
}
/** /**
* Interface for database drivers * Interface for database drivers
* *
@@ -90,21 +71,22 @@ class dibi extends NClass
FIELD_UNKNOWN = '?', FIELD_UNKNOWN = '?',
// special // special
FIELD_COUNTER = 'c', // counter or autoincrement, is integer FIELD_COUNTER = 'C', // counter or autoincrement, is integer
IDENTIFIER = 'I',
// dibi version // dibi version
VERSION = '0.9 (Revision: $WCREV$, Date: $WCDATE$)'; VERSION = '0.9 (Revision: $WCREV$, Date: $WCDATE$)';
/** /**
* Connection registry storage for DibiDriver objects * Connection registry storage for DibiConnection objects
* @var DibiDriver[] * @var DibiConnection[]
*/ */
private static $registry = array(); private static $registry = array();
/** /**
* Current connection * Current connection
* @var DibiDriver * @var DibiConnection
*/ */
private static $connection; private static $connection;
@@ -161,41 +143,22 @@ class dibi extends NClass
/** /**
* Creates a new DibiDriver object and connects it to specified database * Creates a new DibiConnection object and connects it to specified database
* *
* @param array|string connection parameters * @param array|string connection parameters
* @param string connection name * @param string connection name
* @return DibiDriver * @return DibiConnection
* @throws DibiException * @throws DibiException
*/ */
public static function connect($config = array(), $name = 0) public static function connect($config = array(), $name = 0)
{ {
// DSN string return self::$connection = self::$registry[$name] = new DibiConnection($config);
if (is_string($config)) {
parse_str($config, $config);
}
if (!isset($config['driver'])) {
$config['driver'] = self::$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'.");
}
}
// create connection object and store in list; like $connection = $class::connect($config);
return self::$connection = self::$registry[$name] = new $class($config);
} }
/** /**
* Disconnects from database (doesn't destroy DibiDriver object) * Disconnects from database (doesn't destroy DibiConnection object)
* *
* @return void * @return void
*/ */
@@ -222,7 +185,7 @@ class dibi extends NClass
* Retrieve active connection * Retrieve active connection
* *
* @param string connection registy name * @param string connection registy name
* @return object DibiDriver object. * @return object DibiConnection object.
* @throws DibiException * @throws DibiException
*/ */
public static function getConnection($name = NULL) public static function getConnection($name = NULL)
@@ -259,7 +222,7 @@ class dibi extends NClass
/** /**
* Generates and executes SQL query - Monostate for DibiDriver::query() * Generates and executes SQL query - Monostate for DibiConnection::query()
* *
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiResult Result set object (if any) * @return DibiResult Result set object (if any)
@@ -275,7 +238,7 @@ class dibi extends NClass
/** /**
* Executes the SQL query - Monostate for DibiDriver::nativeQuery() * Executes the SQL query - Monostate for DibiConnection::nativeQuery()
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object (if any) * @return DibiResult Result set object (if any)
@@ -288,7 +251,7 @@ class dibi extends NClass
/** /**
* Generates and prints SQL query - Monostate for DibiDriver::test() * Generates and prints SQL query - Monostate for DibiConnection::test()
* *
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return bool * @return bool
@@ -304,7 +267,7 @@ class dibi extends NClass
/** /**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query
* Monostate for DibiDriver::insertId() * Monostate for DibiConnection::insertId()
* *
* @param string optional sequence name for DibiPostgreDriver * @param string optional sequence name for DibiPostgreDriver
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
@@ -318,7 +281,7 @@ class dibi extends NClass
/** /**
* Gets the number of affected rows * Gets the number of affected rows
* Monostate for DibiDriver::affectedRows() * Monostate for DibiConnection::affectedRows()
* *
* @return int number of rows or FALSE on error * @return int number of rows or FALSE on error
*/ */
@@ -330,7 +293,7 @@ class dibi extends NClass
/** /**
* Begins a transaction - Monostate for DibiDriver::begin() * Begins a transaction - Monostate for DibiConnection::begin()
*/ */
public static function begin() public static function begin()
{ {
@@ -340,7 +303,7 @@ class dibi extends NClass
/** /**
* Commits statements in a transaction - Monostate for DibiDriver::commit() * Commits statements in a transaction - Monostate for DibiConnection::commit()
*/ */
public static function commit() public static function commit()
{ {
@@ -350,7 +313,7 @@ class dibi extends NClass
/** /**
* Rollback changes in a transaction - Monostate for DibiDriver::rollback() * Rollback changes in a transaction - Monostate for DibiConnection::rollback()
*/ */
public static function rollback() public static function rollback()
{ {
@@ -434,11 +397,11 @@ class dibi extends NClass
* Event notification (events: exception, connected, beforeQuery, afterQuery, begin, commit, rollback) * Event notification (events: exception, connected, beforeQuery, afterQuery, begin, commit, rollback)
* *
* @param string event name * @param string event name
* @param DibiDriver * @param DibiConnection
* @param mixed * @param mixed
* @return void * @return void
*/ */
public static function notify($event, DibiDriver $driver = NULL, $arg = NULL) public static function notify($event, DibiConnection $conn = NULL, $arg = NULL)
{ {
if ($event === 'beforeQuery') { if ($event === 'beforeQuery') {
self::$numOfQueries++; self::$numOfQueries++;
@@ -452,7 +415,7 @@ class dibi extends NClass
} }
foreach (self::$handlers as $handler) { foreach (self::$handlers as $handler) {
call_user_func($handler, $event, $driver, $arg); call_user_func($handler, $event, $conn, $arg);
} }
} }

View File

@@ -33,33 +33,21 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiMsSqlDriver extends DibiDriver class DibiMsSqlDriver extends NObject implements DibiDriverInterface
{ {
/** /**
* Describes how convert some datatypes to SQL command * Connection resource
* @var array * @var resource
*/ */
public $formats = array( private $connection;
'TRUE' => "-1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
/** /**
* Creates object and (optionally) connects to a database * Resultset resource
* * @var resource
* @param array connect configuration
* @throws DibiException
*/ */
public function __construct(array $config) private $resultset;
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'host');
parent::__construct($config);
}
@@ -67,31 +55,32 @@ class DibiMsSqlDriver extends DibiDriver
* Connects to a database * Connects to a database
* *
* @throws DibiException * @throws DibiException
* @return resource * @return void
*/ */
protected function doConnect() public function connect(array &$config)
{ {
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'host');
if (!extension_loaded('mssql')) { if (!extension_loaded('mssql')) {
throw new DibiException("PHP extension 'mssql' is not loaded"); throw new DibiException("PHP extension 'mssql' is not loaded");
} }
$config = $this->getConfig();
if (empty($config['persistent'])) { if (empty($config['persistent'])) {
$connection = @mssql_connect($config['host'], $config['username'], $config['password'], TRUE); $this->connection = @mssql_connect($config['host'], $config['username'], $config['password'], TRUE);
} else { } else {
$connection = @mssql_pconnect($config['host'], $config['username'], $config['password']); $this->connection = @mssql_pconnect($config['host'], $config['username'], $config['password']);
} }
if (!is_resource($connection)) { if (!is_resource($this->connection)) {
throw new DibiDatabaseException("Can't connect to DB"); throw new DibiDatabaseException("Can't connect to DB");
} }
if (isset($config['database']) && !@mssql_select_db($config['database'], $connection)) { if (isset($config['database']) && !@mssql_select_db($config['database'], $this->connection)) {
throw new DibiDatabaseException("Can't select DB '$config[database]'"); throw new DibiDatabaseException("Can't select DB '$config[database]'");
} }
return $connection;
} }
@@ -101,29 +90,29 @@ class DibiMsSqlDriver extends DibiDriver
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
mssql_close($this->getConnection()); mssql_close($this->connection);
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql) public function query($sql)
{ {
$res = @mssql_query($sql, $this->getConnection()); $this->resultset = @mssql_query($sql, $this->connection);
if ($res === FALSE) { if ($this->resultset === FALSE) {
throw new DibiDatabaseException('Query error', 0, $sql); throw new DibiDatabaseException('Query error', 0, $sql);
} }
return is_resource($res) ? new DibiMSSqlResult($res, TRUE) : NULL; return is_resource($this->resultset);
} }
@@ -135,8 +124,7 @@ class DibiMsSqlDriver extends DibiDriver
*/ */
public function affectedRows() public function affectedRows()
{ {
$rows = mssql_rows_affected($this->getConnection()); return mssql_rows_affected($this->connection);
return $rows < 0 ? FALSE : $rows;
} }
@@ -146,7 +134,7 @@ class DibiMsSqlDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId() public function insertId($sequence)
{ {
throw new BadMethodCallException(__METHOD__ . ' is not implemented'); throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -159,8 +147,7 @@ class DibiMsSqlDriver extends DibiDriver
*/ */
public function begin() public function begin()
{ {
$this->doQuery('BEGIN TRANSACTION'); $this->query('BEGIN TRANSACTION');
dibi::notify('begin', $this);
} }
@@ -171,8 +158,7 @@ class DibiMsSqlDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$this->doQuery('COMMIT'); $this->query('COMMIT');
dibi::notify('commit', $this);
} }
@@ -183,50 +169,26 @@ class DibiMsSqlDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$this->doQuery('ROLLBACK'); $this->query('ROLLBACK');
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
$value = str_replace("'", "''", $value); if ($type === dibi::FIELD_TEXT) return "'" . str_replace("'", "''", $value) . "'";
return $appendQuotes if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $value) . ']';
? "'" . $value . "'" if ($type === dibi::FIELD_BOOL) return $value ? -1 : 0;
: $value; if ($type === dibi::FIELD_DATE) return date("'Y-m-d'", $value);
} if ($type === dibi::FIELD_DATETIME) return date("'Y-m-d H:i:s'", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return '[' . str_replace('.', '].[', $value) . ']';
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -239,7 +201,7 @@ class DibiMsSqlDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
// offset suppot is missing... // offset suppot is missing...
if ($limit >= 0) { if ($limit >= 0) {
@@ -252,35 +214,16 @@ class DibiMsSqlDriver extends DibiDriver
} }
} // DibiMsSqlDriver
/**
* The dibi result-set class for MS SQL database
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiMSSqlResult extends DibiResult
{
/** /**
* Returns the number of rows in a result set * Returns the number of rows in a result set
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
return mssql_num_rows($this->resource); return mssql_num_rows($this->resultset);
} }
@@ -291,9 +234,9 @@ class DibiMSSqlResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
return mssql_fetch_assoc($this->resource); return mssql_fetch_assoc($this->resultset);
} }
@@ -305,9 +248,9 @@ class DibiMSSqlResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
if (!mssql_data_seek($this->resource, $row)) { if (!mssql_data_seek($this->resultset, $row)) {
throw new DibiDriverException('Unable to seek to row ' . $row); throw new DibiDriverException('Unable to seek to row ' . $row);
} }
} }
@@ -319,15 +262,15 @@ class DibiMSSqlResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
mssql_free_result($this->resource); mssql_free_result($this->resultset);
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
static $types = array( static $types = array(
'CHAR' => dibi::FIELD_TEXT, 'CHAR' => dibi::FIELD_TEXT,
@@ -355,21 +298,53 @@ class DibiMSSqlResult extends DibiResult
// and many others? // and many others?
); );
$count = mssql_num_fields($this->resource); $count = mssql_num_fields($this->resultset);
$this->meta = $this->convert = array(); $meta = array();
for ($index = 0; $index < $count; $index++) { for ($index = 0; $index < $count; $index++) {
$tmp = mssql_fetch_field($this->resource, $index); $tmp = mssql_fetch_field($this->resultset, $index);
$type = strtoupper($tmp->type); $type = strtoupper($tmp->type);
$info['native'] = $tmp->type; $info['native'] = $tmp->type;
$info['type'] = isset($types[$type]) ? $types[$type] : dibi::FIELD_UNKNOWN; $info['type'] = isset($types[$type]) ? $types[$type] : dibi::FIELD_UNKNOWN;
$info['length'] = $tmp->max_length; $info['length'] = $tmp->max_length;
$info['table'] = $tmp->column_source; $info['table'] = $tmp->column_source;
$this->meta[$tmp->name] = $info; $meta[$tmp->name] = $info;
$this->convert[$tmp->name] = $info['type'];
} }
return $meta;
} }
} // class DibiMSSqlResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -38,31 +38,45 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiMySqlDriver extends DibiDriver class DibiMySqlDriver extends NObject implements DibiDriverInterface
{ {
/** /**
* Describes how convert some datatypes to SQL command * Connection resource
* @var array * @var resource
*/ */
public $formats = array( private $connection;
'TRUE' => "1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
/** /**
* Creates object and (optionally) connects to a database * Resultset resource
* @var resource
*/
private $resultset;
/**
* Is buffered (seekable and countable)?
* @var bool
*/
private $buffered;
/**
* Connects to a database
* *
* @param array connect configuration
* @throws DibiException * @throws DibiException
* @return void
*/ */
public function __construct(array $config) public function connect(array &$config)
{ {
self::alias($config, 'username', 'user'); if (!extension_loaded('mysql')) {
self::alias($config, 'password', 'pass'); throw new DibiException("PHP extension 'mysql' is not loaded");
self::alias($config, 'options'); }
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'options');
// default values // default values
if (!isset($config['username'])) $config['username'] = ini_get('mysql.default_user'); if (!isset($config['username'])) $config['username'] = ini_get('mysql.default_user');
@@ -78,24 +92,6 @@ class DibiMySqlDriver extends DibiDriver
} }
} }
parent::__construct($config);
}
/**
* Connects to a database
*
* @throws DibiException
* @return resource
*/
protected function doConnect()
{
if (!extension_loaded('mysql')) {
throw new DibiException("PHP extension 'mysql' is not loaded");
}
$config = $this->getConfig();
if (empty($config['socket'])) { if (empty($config['socket'])) {
$host = $config['host'] . (empty($config['port']) ? '' : ':' . $config['port']); $host = $config['host'] . (empty($config['port']) ? '' : ':' . $config['port']);
@@ -105,26 +101,26 @@ class DibiMySqlDriver extends DibiDriver
DibiDatabaseException::catchError(); DibiDatabaseException::catchError();
if (empty($config['persistent'])) { if (empty($config['persistent'])) {
$connection = @mysql_connect($host, $config['username'], $config['password'], TRUE, $config['options']); $this->connection = @mysql_connect($host, $config['username'], $config['password'], TRUE, $config['options']);
} else { } else {
$connection = @mysql_pconnect($host, $config['username'], $config['password'], $config['options']); $this->connection = @mysql_pconnect($host, $config['username'], $config['password'], $config['options']);
} }
DibiDatabaseException::restore(); DibiDatabaseException::restore();
if (!is_resource($connection)) { if (!is_resource($this->connection)) {
throw new DibiDatabaseException(mysql_error(), mysql_errno()); throw new DibiDatabaseException(mysql_error(), mysql_errno());
} }
if (isset($config['charset'])) { if (isset($config['charset'])) {
@mysql_query("SET NAMES '" . $config['charset'] . "'", $connection); @mysql_query("SET NAMES '" . $config['charset'] . "'", $this->connection);
// don't handle this error... // don't handle this error...
} }
if (isset($config['database']) && !@mysql_select_db($config['database'], $connection)) { if (isset($config['database']) && !@mysql_select_db($config['database'], $this->connection)) {
throw new DibiDatabaseException(mysql_error($connection), mysql_errno($connection)); throw new DibiDatabaseException(mysql_error($this->connection), mysql_errno($this->connection));
} }
return $connection; $this->buffered = empty($config['unbuffered']);
} }
@@ -134,36 +130,33 @@ class DibiMySqlDriver extends DibiDriver
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
mysql_close($this->getConnection()); mysql_close($this->connection);
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql) public function query($sql)
{ {
$connection = $this->getConnection(); if ($this->buffered) {
$this->resultset = @mysql_query($sql, $this->connection);
$buffered = !$this->getConfig('unbuffered');
if ($buffered) {
$res = @mysql_query($sql, $connection);
} else { } else {
$res = @mysql_unbuffered_query($sql, $connection); $this->resultset = @mysql_unbuffered_query($sql, $this->connection);
} }
if ($errno = mysql_errno($connection)) { if ($errno = mysql_errno($this->connection)) {
throw new DibiDatabaseException(mysql_error($connection), $errno, $sql); throw new DibiDatabaseException(mysql_error($this->connection), $errno, $sql);
} }
return is_resource($res) ? new DibiMySqlResult($res, $buffered) : NULL; return is_resource($this->resultset);
} }
@@ -175,8 +168,7 @@ class DibiMySqlDriver extends DibiDriver
*/ */
public function affectedRows() public function affectedRows()
{ {
$rows = mysql_affected_rows($this->getConnection()); return mysql_affected_rows($this->connection);
return $rows < 0 ? FALSE : $rows;
} }
@@ -186,10 +178,9 @@ class DibiMySqlDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId() public function insertId($sequence)
{ {
$id = mysql_insert_id($this->getConnection()); return mysql_insert_id($this->connection);
return $id < 1 ? FALSE : $id;
} }
@@ -200,8 +191,7 @@ class DibiMySqlDriver extends DibiDriver
*/ */
public function begin() public function begin()
{ {
$this->doQuery('BEGIN'); $this->query('BEGIN');
dibi::notify('begin', $this);
} }
@@ -212,8 +202,7 @@ class DibiMySqlDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$this->doQuery('COMMIT'); $this->query('COMMIT');
dibi::notify('commit', $this);
} }
@@ -224,50 +213,26 @@ class DibiMySqlDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$this->doQuery('ROLLBACK'); $this->query('ROLLBACK');
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
$connection = $this->getConnection(); if ($type === dibi::FIELD_TEXT) return "'" . mysql_real_escape_string($value, $this->connection) . "'";
return $appendQuotes if ($type === dibi::IDENTIFIER) return '`' . str_replace('.', '`.`', $value) . '`';
? "'" . mysql_real_escape_string($value, $connection) . "'" if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
: mysql_real_escape_string($value, $connection); if ($type === dibi::FIELD_DATE) return date("'Y-m-d'", $value);
} if ($type === dibi::FIELD_DATETIME) return date("'Y-m-d H:i:s'", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return '`' . str_replace('.', '`.`', $value) . '`';
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -280,7 +245,7 @@ class DibiMySqlDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
if ($limit < 0 && $offset < 1) return; if ($limit < 0 && $offset < 1) return;
@@ -290,35 +255,19 @@ class DibiMySqlDriver extends DibiDriver
} }
} // DibiMySqlDriver
/**
* The dibi result-set class for MySQL database
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiMySqlResult extends DibiResult
{
/** /**
* Returns the number of rows in a result set * Returns the number of rows in a result set
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
return mysql_num_rows($this->resource); if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
return mysql_num_rows($this->resultset);
} }
@@ -329,9 +278,9 @@ class DibiMySqlResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
return mysql_fetch_assoc($this->resource); return mysql_fetch_assoc($this->resultset);
} }
@@ -343,9 +292,12 @@ class DibiMySqlResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
if (!mysql_data_seek($this->resource, $row)) { if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
if (!mysql_data_seek($this->resultset, $row)) {
throw new DibiDriverException('Unable to seek to row ' . $row); throw new DibiDriverException('Unable to seek to row ' . $row);
} }
} }
@@ -357,15 +309,15 @@ class DibiMySqlResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
mysql_free_result($this->resource); mysql_free_result($this->resultset);
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
static $types = array( static $types = array(
'ENUM' => dibi::FIELD_TEXT, // eventually dibi::FIELD_INTEGER 'ENUM' => dibi::FIELD_TEXT, // eventually dibi::FIELD_INTEGER
@@ -402,14 +354,14 @@ class DibiMySqlResult extends DibiResult
'NUMERIC' => dibi::FIELD_FLOAT, 'NUMERIC' => dibi::FIELD_FLOAT,
); );
$count = mysql_num_fields($this->resource); $count = mysql_num_fields($this->resultset);
$this->meta = $this->convert = array(); $meta = array();
for ($index = 0; $index < $count; $index++) { for ($index = 0; $index < $count; $index++) {
$info['native'] = $native = strtoupper(mysql_field_type($this->resource, $index)); $info['native'] = $native = strtoupper(mysql_field_type($this->resultset, $index));
$info['flags'] = explode(' ', mysql_field_flags($this->resource, $index)); $info['flags'] = explode(' ', mysql_field_flags($this->resultset, $index));
$info['length'] = mysql_field_len($this->resource, $index); $info['length'] = mysql_field_len($this->resultset, $index);
$info['table'] = mysql_field_table($this->resource, $index); $info['table'] = mysql_field_table($this->resultset, $index);
if (in_array('auto_increment', $info['flags'])) { // or 'primary_key' ? if (in_array('auto_increment', $info['flags'])) { // or 'primary_key' ?
$info['type'] = dibi::FIELD_COUNTER; $info['type'] = dibi::FIELD_COUNTER;
@@ -420,11 +372,43 @@ class DibiMySqlResult extends DibiResult
// $info['type'] = dibi::FIELD_LONG_TEXT; // $info['type'] = dibi::FIELD_LONG_TEXT;
} }
$name = mysql_field_name($this->resource, $index); $name = mysql_field_name($this->resultset, $index);
$this->meta[$name] = $info; $meta[$name] = $info;
$this->convert[$name] = $info['type'];
} }
return $meta;
} }
} // class DibiMySqlResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -38,32 +38,42 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiMySqliDriver extends DibiDriver class DibiMySqliDriver extends NObject implements DibiDriverInterface
{ {
/** /**
* Describes how convert some datatypes to SQL command * Connection resource
* @var array * @var resource
*/ */
public $formats = array( private $connection;
'TRUE' => "1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
/** /**
* Creates object and (optionally) connects to a database * Resultset resource
* @var resource
*/
private $resultset;
/**
* Is buffered (seekable and countable)?
* @var bool
*/
private $buffered;
/**
* Connects to a database
* *
* @param array connect configuration
* @throws DibiException * @throws DibiException
* @return void
*/ */
public function __construct(array $config) public function connect(array &$config)
{ {
self::alias($config, 'username', 'user'); DibiConnection::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass'); DibiConnection::alias($config, 'password', 'pass');
self::alias($config, 'options'); DibiConnection::alias($config, 'options');
self::alias($config, 'database'); DibiConnection::alias($config, 'database');
// default values // default values
if (!isset($config['username'])) $config['username'] = ini_get('mysqli.default_user'); if (!isset($config['username'])) $config['username'] = ini_get('mysqli.default_user');
@@ -75,71 +85,54 @@ class DibiMySqliDriver extends DibiDriver
if (!isset($config['host'])) $config['host'] = 'localhost'; if (!isset($config['host'])) $config['host'] = 'localhost';
} }
parent::__construct($config);
}
/**
* Connects to a database
*
* @throws DibiException
* @return resource
*/
protected function doConnect()
{
if (!extension_loaded('mysqli')) { if (!extension_loaded('mysqli')) {
throw new DibiException("PHP extension 'mysqli' is not loaded"); throw new DibiException("PHP extension 'mysqli' is not loaded");
} }
$config = $this->getConfig();
$connection = mysqli_init(); $this->connection = mysqli_init();
@mysqli_real_connect($connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']); @mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']);
if ($errno = mysqli_connect_errno()) { if ($errno = mysqli_connect_errno()) {
throw new DibiDatabaseException(mysqli_connect_error(), $errno); throw new DibiDatabaseException(mysqli_connect_error(), $errno);
} }
if (isset($config['charset'])) { if (isset($config['charset'])) {
mysqli_query($connection, "SET NAMES '" . $config['charset'] . "'"); mysqli_query($this->connection, "SET NAMES '" . $config['charset'] . "'");
} }
return $connection; $this->buffered = empty($config['unbuffered']);
} }
/** /**
* Disconnects from a database * Disconnects from a database
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
mysqli_close($this->getConnection()); mysqli_close($this->connection);
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql) public function query($sql)
{ {
$connection = $this->getConnection(); $this->resultset = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
$buffered = !$this->getConfig('unbuffered');
$res = @mysqli_query($connection, $sql, $buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
if ($errno = mysqli_errno($connection)) { if ($errno = mysqli_errno($this->connection)) {
throw new DibiDatabaseException(mysqli_error($connection), $errno, $sql); throw new DibiDatabaseException(mysqli_error($this->connection), $errno, $sql);
} }
return is_object($res) ? new DibiMySqliResult($res, $buffered) : NULL; return is_object($this->resultset);
} }
@@ -151,8 +144,7 @@ class DibiMySqliDriver extends DibiDriver
*/ */
public function affectedRows() public function affectedRows()
{ {
$rows = mysqli_affected_rows($this->getConnection()); return mysqli_affected_rows($this->connection);
return $rows < 0 ? FALSE : $rows;
} }
@@ -162,10 +154,9 @@ class DibiMySqliDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId() public function insertId($sequence)
{ {
$id = mysqli_insert_id($this->getConnection()); return mysqli_insert_id($this->connection);
return $id < 1 ? FALSE : $id;
} }
@@ -176,11 +167,9 @@ class DibiMySqliDriver extends DibiDriver
*/ */
public function begin() public function begin()
{ {
$connection = $this->getConnection(); if (!mysqli_autocommit($this->connection, FALSE)) {
if (!mysqli_autocommit($connection, FALSE)) { throw new DibiDatabaseException(mysqli_error($this->connection), mysqli_errno($this->connection));
throw new DibiDatabaseException(mysqli_error($connection), mysqli_errno($connection));
} }
dibi::notify('begin', $this);
} }
@@ -191,12 +180,10 @@ class DibiMySqliDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$connection = $this->getConnection(); if (!mysqli_commit($this->connection)) {
if (!mysqli_commit($connection)) { throw new DibiDatabaseException(mysqli_error($this->connection), mysqli_errno($this->connection));
throw new DibiDatabaseException(mysqli_error($connection), mysqli_errno($connection));
} }
mysqli_autocommit($connection, TRUE); mysqli_autocommit($this->connection, TRUE);
dibi::notify('commit', $this);
} }
@@ -207,54 +194,29 @@ class DibiMySqliDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$connection = $this->getConnection(); if (!mysqli_rollback($this->connection)) {
if (!mysqli_rollback($connection)) { throw new DibiDatabaseException(mysqli_error($this->connection), mysqli_errno($this->connection));
throw new DibiDatabaseException(mysqli_error($connection), mysqli_errno($connection));
} }
mysqli_autocommit($connection, TRUE); mysqli_autocommit($this->connection, TRUE);
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
$connection = $this->getConnection(); if ($type === dibi::FIELD_TEXT) return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
return $appendQuotes if ($type === dibi::IDENTIFIER) return '`' . str_replace('.', '`.`', $value) . '`';
? "'" . mysqli_real_escape_string($connection, $value) . "'" if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
: mysqli_real_escape_string($connection, $value); if ($type === dibi::FIELD_DATE) return date("'Y-m-d'", $value);
} if ($type === dibi::FIELD_DATETIME) return date("'Y-m-d H:i:s'", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return '`' . str_replace('.', '`.`', $value) . '`';
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -267,7 +229,7 @@ class DibiMySqliDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
if ($limit < 0 && $offset < 1) return; if ($limit < 0 && $offset < 1) return;
@@ -277,35 +239,20 @@ class DibiMySqliDriver extends DibiDriver
} }
} // class DibiMySqliDriver
/**
* The dibi result-set class for MySQL database via improved extension
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiMySqliResult extends DibiResult
{
/** /**
* Returns the number of rows in a result set * Returns the number of rows in a result set
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
return mysqli_num_rows($this->resource); if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
return mysqli_num_rows($this->resultset);
} }
@@ -316,9 +263,9 @@ class DibiMySqliResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
return mysqli_fetch_assoc($this->resource); return mysqli_fetch_assoc($this->resultset);
} }
@@ -330,9 +277,12 @@ class DibiMySqliResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
if (!mysqli_data_seek($this->resource, $row)) { if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
if (!mysqli_data_seek($this->resultset, $row)) {
throw new DibiDriverException('Unable to seek to row ' . $row); throw new DibiDriverException('Unable to seek to row ' . $row);
} }
} }
@@ -344,15 +294,15 @@ class DibiMySqliResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
mysqli_free_result($this->resource); mysqli_free_result($this->resultset);
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
static $types = array( static $types = array(
MYSQLI_TYPE_FLOAT => dibi::FIELD_FLOAT, MYSQLI_TYPE_FLOAT => dibi::FIELD_FLOAT,
@@ -382,10 +332,10 @@ class DibiMySqliResult extends DibiResult
MYSQLI_TYPE_BLOB => dibi::FIELD_BINARY, MYSQLI_TYPE_BLOB => dibi::FIELD_BINARY,
); );
$count = mysqli_num_fields($this->resource); $count = mysqli_num_fields($this->resultset);
$this->meta = $this->convert = array(); $meta = array();
for ($index = 0; $index < $count; $index++) { for ($index = 0; $index < $count; $index++) {
$info = (array) mysqli_fetch_field_direct($this->resource, $index); $info = (array) mysqli_fetch_field_direct($this->resultset, $index);
$native = $info['native'] = $info['type']; $native = $info['native'] = $info['type'];
if ($info['flags'] & MYSQLI_AUTO_INCREMENT_FLAG) { // or 'primary_key' ? if ($info['flags'] & MYSQLI_AUTO_INCREMENT_FLAG) { // or 'primary_key' ?
@@ -396,10 +346,42 @@ class DibiMySqliResult extends DibiResult
// $info['type'] = dibi::FIELD_LONG_TEXT; // $info['type'] = dibi::FIELD_LONG_TEXT;
} }
$this->meta[$info['name']] = $info; $meta[$info['name']] = $info;
$this->convert[$info['name']] = $info['type'];
} }
return $meta;
} }
} // class DibiMySqliResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -32,45 +32,28 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiOdbcDriver extends DibiDriver class DibiOdbcDriver extends NObject implements DibiDriverInterface
{ {
/**
* Describes how convert some datatypes to SQL command
* @var array
*/
public $formats = array(
'TRUE' => "-1",
'FALSE' => "0",
'date' => "#m/d/Y#",
'datetime' => "#m/d/Y H:i:s#",
);
/** /**
* Affected rows * Connection resource
* @var mixed * @var resource
*/ */
private $affectedRows = FALSE; private $connection;
/** /**
* Creates object and (optionally) connects to a database * Resultset resource
* * @var resource
* @param array connect configuration
* @throws DibiException
*/ */
public function __construct(array $config) private $resultset;
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
// default values
if (!isset($config['username'])) $config['username'] = ini_get('odbc.default_user');
if (!isset($config['password'])) $config['password'] = ini_get('odbc.default_pw');
if (!isset($config['dsn'])) $config['dsn'] = ini_get('odbc.default_db');
parent::__construct($config); /**
} * Cursor
* @var int
*/
private $row = 0;
@@ -78,27 +61,32 @@ class DibiOdbcDriver extends DibiDriver
* Connects to a database * Connects to a database
* *
* @throws DibiException * @throws DibiException
* @return resource * @return void
*/ */
protected function doConnect() public function connect(array &$config)
{ {
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
// default values
if (!isset($config['username'])) $config['username'] = ini_get('odbc.default_user');
if (!isset($config['password'])) $config['password'] = ini_get('odbc.default_pw');
if (!isset($config['dsn'])) $config['dsn'] = ini_get('odbc.default_db');
if (!extension_loaded('odbc')) { if (!extension_loaded('odbc')) {
throw new DibiException("PHP extension 'odbc' is not loaded"); throw new DibiException("PHP extension 'odbc' is not loaded");
} }
$config = $this->getConfig();
if (empty($config['persistent'])) { if (empty($config['persistent'])) {
$connection = @odbc_connect($config['dsn'], $config['username'], $config['password']); $this->connection = @odbc_connect($config['dsn'], $config['username'], $config['password']);
} else { } else {
$connection = @odbc_pconnect($config['dsn'], $config['username'], $config['password']); $this->connection = @odbc_pconnect($config['dsn'], $config['username'], $config['password']);
} }
if (!is_resource($connection)) { if (!is_resource($this->connection)) {
throw new DibiDatabaseException(odbc_errormsg(), odbc_error()); throw new DibiDatabaseException(odbc_errormsg(), odbc_error());
} }
return $connection;
} }
@@ -108,35 +96,30 @@ class DibiOdbcDriver extends DibiDriver
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
odbc_close($this->getConnection()); odbc_close($this->connection);
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql) public function query($sql)
{ {
$this->affectedRows = FALSE; $this->affectedRows = FALSE;
$connection = $this->getConnection(); $this->resultset = @odbc_exec($this->connection, $sql);
$res = @odbc_exec($connection, $sql);
if ($res === FALSE) { if ($this->resultset === FALSE) {
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection), $sql); throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection), $sql);
} }
if (is_resource($res)) { return is_resource($this->resultset);
$this->affectedRows = odbc_num_rows($res);
if ($this->affectedRows < 0) $this->affectedRows = FALSE;
return new DibiOdbcResult($res, TRUE);
}
} }
@@ -148,7 +131,7 @@ class DibiOdbcDriver extends DibiDriver
*/ */
public function affectedRows() public function affectedRows()
{ {
return $this->affectedRows; return odbc_num_rows($this->resultset);
} }
@@ -158,7 +141,7 @@ class DibiOdbcDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId() public function insertId($sequence)
{ {
throw new BadMethodCallException(__METHOD__ . ' is not implemented'); throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -171,11 +154,9 @@ class DibiOdbcDriver extends DibiDriver
*/ */
public function begin() public function begin()
{ {
$connection = $this->getConnection(); if (!odbc_autocommit($this->connection, FALSE)) {
if (!odbc_autocommit($connection, FALSE)) { throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection));
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection));
} }
dibi::notify('begin', $this);
} }
@@ -186,12 +167,10 @@ class DibiOdbcDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$connection = $this->getConnection(); if (!odbc_commit($this->connection)) {
if (!odbc_commit($connection)) { throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection));
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection));
} }
odbc_autocommit($connection, TRUE); odbc_autocommit($this->connection, TRUE);
dibi::notify('commit', $this);
} }
@@ -202,54 +181,29 @@ class DibiOdbcDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$connection = $this->getConnection(); if (!odbc_rollback($this->connection)) {
if (!odbc_rollback($connection)) { throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection));
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection));
} }
odbc_autocommit($connection, TRUE); odbc_autocommit($this->connection, TRUE);
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
$value = str_replace("'", "''", $value); if ($type === dibi::FIELD_TEXT) return "'" . str_replace("'", "''", $value) . "'";
return $appendQuotes if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $value) . ']';
? "'" . $value . "'" if ($type === dibi::FIELD_BOOL) return $value ? -1 : 0;
: $value; if ($type === dibi::FIELD_DATE) return date("#m/d/Y#", $value);
} if ($type === dibi::FIELD_DATETIME) return date("#m/d/Y H:i:s#", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return '[' . str_replace('.', '].[', $value) . ']';
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -262,7 +216,7 @@ class DibiOdbcDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
// offset suppot is missing... // offset suppot is missing...
if ($limit >= 0) { if ($limit >= 0) {
@@ -273,26 +227,6 @@ class DibiOdbcDriver extends DibiDriver
} }
} // class DibiOdbcDriver
/**
* The dibi result-set class for ODBC database
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiOdbcResult extends DibiResult
{
private $row = 0;
/** /**
@@ -300,10 +234,10 @@ class DibiOdbcResult extends DibiResult
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
// will return -1 with many drivers :-( // will return -1 with many drivers :-(
return odbc_num_rows($this->resource); return odbc_num_rows($this->resultset);
} }
@@ -314,9 +248,9 @@ class DibiOdbcResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
return odbc_fetch_array($this->resource, $this->row++); return odbc_fetch_array($this->resultset, $this->row++);
} }
@@ -328,7 +262,7 @@ class DibiOdbcResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
$this->row = $row; $this->row = $row;
} }
@@ -340,19 +274,19 @@ class DibiOdbcResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
odbc_free_result($this->resource); odbc_free_result($this->resultset);
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
// cache // cache
if ($this->meta !== NULL) { if ($meta !== NULL) {
return $this->meta; return $meta;
} }
static $types = array( static $types = array(
@@ -381,21 +315,53 @@ class DibiOdbcResult extends DibiResult
// and many others? // and many others?
); );
$count = odbc_num_fields($this->resource); $count = odbc_num_fields($this->resultset);
$this->meta = $this->convert = array(); $meta = array();
for ($index = 1; $index <= $count; $index++) { for ($index = 1; $index <= $count; $index++) {
$native = strtoupper(odbc_field_type($this->resource, $index)); $native = strtoupper(odbc_field_type($this->resultset, $index));
$name = odbc_field_name($this->resource, $index); $name = odbc_field_name($this->resultset, $index);
$this->meta[$name] = array( $meta[$name] = array(
'type' => isset($types[$native]) ? $types[$native] : dibi::FIELD_UNKNOWN, 'type' => isset($types[$native]) ? $types[$native] : dibi::FIELD_UNKNOWN,
'native' => $native, 'native' => $native,
'length' => odbc_field_len($this->resource, $index), 'length' => odbc_field_len($this->resultset, $index),
'scale' => odbc_field_scale($this->resource, $index), 'scale' => odbc_field_scale($this->resultset, $index),
'precision' => odbc_field_precision($this->resource, $index), 'precision' => odbc_field_precision($this->resultset, $index),
); );
$this->convert[$name] = $this->meta[$name]['type'];
} }
return $meta;
} }
} // class DibiOdbcResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -32,61 +32,53 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiOracleDriver extends DibiDriver class DibiOracleDriver extends NObject implements DibiDriverInterface
{ {
/**
* Describes how convert some datatypes to SQL command
* @var array
*/
public $formats = array(
'TRUE' => "1",
'FALSE' => "0",
'date' => "U",
'datetime' => "U",
);
/**
* Connection resource
* @var resource
*/
private $connection;
/**
* Resultset resource
* @var resource
*/
private $resultset;
/**
* @var bool
*/
private $autocommit = TRUE; private $autocommit = TRUE;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @throws DibiException
*/
public function __construct(array $config)
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'database', 'db');
self::alias($config, 'charset');
parent::__construct($config);
}
/** /**
* Connects to a database * Connects to a database
* *
* @throws DibiException * @throws DibiException
* @return resource * @return void
*/ */
protected function doConnect() public function connect(array &$config)
{ {
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'database', 'db');
DibiConnection::alias($config, 'charset');
if (!extension_loaded('oci8')) { if (!extension_loaded('oci8')) {
throw new DibiException("PHP extension 'oci8' is not loaded"); throw new DibiException("PHP extension 'oci8' is not loaded");
} }
$config = $this->getConfig(); $this->connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']);
$connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']);
if (!$connection) { if (!$this->connection) {
$err = oci_error(); $err = oci_error();
throw new DibiDatabaseException($err['message'], $err['code']); throw new DibiDatabaseException($err['message'], $err['code']);
} }
return $connection;
} }
@@ -96,37 +88,36 @@ class DibiOracleDriver extends DibiDriver
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
oci_close($this->getConnection()); oci_close($this->connection);
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql) public function query($sql)
{ {
$connection = $this->getConnection();
$statement = oci_parse($connection, $sql); $this->resultset = oci_parse($this->connection, $sql);
if ($statement) { if ($this->resultset) {
$res = oci_execute($statement, $this->autocommit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT); oci_execute($this->resultset, $this->autocommit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT);
$err = oci_error($statement); $err = oci_error($this->resultset);
if ($err) { if ($err) {
throw new DibiDatabaseException($err['message'], $err['code'], $sql); throw new DibiDatabaseException($err['message'], $err['code'], $sql);
} }
} else { } else {
$err = oci_error($connection); $err = oci_error($this->connection);
throw new DibiDatabaseException($err['message'], $err['code'], $sql); throw new DibiDatabaseException($err['message'], $err['code'], $sql);
} }
return is_resource($res) ? new DibiOracleResult($statement, TRUE) : TRUE; return is_resource($this->resultset);
} }
@@ -148,7 +139,7 @@ class DibiOracleDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId() public function insertId($sequence)
{ {
throw new BadMethodCallException(__METHOD__ . ' is not implemented'); throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -172,13 +163,11 @@ class DibiOracleDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$connection = $this->getConnection(); if (!oci_commit($this->connection)) {
if (!oci_commit($connection)) { $err = oci_error($this->connection);
$err = oci_error($connection);
throw new DibiDatabaseException($err['message'], $err['code']); throw new DibiDatabaseException($err['message'], $err['code']);
} }
$this->autocommit = TRUE; $this->autocommit = TRUE;
dibi::notify('commit', $this);
} }
@@ -189,54 +178,30 @@ class DibiOracleDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$connection = $this->getConnection(); if (!oci_rollback($this->connection)) {
if (!oci_rollback($connection)) { $err = oci_error($this->connection);
$err = oci_error($connection);
throw new DibiDatabaseException($err['message'], $err['code']); throw new DibiDatabaseException($err['message'], $err['code']);
} }
$this->autocommit = TRUE; $this->autocommit = TRUE;
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
return $appendQuotes if ($type === dibi::FIELD_TEXT) return "'" . str_replace("'", "''", $value) . "'"; // TODO: not tested
? "'" . sqlite_escape_string($value) . "'" if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $value) . ']'; // TODO: not tested
: sqlite_escape_string($value); if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
} if ($type === dibi::FIELD_DATE) return date("U", $value);
if ($type === dibi::FIELD_DATETIME) return date("U", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return '[' . str_replace('.', '].[', $value) . ']';
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -249,41 +214,23 @@ class DibiOracleDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
if ($limit < 0 && $offset < 1) return; if ($limit < 0 && $offset < 1) return;
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : ''); $sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
} }
} // class DibiOracleDriver
/**
* The dibi result-set class for Oracle database
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiOracleResult extends DibiResult
{
/** /**
* Returns the number of rows in a result set * Returns the number of rows in a result set
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
return oci_num_rows($this->resource); return oci_num_rows($this->resultset);
} }
@@ -294,10 +241,10 @@ class DibiOracleResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
$this->fetched = TRUE; $this->fetched = TRUE;
return oci_fetch_assoc($this->resource); return oci_fetch_assoc($this->resultset);
} }
@@ -309,7 +256,7 @@ class DibiOracleResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
if ($row === 0 && !$this->fetched) return TRUE; if ($row === 0 && !$this->fetched) return TRUE;
throw new BadMethodCallException(__METHOD__ . ' is not implemented'); throw new BadMethodCallException(__METHOD__ . ' is not implemented');
@@ -322,24 +269,56 @@ class DibiOracleResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
oci_free_statement($this->resource); oci_free_statement($this->resultset);
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
$count = oci_num_fields($this->resource); $count = oci_num_fields($this->resultset);
$this->meta = $this->convert = array(); $meta = array();
for ($index = 0; $index < $count; $index++) { for ($index = 0; $index < $count; $index++) {
$name = oci_field_name($this->resource, $index + 1); $name = oci_field_name($this->resultset, $index + 1);
$this->meta[$name] = array('type' => dibi::FIELD_UNKNOWN); $meta[$name] = array('type' => dibi::FIELD_UNKNOWN);
$this->convert[$name] = dibi::FIELD_UNKNOWN;
} }
return $meta;
} }
} // class DibiOracleResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -32,79 +32,75 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiPdoDriver extends DibiDriver class DibiPdoDriver extends NObject implements DibiDriverInterface
{ {
/** /**
* Describes how convert some datatypes to SQL command * Connection resource
* @var array * @var resource
*/ */
public $formats = array( private $connection;
'TRUE' => "1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
/** /**
* Creates object and (optionally) connects to a database * Resultset resource
* * @var resource
* @param array connect configuration
* @throws DibiException
*/ */
public function __construct(array $config) private $resultset;
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'dsn');
self::alias($config, 'options');
parent::__construct($config);
}
/**
* Cursor
* @var int
*/
private $row = 0;
/** /**
* Connects to a database * Connects to a database
* *
* @throws DibiException * @throws DibiException
* @return resource * @return void
*/ */
protected function doConnect() public function connect(array &$config)
{ {
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'dsn');
DibiConnection::alias($config, 'options');
if (!extension_loaded('pdo')) { if (!extension_loaded('pdo')) {
throw new DibiException("PHP extension 'pdo' is not loaded"); throw new DibiException("PHP extension 'pdo' is not loaded");
} }
$config = $this->getConfig(); $this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']);
$connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connection;
} }
/** /**
* Disconnects from a database * Disconnects from a database
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
$this->connection = NULL;
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql) public function query($sql)
{ {
$res = $this->getConnection()->query($sql); $this->resultset = $this->connection->query($sql);
return $res instanceof PDOStatement ? new DibiPdoResult($res, TRUE) : NULL; return $this->resultset instanceof PDOStatement;
} }
@@ -126,9 +122,9 @@ class DibiPdoDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId() public function insertId($sequence)
{ {
return $this->getConnection()->lastInsertId(); return $this->connection->lastInsertId();
} }
@@ -139,8 +135,7 @@ class DibiPdoDriver extends DibiDriver
*/ */
public function begin() public function begin()
{ {
$this->getConnection()->beginTransaction(); $this->connection->beginTransaction();
dibi::notify('begin', $this);
} }
@@ -151,8 +146,7 @@ class DibiPdoDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$this->getConnection()->commit(); $this->connection->commit();
dibi::notify('commit', $this);
} }
@@ -163,51 +157,26 @@ class DibiPdoDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$this->getConnection()->rollBack(); $this->connection->rollBack();
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
if (!$appendQuotes) { if ($type === dibi::FIELD_TEXT) return $this->connection->quote($value);
throw new BadMethodCallException('Escaping without qoutes is not supported by PDO'); if ($type === dibi::IDENTIFIER) return $value; // quoting is not supported by PDO
} if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
return $this->getConnection()->quote($value); if ($type === dibi::FIELD_DATE) return date("'Y-m-d'", $value);
} if ($type === dibi::FIELD_DATETIME) return date("'Y-m-d H:i:s'", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
// quoting is not supported by PDO
return $value;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -220,32 +189,11 @@ class DibiPdoDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
throw new BadMethodCallException(__METHOD__ . ' is not implemented'); throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
} // class DibiPdoDriver
/**
* The dibi result-set class for PDOStatement
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiPdoResult extends DibiResult
{
private $row = 0;
/** /**
@@ -253,9 +201,9 @@ class DibiPdoResult extends DibiResult
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
return $this->resource->rowCount(); return $this->resultset->rowCount();
} }
@@ -266,9 +214,9 @@ class DibiPdoResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
return $this->resource->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT, $this->row++); return $this->resultset->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT, $this->row++);
} }
@@ -280,9 +228,8 @@ class DibiPdoResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
$this->row = $row;
} }
@@ -292,26 +239,59 @@ class DibiPdoResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
$this->resultset = NULL;
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
$count = $this->resource->columnCount(); $count = $this->resultset->columnCount();
$this->meta = $this->convert = array(); $meta = array();
for ($index = 0; $index < $count; $index++) { for ($index = 0; $index < $count; $index++) {
$meta = $this->resource->getColumnMeta($index); $meta = $this->resultset->getColumnMeta($index);
// TODO: // TODO:
$meta['type'] = dibi::FIELD_UNKNOWN; $meta['type'] = dibi::FIELD_UNKNOWN;
$name = $meta['name']; $name = $meta['name'];
$this->meta[$name] = $meta; $meta[$name] = $meta;
$this->convert[$name] = $meta['type'];
} }
return $meta;
} }
} // class DibiPdoResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -31,39 +31,21 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiPostgreDriver extends DibiDriver class DibiPostgreDriver extends NObject implements DibiDriverInterface
{ {
/**
* Describes how convert some datatypes to SQL command
* @var array
*/
public $formats = array(
'TRUE' => "TRUE",
'FALSE' => "FALSE",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
/** /**
* Affected rows * Connection resource
* @var mixed * @var resource
*/ */
private $affectedRows = FALSE; private $connection;
/** /**
* Creates object and (optionally) connects to a database * Resultset resource
* * @var resource
* @param array connect configuration
* @throws DibiException
*/ */
public function __construct(array $config) private $resultset;
{
self::alias($config, 'database', 'string');
self::alias($config, 'type');
parent::__construct($config);
}
@@ -71,34 +53,34 @@ class DibiPostgreDriver extends DibiDriver
* Connects to a database * Connects to a database
* *
* @throws DibiException * @throws DibiException
* @return resource * @return void
*/ */
protected function doConnect() public function connect(array &$config)
{ {
DibiConnection::alias($config, 'database', 'string');
DibiConnection::alias($config, 'type');
if (!extension_loaded('pgsql')) { if (!extension_loaded('pgsql')) {
throw new DibiException("PHP extension 'pgsql' is not loaded"); throw new DibiException("PHP extension 'pgsql' is not loaded");
} }
$config = $this->getConfig();
DibiDatabaseException::catchError(); DibiDatabaseException::catchError();
if (isset($config['persistent'])) { if (isset($config['persistent'])) {
$connection = @pg_connect($config['database'], PGSQL_CONNECT_FORCE_NEW); $this->connection = @pg_connect($config['database'], PGSQL_CONNECT_FORCE_NEW);
} else { } else {
$connection = @pg_pconnect($config['database'], PGSQL_CONNECT_FORCE_NEW); $this->connection = @pg_pconnect($config['database'], PGSQL_CONNECT_FORCE_NEW);
} }
DibiDatabaseException::restore(); DibiDatabaseException::restore();
if (!is_resource($connection)) { if (!is_resource($this->connection)) {
throw new DibiDatabaseException('unknown error'); throw new DibiDatabaseException('unknown error');
} }
if (isset($config['charset'])) { if (isset($config['charset'])) {
@pg_set_client_encoding($connection, $config['charset']); @pg_set_client_encoding($this->connection, $config['charset']);
// don't handle this error... // don't handle this error...
} }
return $connection;
} }
@@ -108,37 +90,30 @@ class DibiPostgreDriver extends DibiDriver
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
pg_close($this->getConnection()); pg_close($this->connection);
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @param bool update affected rows? * @param bool update affected rows?
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql, $silent = FALSE) public function query($sql)
{ {
$connection = $this->getConnection(); $this->resultset = @pg_query($this->connection, $sql);
$res = @pg_query($connection, $sql);
if ($res === FALSE) { if ($this->resultset === FALSE) {
throw new DibiDatabaseException(pg_last_error($connection), 0, $sql); throw new DibiDatabaseException(pg_last_error($this->connection), 0, $sql);
} }
if (is_resource($res)) { return is_resource($this->resultset);
if (!$silent) {
$this->affectedRows = pg_affected_rows($res);
if ($this->affectedRows < 0) $this->affectedRows = FALSE;
}
return new DibiPostgreResult($res, TRUE);
}
} }
@@ -150,7 +125,7 @@ class DibiPostgreDriver extends DibiDriver
*/ */
public function affectedRows() public function affectedRows()
{ {
return $this->affectedRows; return pg_affected_rows($this->resultset);
} }
@@ -160,13 +135,13 @@ class DibiPostgreDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId($sequence = NULL) public function insertId($sequence)
{ {
if ($sequence === NULL) { if ($sequence === NULL) {
// PostgreSQL 8.1 is needed // PostgreSQL 8.1 is needed
$res = $this->doQuery("SELECT LASTVAL() AS seq", TRUE); $res = $this->query("SELECT LASTVAL() AS seq");
} else { } else {
$res = $this->doQuery("SELECT CURRVAL('$sequence') AS seq", TRUE); $res = $this->query("SELECT CURRVAL('$sequence') AS seq");
} }
if (is_resource($res)) { if (is_resource($res)) {
@@ -186,8 +161,7 @@ class DibiPostgreDriver extends DibiDriver
*/ */
public function begin() public function begin()
{ {
$this->doQuery('BEGIN', TRUE); $this->query('BEGIN');
dibi::notify('begin', $this);
} }
@@ -198,8 +172,7 @@ class DibiPostgreDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$this->doQuery('COMMIT', TRUE); $this->query('COMMIT');
dibi::notify('commit', $this);
} }
@@ -210,50 +183,26 @@ class DibiPostgreDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$this->doQuery('ROLLBACK', TRUE); $this->query('ROLLBACK');
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
return $appendQuotes if ($type === dibi::FIELD_TEXT) return "'" . pg_escape_string($value) . "'";
? "'" . pg_escape_string($value) . "'" if ($type === dibi::IDENTIFIER) return '"' . str_replace('.', '"."', str_replace('"', '""', $value)) . '"';
: pg_escape_string($value); if ($type === dibi::FIELD_BOOL) return $value ? 'TRUE' : 'FALSE';
} if ($type === dibi::FIELD_DATE) return date("'Y-m-d'", $value);
if ($type === dibi::FIELD_DATETIME) return date("'Y-m-d H:i:s'", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
$value = str_replace('"', '""', $value);
return '"' . str_replace('.', '"."', $value) . '"';
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -266,7 +215,7 @@ class DibiPostgreDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
if ($limit >= 0) if ($limit >= 0)
$sql .= ' LIMIT ' . (int) $limit; $sql .= ' LIMIT ' . (int) $limit;
@@ -276,35 +225,17 @@ class DibiPostgreDriver extends DibiDriver
} }
} // class DibiPostgreDriver
/**
* The dibi result-set class for PostgreSQL database
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiPostgreResult extends DibiResult
{
/** /**
* Returns the number of rows in a result set * Returns the number of rows in a result set
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
return pg_num_rows($this->resource); return pg_num_rows($this->resultset);
} }
@@ -315,9 +246,9 @@ class DibiPostgreResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
return pg_fetch_array($this->resource, NULL, PGSQL_ASSOC); return pg_fetch_array($this->resultset, NULL, PGSQL_ASSOC);
} }
@@ -329,9 +260,9 @@ class DibiPostgreResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
if (!pg_result_seek($this->resource, $row)) { if (!pg_result_seek($this->resultset, $row)) {
throw new DibiDriverException('Unable to seek to row ' . $row); throw new DibiDriverException('Unable to seek to row ' . $row);
} }
} }
@@ -343,15 +274,15 @@ class DibiPostgreResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
pg_free_result($this->resource); pg_free_result($this->resultset);
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
static $types = array( static $types = array(
'bool' => dibi::FIELD_BOOL, 'bool' => dibi::FIELD_BOOL,
@@ -370,20 +301,52 @@ class DibiPostgreResult extends DibiResult
'money' => dibi::FIELD_FLOAT, 'money' => dibi::FIELD_FLOAT,
); );
$count = pg_num_fields($this->resource); $count = pg_num_fields($this->resultset);
$this->meta = $this->convert = array(); $meta = array();
for ($index = 0; $index < $count; $index++) { for ($index = 0; $index < $count; $index++) {
$info['native'] = $native = pg_field_type($this->resource, $index); $info['native'] = $native = pg_field_type($this->resultset, $index);
$info['length'] = pg_field_size($this->resource, $index); $info['length'] = pg_field_size($this->resultset, $index);
$info['table'] = pg_field_table($this->resource, $index); $info['table'] = pg_field_table($this->resultset, $index);
$info['type'] = isset($types[$native]) ? $types[$native] : dibi::FIELD_UNKNOWN; $info['type'] = isset($types[$native]) ? $types[$native] : dibi::FIELD_UNKNOWN;
$name = pg_field_name($this->resource, $index); $name = pg_field_name($this->resultset, $index);
$this->meta[$name] = $info; $meta[$name] = $info;
$this->convert[$name] = $info['type'];
} }
return $meta;
} }
} // class DibiPostgreResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -31,101 +31,93 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class DibiSqliteDriver extends DibiDriver class DibiSqliteDriver extends NObject implements DibiDriverInterface
{ {
/** /**
* Describes how convert some datatypes to SQL command * Connection resource
* @var array * @var resource
*/ */
public $formats = array( private $connection;
'TRUE' => "1",
'FALSE' => "0",
'date' => "U",
'datetime' => "U",
);
/** /**
* Creates object and (optionally) connects to a database * Resultset resource
* * @var resource
* @param array connect configuration
* @throws DibiException
*/ */
public function __construct($config) private $resultset;
{
self::alias($config, 'database', 'file');
parent::__construct($config);
}
/**
* Is buffered (seekable and countable)?
* @var bool
*/
private $buffered;
/** /**
* Connects to a database * Connects to a database
* *
* @throws DibiException * @throws DibiException
* @return resource * @return void
*/ */
protected function doConnect() public function connect(array &$config)
{ {
DibiConnection::alias($config, 'database', 'file');
if (!extension_loaded('sqlite')) { if (!extension_loaded('sqlite')) {
throw new DibiException("PHP extension 'sqlite' is not loaded"); throw new DibiException("PHP extension 'sqlite' is not loaded");
} }
$config = $this->getConfig();
$errorMsg = ''; $errorMsg = '';
if (empty($config['persistent'])) { if (empty($config['persistent'])) {
$connection = @sqlite_open($config['database'], 0666, $errorMsg); $this->connection = @sqlite_open($config['database'], 0666, $errorMsg);
} else { } else {
$connection = @sqlite_popen($config['database'], 0666, $errorMsg); $this->connection = @sqlite_popen($config['database'], 0666, $errorMsg);
} }
if (!$connection) { if (!$this->connection) {
throw new DibiDatabaseException($errorMsg); throw new DibiDatabaseException($errorMsg);
} }
return $connection; $this->buffered = empty($config['unbuffered']);
} }
/** /**
* Disconnects from a database * Disconnects from a database
* *
* @return void * @return void
*/ */
protected function doDisconnect() public function disconnect()
{ {
sqlite_close($this->getConnection()); sqlite_close($this->connection);
} }
/** /**
* Internal: Executes the SQL query * Executes the SQL query
* *
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult Result set object * @return bool have resultset?
* @throws DibiDatabaseException * @throws DibiDatabaseException
*/ */
protected function doQuery($sql) public function query($sql)
{ {
$connection = $this->getConnection();
$errorMsg = NULL; $errorMsg = NULL;
$buffered = !$this->getConfig('unbuffered'); if ($this->buffered) {
if ($buffered) { $this->resultset = @sqlite_query($this->connection, $sql, SQLITE_ASSOC, $errorMsg);
$res = @sqlite_query($connection, $sql, SQLITE_ASSOC, $errorMsg);
} else { } else {
$res = @sqlite_unbuffered_query($connection, $sql, SQLITE_ASSOC, $errorMsg); $this->resultset = @sqlite_unbuffered_query($this->connection, $sql, SQLITE_ASSOC, $errorMsg);
} }
if ($errorMsg !== NULL) { if ($errorMsg !== NULL) {
throw new DibiDatabaseException($errorMsg, sqlite_last_error($connection), $sql); throw new DibiDatabaseException($errorMsg, sqlite_last_error($this->connection), $sql);
} }
return is_resource($res) ? new DibiSqliteResult($res, $buffered) : NULL; return is_resource($this->resultset);
} }
@@ -137,8 +129,7 @@ class DibiSqliteDriver extends DibiDriver
*/ */
public function affectedRows() public function affectedRows()
{ {
$rows = sqlite_changes($this->getConnection()); return sqlite_changes($this->connection);
return $rows < 0 ? FALSE : $rows;
} }
@@ -148,10 +139,9 @@ class DibiSqliteDriver extends DibiDriver
* *
* @return int|FALSE int on success or FALSE on failure * @return int|FALSE int on success or FALSE on failure
*/ */
public function insertId() public function insertId($sequence)
{ {
$id = sqlite_last_insert_rowid($this->getConnection()); return sqlite_last_insert_rowid($this->connection);
return $id < 1 ? FALSE : $id;
} }
@@ -162,8 +152,7 @@ class DibiSqliteDriver extends DibiDriver
*/ */
public function begin() public function begin()
{ {
$this->doQuery('BEGIN'); $this->query('BEGIN');
dibi::notify('begin', $this);
} }
@@ -174,8 +163,7 @@ class DibiSqliteDriver extends DibiDriver
*/ */
public function commit() public function commit()
{ {
$this->doQuery('COMMIT'); $this->query('COMMIT');
dibi::notify('commit', $this);
} }
@@ -186,49 +174,26 @@ class DibiSqliteDriver extends DibiDriver
*/ */
public function rollback() public function rollback()
{ {
$this->doQuery('ROLLBACK'); $this->query('ROLLBACK');
dibi::notify('rollback', $this);
} }
/** /**
* Escapes the string * Format to SQL command
* *
* @param string unescaped string * @param string value
* @param bool quote string? * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string escaped and optionally quoted string * @return string formatted value
*/ */
public function escape($value, $appendQuotes = TRUE) public function format($value, $type)
{ {
return $appendQuotes if ($type === dibi::FIELD_TEXT) return "'" . sqlite_escape_string($value) . "'";
? "'" . sqlite_escape_string($value) . "'" if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $value) . ']';
: sqlite_escape_string($value); if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
} if ($type === dibi::FIELD_DATE) return date("U", $value);
if ($type === dibi::FIELD_DATETIME) return date("U", $value);
throw new DibiException('Invalid formatting type');
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return '[' . str_replace('.', '].[', $value) . ']';
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
} }
@@ -241,41 +206,26 @@ class DibiSqliteDriver extends DibiDriver
* @param int $offset * @param int $offset
* @return void * @return void
*/ */
public function applyLimit(&$sql, $limit, $offset = 0) public function applyLimit(&$sql, $limit, $offset)
{ {
if ($limit < 0 && $offset < 1) return; if ($limit < 0 && $offset < 1) return;
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : ''); $sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
} }
} // class DibiSqliteDriver
/**
* The dibi result-set class for SQLite database
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
class DibiSqliteResult extends DibiResult
{
/** /**
* Returns the number of rows in a result set * Returns the number of rows in a result set
* *
* @return int * @return int
*/ */
protected function doRowCount() public function rowCount()
{ {
return sqlite_num_rows($this->resource); if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
return sqlite_num_rows($this->resultset);
} }
@@ -286,9 +236,9 @@ class DibiSqliteResult extends DibiResult
* *
* @return array|FALSE array on success, FALSE if no next record * @return array|FALSE array on success, FALSE if no next record
*/ */
protected function doFetch() public function fetch()
{ {
return sqlite_fetch_array($this->resource, SQLITE_ASSOC); return sqlite_fetch_array($this->resultset, SQLITE_ASSOC);
} }
@@ -300,10 +250,13 @@ class DibiSqliteResult extends DibiResult
* @return void * @return void
* @throws DibiException * @throws DibiException
*/ */
protected function doSeek($row) public function seek($row)
{ {
if (!$this->buffered) {
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
DibiDatabaseException::catchError(); DibiDatabaseException::catchError();
sqlite_seek($this->resource, $row); sqlite_seek($this->resultset, $row);
DibiDatabaseException::restore(); DibiDatabaseException::restore();
} }
@@ -314,23 +267,55 @@ class DibiSqliteResult extends DibiResult
* *
* @return void * @return void
*/ */
protected function doFree() public function free()
{ {
} }
/** this is experimental */ /** this is experimental */
protected function buildMeta() public function buildMeta()
{ {
$count = sqlite_num_fields($this->resource); $count = sqlite_num_fields($this->resultset);
$this->meta = $this->convert = array(); $meta = array();
for ($index = 0; $index < $count; $index++) { for ($index = 0; $index < $count; $index++) {
$name = sqlite_field_name($this->resource, $index); $name = sqlite_field_name($this->resultset, $index);
$this->meta[$name] = array('type' => dibi::FIELD_UNKNOWN); $meta[$name] = array('type' => dibi::FIELD_UNKNOWN);
$this->convert[$name] = dibi::FIELD_UNKNOWN;
} }
return $meta;
} }
} // class DibiSqliteResult /**
* Returns the connection resource
*
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/**
* Returns the resultset resource
*
* @return mixed
*/
public function getResultResource()
{
return $this->resultset;
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
function getDibiReflection()
{}
}

View File

@@ -20,14 +20,14 @@
/** /**
* dibi Common Driver * dibi connection
* *
* @author David Grudl * @author David Grudl
* @copyright Copyright (c) 2005, 2007 David Grudl * @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
abstract class DibiDriver extends NObject class DibiConnection extends NObject
{ {
/** /**
* Current connection configuration * Current connection configuration
@@ -36,33 +36,47 @@ abstract class DibiDriver extends NObject
private $config; private $config;
/** /**
* Connection resource * DibiDriverInterface
* @var resource
*/
private $connection;
/**
* Describes how convert some datatypes to SQL command
* @var array * @var array
*/ */
public $formats = array( private $driver;
'TRUE' => "1", // boolean true
'FALSE' => "0", // boolean false /**
'date' => "'Y-m-d'", // format used by date() * Is connected?
'datetime' => "'Y-m-d H:i:s'", // format used by date() * @var bool
); */
private $connected = FALSE;
/** /**
* Creates object and (optionally) connects to a database * Creates object and (optionally) connects to a database
* *
* @param array connect configuration * @param array|string connection parameters
* @throws DibiException * @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->config = $config;
$this->driver = new $class;
if (empty($config['lazy'])) { if (empty($config['lazy'])) {
$this->connect(); $this->connect();
@@ -88,9 +102,10 @@ abstract class DibiDriver extends NObject
* *
* @return void * @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'); dibi::notify('connected');
} }
@@ -103,17 +118,19 @@ abstract class DibiDriver extends NObject
*/ */
final public function disconnect() final public function disconnect()
{ {
$this->doDisconnect(); if ($this->connected) {
$this->connection = NULL; $this->driver->disconnect();
$this->connected = FALSE;
dibi::notify('disconnected'); dibi::notify('disconnected');
} }
}
/** /**
* Returns configuration variable. If no $key is passed, returns the entire array. * Returns configuration variable. If no $key is passed, returns the entire array.
* *
* @see DibiDriver::__construct * @see self::__construct
* @param string * @param string
* @param mixed default value to use if key not found * @param mixed default value to use if key not found
* @return mixed * @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 * Returns the connection resource
* *
* @return resource * @return resource
*/ */
final public function getConnection() final public function getResource()
{ {
if ($this->connection === NULL) { return $this->driver->getResource();
$this->connect();
}
return $this->connection;
} }
@@ -160,7 +195,7 @@ abstract class DibiDriver extends NObject
{ {
if (!is_array($args)) $args = func_get_args(); if (!is_array($args)) $args = func_get_args();
$trans = new DibiTranslator($this); $trans = new DibiTranslator($this->driver);
if ($trans->translate($args)) { if ($trans->translate($args)) {
return $this->nativeQuery($trans->sql); return $this->nativeQuery($trans->sql);
} else { } else {
@@ -180,7 +215,7 @@ abstract class DibiDriver extends NObject
{ {
if (!is_array($args)) $args = func_get_args(); if (!is_array($args)) $args = func_get_args();
$trans = new DibiTranslator($this); $trans = new DibiTranslator($this->driver);
$ok = $trans->translate($args); $ok = $trans->translate($args);
dibi::dump($trans->sql); dibi::dump($trans->sql);
return $ok; return $ok;
@@ -197,74 +232,30 @@ abstract class DibiDriver extends NObject
*/ */
final public function nativeQuery($sql) final public function nativeQuery($sql)
{ {
if (!$this->connected) $this->connect();
dibi::notify('beforeQuery', $this, $sql); 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); 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 * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query
* *
* @return int number of rows or FALSE on error * @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 * @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). * Begins a transaction (if supported).
* @return void * @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. * Commits statements in a transaction.
* @return void * @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. * Rollback changes in a transaction.
* @return void * @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() public function __toString()
{ {
$s = parent::__toString(); return parent::__toString() . ($this->sql ? "\nSQL: " . $this->sql : '');
if ($this->sql) {
$s .= "\nSQL: " . $this->sql;
}
return $s;
} }

View File

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

View File

@@ -40,8 +40,14 @@
* @package dibi * @package dibi
* @version $Revision$ $Date$ * @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 * Describes columns types
* @var array * @var array
@@ -54,18 +60,6 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/ */
protected $meta; 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) * Already fetched? Used for allowance for first seek(0)
* @var bool * @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->driver = $driver;
$this->buffered = $buffered;
} }
/** /**
* Returns the resultset resource * Returns the resultset resource
* *
* @return resource * @return mixed
*/ */
final public function getResource() 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; return TRUE;
} }
if (!$this->buffered) { $this->driver->seek($row);
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
}
return $this->doSeek($row);
} }
@@ -134,52 +123,9 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/ */
final public function rowCount() final public function rowCount()
{ {
if (!$this->buffered) { return $this->driver->rowCount();
throw new BadMethodCallException(__METHOD__ . ' is not allowed for unbuffered queries');
} }
return $this->doRowCount();
}
/**
* 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();
/** /**
@@ -190,7 +136,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/ */
final public function fetch() final public function fetch()
{ {
$row = $this->doFetch(); $row = $this->driver->fetch();
if (!is_array($row)) return FALSE; if (!is_array($row)) return FALSE;
$this->fetched = TRUE; $this->fetched = TRUE;
@@ -215,7 +161,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/ */
final function fetchSingle() final function fetchSingle()
{ {
$row = $this->doFetch(); $row = $this->driver->fetch();
if (!is_array($row)) return FALSE; if (!is_array($row)) return FALSE;
$this->fetched = TRUE; $this->fetched = TRUE;
@@ -395,7 +341,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/ */
public function __destruct() 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) final public function setType($field, $type = NULL)
{ {
if ($field === TRUE) { if ($field === TRUE) {
$this->detectTypes(); $this->buildMeta();
} elseif (is_array($field)) { } elseif (is_array($field)) {
$this->convert = $field; $this->convert = $field;
@@ -434,11 +380,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
return $value; 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 strtotime($value); // !!! not good
} }
@@ -454,10 +396,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/ */
final public function getFields() final public function getFields()
{ {
// lazy init
if ($this->meta === NULL) {
$this->buildMeta(); $this->buildMeta();
}
return array_keys($this->meta); return array_keys($this->meta);
} }
@@ -471,10 +410,7 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
*/ */
final public function getMetaData($field) final public function getMetaData($field)
{ {
// lazy init
if ($this->meta === NULL) {
$this->buildMeta(); $this->buildMeta();
}
return isset($this->meta[$field]) ? $this->meta[$field] : FALSE; return isset($this->meta[$field]) ? $this->meta[$field] : FALSE;
} }
@@ -485,19 +421,15 @@ abstract class DibiResult extends NObject implements IteratorAggregate, Countabl
* *
* @return void * @return void
*/ */
final protected function detectTypes() final protected function buildMeta()
{ {
if ($this->meta === NULL) { 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();
@@ -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 */ /** @var string NOT USED YET */
public $mask; public $mask;
/** @var DibiDriver */ /** @var DibiDriverInterface */
private $driver; private $driver;
/** @var string last modifier */ /** @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; $this->driver = $driver;
} }
@@ -105,7 +105,7 @@ final class DibiTranslator extends NObject
if (is_string($arg) && (!$mod || $mod === 'sql')) { if (is_string($arg) && (!$mod || $mod === 'sql')) {
$mod = FALSE; $mod = FALSE;
// will generate new mod // will generate new mod
$mask[] = $sql[] = $this->formatValue($arg, 'sql'); /*$mask[] =*/ $sql[] = $this->formatValue($arg, 'sql');
continue; continue;
} }
@@ -117,13 +117,13 @@ final class DibiTranslator extends NObject
$mod = $commandIns ? 'v' : 'a'; $mod = $commandIns ? 'v' : 'a';
} else { } else {
$mod = $commandIns ? 'l' : 'a'; $mod = $commandIns ? 'l' : 'a';
if ($lastArr === $i - 1) $mask[] = $sql[] = ','; if ($lastArr === $i - 1) /*$mask[] =*/ $sql[] = ',';
} }
$lastArr = $i; $lastArr = $i;
} }
// default processing // default processing
$mask[] = '?'; //$mask[] = '?';
if (!$comment) { if (!$comment) {
$sql[] = $this->formatValue($arg, $mod); $sql[] = $this->formatValue($arg, $mod);
} }
@@ -132,7 +132,7 @@ final class DibiTranslator extends NObject
if ($comment) $sql[] = "\0"; if ($comment) $sql[] = "\0";
//$this->mask = implode(' ', $mask); /*$this->mask = implode(' ', $mask);*/
$this->sql = implode(' ', $sql); $this->sql = implode(' ', $sql);
@@ -218,15 +218,13 @@ final class DibiTranslator extends NObject
switch ($modifier) { switch ($modifier) {
case 's': // string case 's': // string
return $this->driver->escape($value); return $this->driver->format($value, dibi::FIELD_TEXT);
case 'sn': // string or NULL 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 case 'b': // boolean
return $value return $this->driver->format($value, dibi::FIELD_BOOL);
? $this->driver->formats['TRUE']
: $this->driver->formats['FALSE'];
case 'i': // signed int case 'i': // signed int
case 'u': // unsigned int, ignored case 'u': // unsigned int, ignored
@@ -244,14 +242,10 @@ final class DibiTranslator extends NObject
return (string) ($value + 0); return (string) ($value + 0);
case 'd': // date case 'd': // date
return date($this->driver->formats['date'], is_string($value) return $this->driver->format(is_string($value) ? strtotime($value) : $value, dibi::FIELD_DATE);
? strtotime($value)
: $value);
case 't': // datetime case 't': // datetime
return date($this->driver->formats['datetime'], is_string($value) return $this->driver->format(is_string($value) ? strtotime($value) : $value, dibi::FIELD_DATETIME);
? strtotime($value)
: $value);
case 'n': // identifier name case 'n': // identifier name
return $this->delimite($value); return $this->delimite($value);
@@ -306,13 +300,13 @@ final class DibiTranslator extends NObject
// without modifier procession // without modifier procession
if (is_string($value)) if (is_string($value))
return $this->driver->escape($value); return $this->driver->format($value, dibi::FIELD_TEXT);
if (is_int($value) || is_float($value)) if (is_int($value) || is_float($value))
return (string) $value; // something like -9E-005 is accepted by SQL return (string) $value; // something like -9E-005 is accepted by SQL
if (is_bool($value)) 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) if ($value === NULL)
return 'NULL'; return 'NULL';
@@ -388,10 +382,10 @@ final class DibiTranslator extends NObject
return $this->delimite($matches[2]); return $this->delimite($matches[2]);
if ($matches[3]) // SQL strings: '....' 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: "..." 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 if ($matches[9]) { // string quote
@@ -415,7 +409,7 @@ final class DibiTranslator extends NObject
if (strpos($value, ':') !== FALSE) { if (strpos($value, ':') !== FALSE) {
$value = strtr($value, dibi::getSubst()); $value = strtr($value, dibi::getSubst());
} }
return $this->driver->delimite($value); return $this->driver->format($value, dibi::IDENTIFIER);
} }

View File

@@ -46,10 +46,7 @@ class MyDateTime implements DibiVariableInterface
*/ */
public function toSQL($driver, $modifier = NULL) public function toSQL($driver, $modifier = NULL)
{ {
return date( return $driver->format($this->time, dibi::FIELD_DATETIME); // format according to driver's spec.
$driver->formats['datetime'], // format according to driver's spec.
$this->time
);
} }