1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-03 20:57: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
require_once __FILE__ . '/../libs/NObject.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/DibiResultIterator.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
*
@@ -90,21 +71,22 @@ class dibi extends NClass
FIELD_UNKNOWN = '?',
// special
FIELD_COUNTER = 'c', // counter or autoincrement, is integer
FIELD_COUNTER = 'C', // counter or autoincrement, is integer
IDENTIFIER = 'I',
// dibi version
VERSION = '0.9 (Revision: $WCREV$, Date: $WCDATE$)';
/**
* Connection registry storage for DibiDriver objects
* @var DibiDriver[]
* Connection registry storage for DibiConnection objects
* @var DibiConnection[]
*/
private static $registry = array();
/**
* Current connection
* @var DibiDriver
* @var DibiConnection
*/
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 string connection name
* @return DibiDriver
* @return DibiConnection
* @throws DibiException
*/
public static function connect($config = array(), $name = 0)
{
// DSN string
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);
return self::$connection = self::$registry[$name] = new DibiConnection($config);
}
/**
* Disconnects from database (doesn't destroy DibiDriver object)
* Disconnects from database (doesn't destroy DibiConnection object)
*
* @return void
*/
@@ -222,7 +185,7 @@ class dibi extends NClass
* Retrieve active connection
*
* @param string connection registy name
* @return object DibiDriver object.
* @return object DibiConnection object.
* @throws DibiException
*/
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
* @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.
* @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
* @return bool
@@ -304,7 +267,7 @@ class dibi extends NClass
/**
* 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
* @return int|FALSE int on success or FALSE on failure
@@ -318,7 +281,7 @@ class dibi extends NClass
/**
* Gets the number of affected rows
* Monostate for DibiDriver::affectedRows()
* Monostate for DibiConnection::affectedRows()
*
* @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()
{
@@ -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()
{
@@ -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()
{
@@ -434,11 +397,11 @@ class dibi extends NClass
* Event notification (events: exception, connected, beforeQuery, afterQuery, begin, commit, rollback)
*
* @param string event name
* @param DibiDriver
* @param DibiConnection
* @param mixed
* @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') {
self::$numOfQueries++;
@@ -452,7 +415,7 @@ class dibi extends NClass
}
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
* @version $Revision$ $Date$
*/
class DibiMsSqlDriver extends DibiDriver
class DibiMsSqlDriver extends NObject implements DibiDriverInterface
{
/**
* Describes how convert some datatypes to SQL command
* @var array
* Connection resource
* @var resource
*/
public $formats = array(
'TRUE' => "-1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
private $connection;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @throws DibiException
* Resultset resource
* @var resource
*/
public function __construct(array $config)
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'host');
parent::__construct($config);
}
private $resultset;
@@ -67,31 +55,32 @@ class DibiMsSqlDriver extends DibiDriver
* Connects to a database
*
* @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')) {
throw new DibiException("PHP extension 'mssql' is not loaded");
}
$config = $this->getConfig();
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 {
$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");
}
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]'");
}
return $connection;
}
@@ -101,29 +90,29 @@ class DibiMsSqlDriver extends DibiDriver
*
* @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.
* @return DibiResult Result set object
* @return bool have resultset?
* @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);
}
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()
{
$rows = mssql_rows_affected($this->getConnection());
return $rows < 0 ? FALSE : $rows;
return mssql_rows_affected($this->connection);
}
@@ -146,7 +134,7 @@ class DibiMsSqlDriver extends DibiDriver
*
* @return int|FALSE int on success or FALSE on failure
*/
public function insertId()
public function insertId($sequence)
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
}
@@ -159,8 +147,7 @@ class DibiMsSqlDriver extends DibiDriver
*/
public function begin()
{
$this->doQuery('BEGIN TRANSACTION');
dibi::notify('begin', $this);
$this->query('BEGIN TRANSACTION');
}
@@ -171,8 +158,7 @@ class DibiMsSqlDriver extends DibiDriver
*/
public function commit()
{
$this->doQuery('COMMIT');
dibi::notify('commit', $this);
$this->query('COMMIT');
}
@@ -183,50 +169,26 @@ class DibiMsSqlDriver extends DibiDriver
*/
public function rollback()
{
$this->doQuery('ROLLBACK');
dibi::notify('rollback', $this);
$this->query('ROLLBACK');
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
$value = str_replace("'", "''", $value);
return $appendQuotes
? "'" . $value . "'"
: $value;
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return "'" . str_replace("'", "''", $value) . "'";
if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $value) . ']';
if ($type === dibi::FIELD_BOOL) return $value ? -1 : 0;
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');
}
@@ -239,7 +201,7 @@ class DibiMsSqlDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
// offset suppot is missing...
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
*
* @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
*/
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
* @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);
}
}
@@ -319,15 +262,15 @@ class DibiMSSqlResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
mssql_free_result($this->resource);
mssql_free_result($this->resultset);
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
static $types = array(
'CHAR' => dibi::FIELD_TEXT,
@@ -355,21 +298,53 @@ class DibiMSSqlResult extends DibiResult
// and many others?
);
$count = mssql_num_fields($this->resource);
$this->meta = $this->convert = array();
$count = mssql_num_fields($this->resultset);
$meta = array();
for ($index = 0; $index < $count; $index++) {
$tmp = mssql_fetch_field($this->resource, $index);
$tmp = mssql_fetch_field($this->resultset, $index);
$type = strtoupper($tmp->type);
$info['native'] = $tmp->type;
$info['type'] = isset($types[$type]) ? $types[$type] : dibi::FIELD_UNKNOWN;
$info['length'] = $tmp->max_length;
$info['table'] = $tmp->column_source;
$this->meta[$tmp->name] = $info;
$this->convert[$tmp->name] = $info['type'];
$meta[$tmp->name] = $info;
}
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
* @version $Revision$ $Date$
*/
class DibiMySqlDriver extends DibiDriver
class DibiMySqlDriver extends NObject implements DibiDriverInterface
{
/**
* Describes how convert some datatypes to SQL command
* @var array
* Connection resource
* @var resource
*/
public $formats = array(
'TRUE' => "1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
private $connection;
/**
* 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
* @return void
*/
public function __construct(array $config)
public function connect(array &$config)
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'options');
if (!extension_loaded('mysql')) {
throw new DibiException("PHP extension 'mysql' is not loaded");
}
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'options');
// default values
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'])) {
$host = $config['host'] . (empty($config['port']) ? '' : ':' . $config['port']);
@@ -105,26 +101,26 @@ class DibiMySqlDriver extends DibiDriver
DibiDatabaseException::catchError();
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 {
$connection = @mysql_pconnect($host, $config['username'], $config['password'], $config['options']);
$this->connection = @mysql_pconnect($host, $config['username'], $config['password'], $config['options']);
}
DibiDatabaseException::restore();
if (!is_resource($connection)) {
if (!is_resource($this->connection)) {
throw new DibiDatabaseException(mysql_error(), mysql_errno());
}
if (isset($config['charset'])) {
@mysql_query("SET NAMES '" . $config['charset'] . "'", $connection);
@mysql_query("SET NAMES '" . $config['charset'] . "'", $this->connection);
// don't handle this error...
}
if (isset($config['database']) && !@mysql_select_db($config['database'], $connection)) {
throw new DibiDatabaseException(mysql_error($connection), mysql_errno($connection));
if (isset($config['database']) && !@mysql_select_db($config['database'], $this->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
*/
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.
* @return DibiResult Result set object
* @return bool have resultset?
* @throws DibiDatabaseException
*/
protected function doQuery($sql)
public function query($sql)
{
$connection = $this->getConnection();
$buffered = !$this->getConfig('unbuffered');
if ($buffered) {
$res = @mysql_query($sql, $connection);
if ($this->buffered) {
$this->resultset = @mysql_query($sql, $this->connection);
} else {
$res = @mysql_unbuffered_query($sql, $connection);
$this->resultset = @mysql_unbuffered_query($sql, $this->connection);
}
if ($errno = mysql_errno($connection)) {
throw new DibiDatabaseException(mysql_error($connection), $errno, $sql);
if ($errno = mysql_errno($this->connection)) {
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()
{
$rows = mysql_affected_rows($this->getConnection());
return $rows < 0 ? FALSE : $rows;
return mysql_affected_rows($this->connection);
}
@@ -186,10 +178,9 @@ class DibiMySqlDriver extends DibiDriver
*
* @return int|FALSE int on success or FALSE on failure
*/
public function insertId()
public function insertId($sequence)
{
$id = mysql_insert_id($this->getConnection());
return $id < 1 ? FALSE : $id;
return mysql_insert_id($this->connection);
}
@@ -200,8 +191,7 @@ class DibiMySqlDriver extends DibiDriver
*/
public function begin()
{
$this->doQuery('BEGIN');
dibi::notify('begin', $this);
$this->query('BEGIN');
}
@@ -212,8 +202,7 @@ class DibiMySqlDriver extends DibiDriver
*/
public function commit()
{
$this->doQuery('COMMIT');
dibi::notify('commit', $this);
$this->query('COMMIT');
}
@@ -224,50 +213,26 @@ class DibiMySqlDriver extends DibiDriver
*/
public function rollback()
{
$this->doQuery('ROLLBACK');
dibi::notify('rollback', $this);
$this->query('ROLLBACK');
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
$connection = $this->getConnection();
return $appendQuotes
? "'" . mysql_real_escape_string($value, $connection) . "'"
: mysql_real_escape_string($value, $connection);
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return "'" . mysql_real_escape_string($value, $this->connection) . "'";
if ($type === dibi::IDENTIFIER) return '`' . str_replace('.', '`.`', $value) . '`';
if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
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');
}
@@ -280,7 +245,7 @@ class DibiMySqlDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
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
*
* @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
*/
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
* @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);
}
}
@@ -357,15 +309,15 @@ class DibiMySqlResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
mysql_free_result($this->resource);
mysql_free_result($this->resultset);
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
static $types = array(
'ENUM' => dibi::FIELD_TEXT, // eventually dibi::FIELD_INTEGER
@@ -402,14 +354,14 @@ class DibiMySqlResult extends DibiResult
'NUMERIC' => dibi::FIELD_FLOAT,
);
$count = mysql_num_fields($this->resource);
$this->meta = $this->convert = array();
$count = mysql_num_fields($this->resultset);
$meta = array();
for ($index = 0; $index < $count; $index++) {
$info['native'] = $native = strtoupper(mysql_field_type($this->resource, $index));
$info['flags'] = explode(' ', mysql_field_flags($this->resource, $index));
$info['length'] = mysql_field_len($this->resource, $index);
$info['table'] = mysql_field_table($this->resource, $index);
$info['native'] = $native = strtoupper(mysql_field_type($this->resultset, $index));
$info['flags'] = explode(' ', mysql_field_flags($this->resultset, $index));
$info['length'] = mysql_field_len($this->resultset, $index);
$info['table'] = mysql_field_table($this->resultset, $index);
if (in_array('auto_increment', $info['flags'])) { // or 'primary_key' ?
$info['type'] = dibi::FIELD_COUNTER;
@@ -420,11 +372,43 @@ class DibiMySqlResult extends DibiResult
// $info['type'] = dibi::FIELD_LONG_TEXT;
}
$name = mysql_field_name($this->resource, $index);
$this->meta[$name] = $info;
$this->convert[$name] = $info['type'];
$name = mysql_field_name($this->resultset, $index);
$meta[$name] = $info;
}
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
* @version $Revision$ $Date$
*/
class DibiMySqliDriver extends DibiDriver
class DibiMySqliDriver extends NObject implements DibiDriverInterface
{
/**
* Describes how convert some datatypes to SQL command
* @var array
* Connection resource
* @var resource
*/
public $formats = array(
'TRUE' => "1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
private $connection;
/**
* 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
* @return void
*/
public function __construct(array $config)
public function connect(array &$config)
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'options');
self::alias($config, 'database');
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'options');
DibiConnection::alias($config, 'database');
// default values
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';
}
parent::__construct($config);
}
/**
* Connects to a database
*
* @throws DibiException
* @return resource
*/
protected function doConnect()
{
if (!extension_loaded('mysqli')) {
throw new DibiException("PHP extension 'mysqli' is not loaded");
}
$config = $this->getConfig();
$connection = mysqli_init();
@mysqli_real_connect($connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']);
$this->connection = mysqli_init();
@mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']);
if ($errno = mysqli_connect_errno()) {
throw new DibiDatabaseException(mysqli_connect_error(), $errno);
}
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
*
* @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.
* @return DibiResult Result set object
* @return bool have resultset?
* @throws DibiDatabaseException
*/
protected function doQuery($sql)
public function query($sql)
{
$connection = $this->getConnection();
$buffered = !$this->getConfig('unbuffered');
$res = @mysqli_query($connection, $sql, $buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
$this->resultset = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
if ($errno = mysqli_errno($connection)) {
throw new DibiDatabaseException(mysqli_error($connection), $errno, $sql);
if ($errno = mysqli_errno($this->connection)) {
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()
{
$rows = mysqli_affected_rows($this->getConnection());
return $rows < 0 ? FALSE : $rows;
return mysqli_affected_rows($this->connection);
}
@@ -162,10 +154,9 @@ class DibiMySqliDriver extends DibiDriver
*
* @return int|FALSE int on success or FALSE on failure
*/
public function insertId()
public function insertId($sequence)
{
$id = mysqli_insert_id($this->getConnection());
return $id < 1 ? FALSE : $id;
return mysqli_insert_id($this->connection);
}
@@ -176,11 +167,9 @@ class DibiMySqliDriver extends DibiDriver
*/
public function begin()
{
$connection = $this->getConnection();
if (!mysqli_autocommit($connection, FALSE)) {
throw new DibiDatabaseException(mysqli_error($connection), mysqli_errno($connection));
if (!mysqli_autocommit($this->connection, FALSE)) {
throw new DibiDatabaseException(mysqli_error($this->connection), mysqli_errno($this->connection));
}
dibi::notify('begin', $this);
}
@@ -191,12 +180,10 @@ class DibiMySqliDriver extends DibiDriver
*/
public function commit()
{
$connection = $this->getConnection();
if (!mysqli_commit($connection)) {
throw new DibiDatabaseException(mysqli_error($connection), mysqli_errno($connection));
if (!mysqli_commit($this->connection)) {
throw new DibiDatabaseException(mysqli_error($this->connection), mysqli_errno($this->connection));
}
mysqli_autocommit($connection, TRUE);
dibi::notify('commit', $this);
mysqli_autocommit($this->connection, TRUE);
}
@@ -207,54 +194,29 @@ class DibiMySqliDriver extends DibiDriver
*/
public function rollback()
{
$connection = $this->getConnection();
if (!mysqli_rollback($connection)) {
throw new DibiDatabaseException(mysqli_error($connection), mysqli_errno($connection));
if (!mysqli_rollback($this->connection)) {
throw new DibiDatabaseException(mysqli_error($this->connection), mysqli_errno($this->connection));
}
mysqli_autocommit($connection, TRUE);
dibi::notify('rollback', $this);
mysqli_autocommit($this->connection, TRUE);
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
$connection = $this->getConnection();
return $appendQuotes
? "'" . mysqli_real_escape_string($connection, $value) . "'"
: mysqli_real_escape_string($connection, $value);
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
if ($type === dibi::IDENTIFIER) return '`' . str_replace('.', '`.`', $value) . '`';
if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
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');
}
@@ -267,7 +229,7 @@ class DibiMySqliDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
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
*
* @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
*/
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
* @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);
}
}
@@ -344,15 +294,15 @@ class DibiMySqliResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
mysqli_free_result($this->resource);
mysqli_free_result($this->resultset);
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
static $types = array(
MYSQLI_TYPE_FLOAT => dibi::FIELD_FLOAT,
@@ -382,10 +332,10 @@ class DibiMySqliResult extends DibiResult
MYSQLI_TYPE_BLOB => dibi::FIELD_BINARY,
);
$count = mysqli_num_fields($this->resource);
$this->meta = $this->convert = array();
$count = mysqli_num_fields($this->resultset);
$meta = array();
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'];
if ($info['flags'] & MYSQLI_AUTO_INCREMENT_FLAG) { // or 'primary_key' ?
@@ -396,10 +346,42 @@ class DibiMySqliResult extends DibiResult
// $info['type'] = dibi::FIELD_LONG_TEXT;
}
$this->meta[$info['name']] = $info;
$this->convert[$info['name']] = $info['type'];
$meta[$info['name']] = $info;
}
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
* @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
* @var mixed
* Connection resource
* @var resource
*/
private $affectedRows = FALSE;
private $connection;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @throws DibiException
* Resultset resource
* @var resource
*/
public function __construct(array $config)
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
private $resultset;
// 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
*
* @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')) {
throw new DibiException("PHP extension 'odbc' is not loaded");
}
$config = $this->getConfig();
if (empty($config['persistent'])) {
$connection = @odbc_connect($config['dsn'], $config['username'], $config['password']);
$this->connection = @odbc_connect($config['dsn'], $config['username'], $config['password']);
} 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());
}
return $connection;
}
@@ -108,35 +96,30 @@ class DibiOdbcDriver extends DibiDriver
*
* @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.
* @return DibiResult Result set object
* @return bool have resultset?
* @throws DibiDatabaseException
*/
protected function doQuery($sql)
public function query($sql)
{
$this->affectedRows = FALSE;
$connection = $this->getConnection();
$res = @odbc_exec($connection, $sql);
$this->resultset = @odbc_exec($this->connection, $sql);
if ($res === FALSE) {
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection), $sql);
if ($this->resultset === FALSE) {
throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection), $sql);
}
if (is_resource($res)) {
$this->affectedRows = odbc_num_rows($res);
if ($this->affectedRows < 0) $this->affectedRows = FALSE;
return new DibiOdbcResult($res, TRUE);
}
return is_resource($this->resultset);
}
@@ -148,7 +131,7 @@ class DibiOdbcDriver extends DibiDriver
*/
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
*/
public function insertId()
public function insertId($sequence)
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
}
@@ -171,11 +154,9 @@ class DibiOdbcDriver extends DibiDriver
*/
public function begin()
{
$connection = $this->getConnection();
if (!odbc_autocommit($connection, FALSE)) {
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection));
if (!odbc_autocommit($this->connection, FALSE)) {
throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection));
}
dibi::notify('begin', $this);
}
@@ -186,12 +167,10 @@ class DibiOdbcDriver extends DibiDriver
*/
public function commit()
{
$connection = $this->getConnection();
if (!odbc_commit($connection)) {
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection));
if (!odbc_commit($this->connection)) {
throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection));
}
odbc_autocommit($connection, TRUE);
dibi::notify('commit', $this);
odbc_autocommit($this->connection, TRUE);
}
@@ -202,54 +181,29 @@ class DibiOdbcDriver extends DibiDriver
*/
public function rollback()
{
$connection = $this->getConnection();
if (!odbc_rollback($connection)) {
throw new DibiDatabaseException(odbc_errormsg($connection), odbc_error($connection));
if (!odbc_rollback($this->connection)) {
throw new DibiDatabaseException(odbc_errormsg($this->connection), odbc_error($this->connection));
}
odbc_autocommit($connection, TRUE);
dibi::notify('rollback', $this);
odbc_autocommit($this->connection, TRUE);
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
$value = str_replace("'", "''", $value);
return $appendQuotes
? "'" . $value . "'"
: $value;
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return "'" . str_replace("'", "''", $value) . "'";
if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $value) . ']';
if ($type === dibi::FIELD_BOOL) return $value ? -1 : 0;
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');
}
@@ -262,7 +216,7 @@ class DibiOdbcDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
// offset suppot is missing...
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
*/
protected function doRowCount()
public function rowCount()
{
// 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
*/
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
* @throws DibiException
*/
protected function doSeek($row)
public function seek($row)
{
$this->row = $row;
}
@@ -340,19 +274,19 @@ class DibiOdbcResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
odbc_free_result($this->resource);
odbc_free_result($this->resultset);
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
// cache
if ($this->meta !== NULL) {
return $this->meta;
if ($meta !== NULL) {
return $meta;
}
static $types = array(
@@ -381,21 +315,53 @@ class DibiOdbcResult extends DibiResult
// and many others?
);
$count = odbc_num_fields($this->resource);
$this->meta = $this->convert = array();
$count = odbc_num_fields($this->resultset);
$meta = array();
for ($index = 1; $index <= $count; $index++) {
$native = strtoupper(odbc_field_type($this->resource, $index));
$name = odbc_field_name($this->resource, $index);
$this->meta[$name] = array(
$native = strtoupper(odbc_field_type($this->resultset, $index));
$name = odbc_field_name($this->resultset, $index);
$meta[$name] = array(
'type' => isset($types[$native]) ? $types[$native] : dibi::FIELD_UNKNOWN,
'native' => $native,
'length' => odbc_field_len($this->resource, $index),
'scale' => odbc_field_scale($this->resource, $index),
'precision' => odbc_field_precision($this->resource, $index),
'length' => odbc_field_len($this->resultset, $index),
'scale' => odbc_field_scale($this->resultset, $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
* @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;
/**
* 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
*
* @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')) {
throw new DibiException("PHP extension 'oci8' is not loaded");
}
$config = $this->getConfig();
$connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']);
$this->connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']);
if (!$connection) {
if (!$this->connection) {
$err = oci_error();
throw new DibiDatabaseException($err['message'], $err['code']);
}
return $connection;
}
@@ -96,37 +88,36 @@ class DibiOracleDriver extends DibiDriver
*
* @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.
* @return DibiResult Result set object
* @return bool have resultset?
* @throws DibiDatabaseException
*/
protected function doQuery($sql)
public function query($sql)
{
$connection = $this->getConnection();
$statement = oci_parse($connection, $sql);
if ($statement) {
$res = oci_execute($statement, $this->autocommit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT);
$err = oci_error($statement);
$this->resultset = oci_parse($this->connection, $sql);
if ($this->resultset) {
oci_execute($this->resultset, $this->autocommit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT);
$err = oci_error($this->resultset);
if ($err) {
throw new DibiDatabaseException($err['message'], $err['code'], $sql);
}
} else {
$err = oci_error($connection);
$err = oci_error($this->connection);
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
*/
public function insertId()
public function insertId($sequence)
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
}
@@ -172,13 +163,11 @@ class DibiOracleDriver extends DibiDriver
*/
public function commit()
{
$connection = $this->getConnection();
if (!oci_commit($connection)) {
$err = oci_error($connection);
if (!oci_commit($this->connection)) {
$err = oci_error($this->connection);
throw new DibiDatabaseException($err['message'], $err['code']);
}
$this->autocommit = TRUE;
dibi::notify('commit', $this);
}
@@ -189,54 +178,30 @@ class DibiOracleDriver extends DibiDriver
*/
public function rollback()
{
$connection = $this->getConnection();
if (!oci_rollback($connection)) {
$err = oci_error($connection);
if (!oci_rollback($this->connection)) {
$err = oci_error($this->connection);
throw new DibiDatabaseException($err['message'], $err['code']);
}
$this->autocommit = TRUE;
dibi::notify('rollback', $this);
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
return $appendQuotes
? "'" . sqlite_escape_string($value) . "'"
: sqlite_escape_string($value);
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return "'" . str_replace("'", "''", $value) . "'"; // TODO: not tested
if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $value) . ']'; // TODO: not tested
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');
}
@@ -249,41 +214,23 @@ class DibiOracleDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
if ($limit < 0 && $offset < 1) return;
$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
*
* @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
*/
protected function doFetch()
public function fetch()
{
$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
* @throws DibiException
*/
protected function doSeek($row)
public function seek($row)
{
if ($row === 0 && !$this->fetched) return TRUE;
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
@@ -322,24 +269,56 @@ class DibiOracleResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
oci_free_statement($this->resource);
oci_free_statement($this->resultset);
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
$count = oci_num_fields($this->resource);
$this->meta = $this->convert = array();
$count = oci_num_fields($this->resultset);
$meta = array();
for ($index = 0; $index < $count; $index++) {
$name = oci_field_name($this->resource, $index + 1);
$this->meta[$name] = array('type' => dibi::FIELD_UNKNOWN);
$this->convert[$name] = dibi::FIELD_UNKNOWN;
$name = oci_field_name($this->resultset, $index + 1);
$meta[$name] = array('type' => 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
* @version $Revision$ $Date$
*/
class DibiPdoDriver extends DibiDriver
class DibiPdoDriver extends NObject implements DibiDriverInterface
{
/**
* Describes how convert some datatypes to SQL command
* @var array
* Connection resource
* @var resource
*/
public $formats = array(
'TRUE' => "1",
'FALSE' => "0",
'date' => "'Y-m-d'",
'datetime' => "'Y-m-d H:i:s'",
);
private $connection;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @throws DibiException
* Resultset resource
* @var resource
*/
public function __construct(array $config)
{
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'dsn');
self::alias($config, 'options');
parent::__construct($config);
}
private $resultset;
/**
* Cursor
* @var int
*/
private $row = 0;
/**
* Connects to a database
*
* @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')) {
throw new DibiException("PHP extension 'pdo' is not loaded");
}
$config = $this->getConfig();
$connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connection;
$this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
/**
* Disconnects from a database
*
* @return void
*/
protected function doDisconnect()
public function disconnect()
{
$this->connection = NULL;
}
/**
* Internal: Executes the SQL query
* Executes the SQL query
*
* @param string SQL statement.
* @return DibiResult Result set object
* @return bool have resultset?
* @throws DibiDatabaseException
*/
protected function doQuery($sql)
public function query($sql)
{
$res = $this->getConnection()->query($sql);
return $res instanceof PDOStatement ? new DibiPdoResult($res, TRUE) : NULL;
$this->resultset = $this->connection->query($sql);
return $this->resultset instanceof PDOStatement;
}
@@ -126,9 +122,9 @@ class DibiPdoDriver extends DibiDriver
*
* @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()
{
$this->getConnection()->beginTransaction();
dibi::notify('begin', $this);
$this->connection->beginTransaction();
}
@@ -151,8 +146,7 @@ class DibiPdoDriver extends DibiDriver
*/
public function commit()
{
$this->getConnection()->commit();
dibi::notify('commit', $this);
$this->connection->commit();
}
@@ -163,51 +157,26 @@ class DibiPdoDriver extends DibiDriver
*/
public function rollback()
{
$this->getConnection()->rollBack();
dibi::notify('rollback', $this);
$this->connection->rollBack();
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
if (!$appendQuotes) {
throw new BadMethodCallException('Escaping without qoutes is not supported by PDO');
}
return $this->getConnection()->quote($value);
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return $this->connection->quote($value);
if ($type === dibi::IDENTIFIER) return $value; // quoting is not supported by PDO
if ($type === dibi::FIELD_BOOL) return $value ? 1 : 0;
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');
}
@@ -220,32 +189,11 @@ class DibiPdoDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
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
*/
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
*/
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
* @throws DibiException
*/
protected function doSeek($row)
public function seek($row)
{
$this->row = $row;
}
@@ -292,26 +239,59 @@ class DibiPdoResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
$this->resultset = NULL;
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
$count = $this->resource->columnCount();
$this->meta = $this->convert = array();
$count = $this->resultset->columnCount();
$meta = array();
for ($index = 0; $index < $count; $index++) {
$meta = $this->resource->getColumnMeta($index);
$meta = $this->resultset->getColumnMeta($index);
// TODO:
$meta['type'] = dibi::FIELD_UNKNOWN;
$name = $meta['name'];
$this->meta[$name] = $meta;
$this->convert[$name] = $meta['type'];
$meta[$name] = $meta;
}
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
* @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
* @var mixed
* Connection resource
* @var resource
*/
private $affectedRows = FALSE;
private $connection;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @throws DibiException
* Resultset resource
* @var resource
*/
public function __construct(array $config)
{
self::alias($config, 'database', 'string');
self::alias($config, 'type');
parent::__construct($config);
}
private $resultset;
@@ -71,34 +53,34 @@ class DibiPostgreDriver extends DibiDriver
* Connects to a database
*
* @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')) {
throw new DibiException("PHP extension 'pgsql' is not loaded");
}
$config = $this->getConfig();
DibiDatabaseException::catchError();
if (isset($config['persistent'])) {
$connection = @pg_connect($config['database'], PGSQL_CONNECT_FORCE_NEW);
$this->connection = @pg_connect($config['database'], PGSQL_CONNECT_FORCE_NEW);
} else {
$connection = @pg_pconnect($config['database'], PGSQL_CONNECT_FORCE_NEW);
$this->connection = @pg_pconnect($config['database'], PGSQL_CONNECT_FORCE_NEW);
}
DibiDatabaseException::restore();
if (!is_resource($connection)) {
if (!is_resource($this->connection)) {
throw new DibiDatabaseException('unknown error');
}
if (isset($config['charset'])) {
@pg_set_client_encoding($connection, $config['charset']);
@pg_set_client_encoding($this->connection, $config['charset']);
// don't handle this error...
}
return $connection;
}
@@ -108,37 +90,30 @@ class DibiPostgreDriver extends DibiDriver
*
* @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 bool update affected rows?
* @return DibiResult Result set object
* @return bool have resultset?
* @throws DibiDatabaseException
*/
protected function doQuery($sql, $silent = FALSE)
public function query($sql)
{
$connection = $this->getConnection();
$res = @pg_query($connection, $sql);
$this->resultset = @pg_query($this->connection, $sql);
if ($res === FALSE) {
throw new DibiDatabaseException(pg_last_error($connection), 0, $sql);
if ($this->resultset === FALSE) {
throw new DibiDatabaseException(pg_last_error($this->connection), 0, $sql);
}
if (is_resource($res)) {
if (!$silent) {
$this->affectedRows = pg_affected_rows($res);
if ($this->affectedRows < 0) $this->affectedRows = FALSE;
}
return new DibiPostgreResult($res, TRUE);
}
return is_resource($this->resultset);
}
@@ -150,7 +125,7 @@ class DibiPostgreDriver extends DibiDriver
*/
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
*/
public function insertId($sequence = NULL)
public function insertId($sequence)
{
if ($sequence === NULL) {
// PostgreSQL 8.1 is needed
$res = $this->doQuery("SELECT LASTVAL() AS seq", TRUE);
$res = $this->query("SELECT LASTVAL() AS seq");
} else {
$res = $this->doQuery("SELECT CURRVAL('$sequence') AS seq", TRUE);
$res = $this->query("SELECT CURRVAL('$sequence') AS seq");
}
if (is_resource($res)) {
@@ -186,8 +161,7 @@ class DibiPostgreDriver extends DibiDriver
*/
public function begin()
{
$this->doQuery('BEGIN', TRUE);
dibi::notify('begin', $this);
$this->query('BEGIN');
}
@@ -198,8 +172,7 @@ class DibiPostgreDriver extends DibiDriver
*/
public function commit()
{
$this->doQuery('COMMIT', TRUE);
dibi::notify('commit', $this);
$this->query('COMMIT');
}
@@ -210,50 +183,26 @@ class DibiPostgreDriver extends DibiDriver
*/
public function rollback()
{
$this->doQuery('ROLLBACK', TRUE);
dibi::notify('rollback', $this);
$this->query('ROLLBACK');
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
return $appendQuotes
? "'" . pg_escape_string($value) . "'"
: pg_escape_string($value);
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return "'" . pg_escape_string($value) . "'";
if ($type === dibi::IDENTIFIER) return '"' . str_replace('.', '"."', str_replace('"', '""', $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');
}
@@ -266,7 +215,7 @@ class DibiPostgreDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
if ($limit >= 0)
$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
*
* @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
*/
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
* @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);
}
}
@@ -343,15 +274,15 @@ class DibiPostgreResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
pg_free_result($this->resource);
pg_free_result($this->resultset);
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
static $types = array(
'bool' => dibi::FIELD_BOOL,
@@ -370,20 +301,52 @@ class DibiPostgreResult extends DibiResult
'money' => dibi::FIELD_FLOAT,
);
$count = pg_num_fields($this->resource);
$this->meta = $this->convert = array();
$count = pg_num_fields($this->resultset);
$meta = array();
for ($index = 0; $index < $count; $index++) {
$info['native'] = $native = pg_field_type($this->resource, $index);
$info['length'] = pg_field_size($this->resource, $index);
$info['table'] = pg_field_table($this->resource, $index);
$info['native'] = $native = pg_field_type($this->resultset, $index);
$info['length'] = pg_field_size($this->resultset, $index);
$info['table'] = pg_field_table($this->resultset, $index);
$info['type'] = isset($types[$native]) ? $types[$native] : dibi::FIELD_UNKNOWN;
$name = pg_field_name($this->resource, $index);
$this->meta[$name] = $info;
$this->convert[$name] = $info['type'];
$name = pg_field_name($this->resultset, $index);
$meta[$name] = $info;
}
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
* @version $Revision$ $Date$
*/
class DibiSqliteDriver extends DibiDriver
class DibiSqliteDriver extends NObject implements DibiDriverInterface
{
/**
* Describes how convert some datatypes to SQL command
* @var array
* Connection resource
* @var resource
*/
public $formats = array(
'TRUE' => "1",
'FALSE' => "0",
'date' => "U",
'datetime' => "U",
);
private $connection;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @throws DibiException
* Resultset resource
* @var resource
*/
public function __construct($config)
{
self::alias($config, 'database', 'file');
parent::__construct($config);
}
private $resultset;
/**
* Is buffered (seekable and countable)?
* @var bool
*/
private $buffered;
/**
* Connects to a database
*
* @throws DibiException
* @return resource
* @return void
*/
protected function doConnect()
public function connect(array &$config)
{
DibiConnection::alias($config, 'database', 'file');
if (!extension_loaded('sqlite')) {
throw new DibiException("PHP extension 'sqlite' is not loaded");
}
$config = $this->getConfig();
$errorMsg = '';
if (empty($config['persistent'])) {
$connection = @sqlite_open($config['database'], 0666, $errorMsg);
$this->connection = @sqlite_open($config['database'], 0666, $errorMsg);
} 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);
}
return $connection;
$this->buffered = empty($config['unbuffered']);
}
/**
* Disconnects from a database
*
* @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.
* @return DibiResult Result set object
* @return bool have resultset?
* @throws DibiDatabaseException
*/
protected function doQuery($sql)
public function query($sql)
{
$connection = $this->getConnection();
$errorMsg = NULL;
$buffered = !$this->getConfig('unbuffered');
if ($buffered) {
$res = @sqlite_query($connection, $sql, SQLITE_ASSOC, $errorMsg);
if ($this->buffered) {
$this->resultset = @sqlite_query($this->connection, $sql, SQLITE_ASSOC, $errorMsg);
} else {
$res = @sqlite_unbuffered_query($connection, $sql, SQLITE_ASSOC, $errorMsg);
$this->resultset = @sqlite_unbuffered_query($this->connection, $sql, SQLITE_ASSOC, $errorMsg);
}
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()
{
$rows = sqlite_changes($this->getConnection());
return $rows < 0 ? FALSE : $rows;
return sqlite_changes($this->connection);
}
@@ -148,10 +139,9 @@ class DibiSqliteDriver extends DibiDriver
*
* @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 $id < 1 ? FALSE : $id;
return sqlite_last_insert_rowid($this->connection);
}
@@ -162,8 +152,7 @@ class DibiSqliteDriver extends DibiDriver
*/
public function begin()
{
$this->doQuery('BEGIN');
dibi::notify('begin', $this);
$this->query('BEGIN');
}
@@ -174,8 +163,7 @@ class DibiSqliteDriver extends DibiDriver
*/
public function commit()
{
$this->doQuery('COMMIT');
dibi::notify('commit', $this);
$this->query('COMMIT');
}
@@ -186,49 +174,26 @@ class DibiSqliteDriver extends DibiDriver
*/
public function rollback()
{
$this->doQuery('ROLLBACK');
dibi::notify('rollback', $this);
$this->query('ROLLBACK');
}
/**
* Escapes the string
* Format to SQL command
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
* @param string value
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, dibi::FIELD_DATE, dibi::FIELD_DATETIME, dibi::IDENTIFIER)
* @return string formatted value
*/
public function escape($value, $appendQuotes = TRUE)
public function format($value, $type)
{
return $appendQuotes
? "'" . sqlite_escape_string($value) . "'"
: sqlite_escape_string($value);
}
/**
* 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');
if ($type === dibi::FIELD_TEXT) return "'" . sqlite_escape_string($value) . "'";
if ($type === dibi::IDENTIFIER) return '[' . str_replace('.', '].[', $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');
}
@@ -241,41 +206,26 @@ class DibiSqliteDriver extends DibiDriver
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset = 0)
public function applyLimit(&$sql, $limit, $offset)
{
if ($limit < 0 && $offset < 1) return;
$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
*
* @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
*/
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
* @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();
sqlite_seek($this->resource, $row);
sqlite_seek($this->resultset, $row);
DibiDatabaseException::restore();
}
@@ -314,23 +267,55 @@ class DibiSqliteResult extends DibiResult
*
* @return void
*/
protected function doFree()
public function free()
{
}
/** this is experimental */
protected function buildMeta()
public function buildMeta()
{
$count = sqlite_num_fields($this->resource);
$this->meta = $this->convert = array();
$count = sqlite_num_fields($this->resultset);
$meta = array();
for ($index = 0; $index < $count; $index++) {
$name = sqlite_field_name($this->resource, $index);
$this->meta[$name] = array('type' => dibi::FIELD_UNKNOWN);
$this->convert[$name] = dibi::FIELD_UNKNOWN;
$name = sqlite_field_name($this->resultset, $index);
$meta[$name] = array('type' => 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
* @copyright Copyright (c) 2005, 2007 David Grudl
* @package dibi
* @version $Revision$ $Date$
*/
abstract class DibiDriver extends NObject
class DibiConnection extends NObject
{
/**
* Current connection configuration
@@ -36,33 +36,47 @@ abstract class DibiDriver extends NObject
private $config;
/**
* Connection resource
* @var resource
*/
private $connection;
/**
* Describes how convert some datatypes to SQL command
* DibiDriverInterface
* @var array
*/
public $formats = array(
'TRUE' => "1", // boolean true
'FALSE' => "0", // boolean false
'date' => "'Y-m-d'", // format used by date()
'datetime' => "'Y-m-d H:i:s'", // format used by date()
);
private $driver;
/**
* Is connected?
* @var bool
*/
private $connected = FALSE;
/**
* Creates object and (optionally) connects to a database
*
* @param array connect configuration
* @param array|string connection parameters
* @throws DibiException
*/
public function __construct(array $config)
public function __construct($config)
{
// DSN string
if (is_string($config)) {
parse_str($config, $config);
}
if (!isset($config['driver'])) {
$config['driver'] = dibi::$defaultDriver;
}
$class = "Dibi$config[driver]Driver";
if (!class_exists($class)) {
include_once __FILE__ . "/../../drivers/$config[driver].php";
if (!class_exists($class)) {
throw new DibiException("Unable to create instance of dibi driver class '$class'.");
}
}
$this->config = $config;
$this->driver = new $class;
if (empty($config['lazy'])) {
$this->connect();
@@ -88,9 +102,10 @@ abstract class DibiDriver extends NObject
*
* @return void
*/
final public function connect()
final protected function connect()
{
$this->connection = $this->doConnect();
$this->driver->connect($this->config);
$this->connected = TRUE;
dibi::notify('connected');
}
@@ -103,9 +118,11 @@ abstract class DibiDriver extends NObject
*/
final public function disconnect()
{
$this->doDisconnect();
$this->connection = NULL;
dibi::notify('disconnected');
if ($this->connected) {
$this->driver->disconnect();
$this->connected = FALSE;
dibi::notify('disconnected');
}
}
@@ -113,7 +130,7 @@ abstract class DibiDriver extends NObject
/**
* Returns configuration variable. If no $key is passed, returns the entire array.
*
* @see DibiDriver::__construct
* @see self::__construct
* @param string
* @param mixed default value to use if key not found
* @return mixed
@@ -133,18 +150,36 @@ abstract class DibiDriver extends NObject
/**
* Apply configuration alias or default values
*
* @param array connect configuration
* @param string key
* @param string alias key
* @return void
*/
public static function alias(&$config, $key, $alias=NULL)
{
if (isset($config[$key])) return;
if ($alias !== NULL && isset($config[$alias])) {
$config[$key] = $config[$alias];
unset($config[$alias]);
} else {
$config[$key] = NULL;
}
}
/**
* Returns the connection resource
*
* @return resource
*/
final public function getConnection()
final public function getResource()
{
if ($this->connection === NULL) {
$this->connect();
}
return $this->connection;
return $this->driver->getResource();
}
@@ -160,7 +195,7 @@ abstract class DibiDriver extends NObject
{
if (!is_array($args)) $args = func_get_args();
$trans = new DibiTranslator($this);
$trans = new DibiTranslator($this->driver);
if ($trans->translate($args)) {
return $this->nativeQuery($trans->sql);
} else {
@@ -180,7 +215,7 @@ abstract class DibiDriver extends NObject
{
if (!is_array($args)) $args = func_get_args();
$trans = new DibiTranslator($this);
$trans = new DibiTranslator($this->driver);
$ok = $trans->translate($args);
dibi::dump($trans->sql);
return $ok;
@@ -197,74 +232,30 @@ abstract class DibiDriver extends NObject
*/
final public function nativeQuery($sql)
{
if (!$this->connected) $this->connect();
dibi::notify('beforeQuery', $this, $sql);
$res = $this->doQuery($sql);
$res = $this->driver->query($sql);
$res = $res ? new DibiResult(clone $this->driver) : TRUE; // backward compatibility - will be changed to NULL
dibi::notify('afterQuery', $this, $res);
// backward compatibility - will be removed!
return $res instanceof DibiResult ? $res : TRUE;
return $res;
}
/**
* Apply configuration alias or default values
*
* @param array connect configuration
* @param string key
* @param string alias key
* @return void
*/
protected static function alias(&$config, $key, $alias=NULL)
{
if (isset($config[$key])) return;
if ($alias !== NULL && isset($config[$alias])) {
$config[$key] = $config[$alias];
unset($config[$alias]);
} else {
$config[$key] = NULL;
}
}
/**
* Internal: Connects to a database
*
* @throws DibiException
* @return resource
*/
abstract protected function doConnect();
/**
* Internal: Disconnects from a database
*
* @throws DibiException
* @return void
*/
abstract protected function doDisconnect();
/**
* Internal: Executes the SQL query
*
* @param string SQL statement.
* @return DibiResult Result set object
* @throws DibiDatabaseException
*/
abstract protected function doQuery($sql);
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query
*
* @return int number of rows or FALSE on error
*/
abstract public function affectedRows();
public function affectedRows()
{
$rows = $this->driver->affectedRows();
return $rows < 0 ? FALSE : $rows;
}
@@ -273,7 +264,11 @@ abstract class DibiDriver extends NObject
*
* @return int|FALSE int on success or FALSE on failure
*/
abstract public function insertId();
public function insertId($sequence = NULL)
{
$id = $this->driver->insertId($sequence);
return $id < 1 ? FALSE : $id;
}
@@ -281,7 +276,12 @@ abstract class DibiDriver extends NObject
* Begins a transaction (if supported).
* @return void
*/
abstract public function begin();
public function begin()
{
if (!$this->connected) $this->connect();
$this->driver->begin();
dibi::notify('begin', $this);
}
@@ -289,7 +289,12 @@ abstract class DibiDriver extends NObject
* Commits statements in a transaction.
* @return void
*/
abstract public function commit();
public function commit()
{
if (!$this->connected) $this->connect();
$this->driver->commit();
dibi::notify('commit', $this);
}
@@ -297,7 +302,65 @@ abstract class DibiDriver extends NObject
* Rollback changes in a transaction.
* @return void
*/
abstract public function rollback();
public function rollback()
{
if (!$this->connected) $this->connect();
$this->driver->rollback();
dibi::notify('rollback', $this);
}
/**
* Escapes the string
*
* @param string unescaped string
* @return string escaped and optionally quoted string
*/
public function escape($value)
{
return $this->driver->format($value, dibi::FIELD_TEXT);
}
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
public function delimite($value)
{
return $this->driver->format($value, dibi::IDENTIFIER);
}
/**
* Injects LIMIT/OFFSET to the SQL query
*
* @param string &$sql The SQL query that will be modified.
* @param int $limit
* @param int $offset
* @return void
*/
public function applyLimit(&$sql, $limit, $offset)
{
$this->driver->applyLimit($sql, $limit, $offset);
}
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
public function getDibiReflection()
{
throw new BadMethodCallException(__METHOD__ . ' is not implemented');
}
@@ -312,45 +375,4 @@ abstract class DibiDriver extends NObject
/**
* Escapes the string
*
* @param string unescaped string
* @param bool quote string?
* @return string escaped and optionally quoted string
*/
abstract public function escape($value, $appendQuotes = TRUE);
/**
* Delimites identifier (table's or column's name, etc.)
*
* @param string identifier
* @return string delimited identifier
*/
abstract public function delimite($value);
/**
* Gets a information of the current database.
*
* @return DibiReflection
*/
abstract public function getDibiReflection();
/**
* Injects LIMIT/OFFSET to the SQL query
*
* @param string &$sql The SQL query that will be modified.
* @param int $limit
* @param int $offset
* @return void
*/
abstract public function applyLimit(&$sql, $limit, $offset = 0);
} // class DibiDriver
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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