1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-31 09:41:43 +02:00

Compare commits

..

1 Commits
v1.1 ... v1.0

Author SHA1 Message Date
David Grudl
da09733a3d released version 1.0 2008-10-30 13:09:47 +00:00
42 changed files with 1714 additions and 3826 deletions

View File

@@ -3,14 +3,14 @@
/**
* Nette Framework
*
* Copyright (c) 2004, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2004, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "Nette license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://nettephp.com
*
* @copyright Copyright (c) 2004, 2009 David Grudl
* @copyright Copyright (c) 2004, 2008 David Grudl
* @license http://nettephp.com/license Nette license
* @link http://nettephp.com
* @category Nette
@@ -22,10 +22,10 @@
/**
* Custom output for Nette\Debug.
* Custom output for Nette::Debug.
*
* @author David Grudl
* @copyright Copyright (c) 2004, 2009 David Grudl
* @copyright Copyright (c) 2004, 2008 David Grudl
* @package Nette
*/
interface IDebuggable

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -25,7 +26,6 @@ if (version_compare(PHP_VERSION, '5.1.0', '<')) {
throw new Exception('dibi needs PHP 5.1.0 or newer.');
}
@set_magic_quotes_runtime(FALSE); // intentionally @
@@ -56,7 +56,7 @@ if (!class_exists('FileNotFoundException', FALSE)) {
class FileNotFoundException extends IOException {}
}
if (!interface_exists(/*Nette\*/'IDebuggable', FALSE)) {
if (!interface_exists(/*Nette::*/'IDebuggable', FALSE)) {
require_once dirname(__FILE__) . '/Nette/IDebuggable.php';
}
@@ -66,10 +66,9 @@ require_once dirname(__FILE__) . '/libs/DibiObject.php';
require_once dirname(__FILE__) . '/libs/DibiException.php';
require_once dirname(__FILE__) . '/libs/DibiConnection.php';
require_once dirname(__FILE__) . '/libs/DibiResult.php';
require_once dirname(__FILE__) . '/libs/DibiResultIterator.php';
require_once dirname(__FILE__) . '/libs/DibiRow.php';
require_once dirname(__FILE__) . '/libs/DibiTranslator.php';
require_once dirname(__FILE__) . '/libs/DibiVariable.php';
require_once dirname(__FILE__) . '/libs/DibiTableX.php';
require_once dirname(__FILE__) . '/libs/DibiDataSource.php';
require_once dirname(__FILE__) . '/libs/DibiFluent.php';
require_once dirname(__FILE__) . '/libs/DibiDatabaseInfo.php';
@@ -86,52 +85,40 @@ require_once dirname(__FILE__) . '/libs/DibiProfiler.php';
* store connections info.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class dibi
{
/**#@+
* dibi data type
* dibi column type
*/
const TEXT = 's'; // as 'string'
const BINARY = 'bin';
const BOOL = 'b';
const INTEGER = 'i';
const FLOAT = 'f';
const DATE = 'd';
const DATETIME = 't';
const TIME = 't';
const IDENTIFIER = 'n';
const FIELD_TEXT = 's'; // as 'string'
const FIELD_BINARY = 'bin';
const FIELD_BOOL = 'b';
const FIELD_INTEGER = 'i';
const FIELD_FLOAT = 'f';
const FIELD_DATE = 'd';
const FIELD_DATETIME = 't';
const FIELD_TIME = 't';
/**#@-*/
/**#@+
* @deprecated column types
/**
* Identifier type
*/
const FIELD_TEXT = self::TEXT;
const FIELD_BINARY = self::BINARY;
const FIELD_BOOL = self::BOOL;
const FIELD_INTEGER = self::INTEGER;
const FIELD_FLOAT = self::FLOAT;
const FIELD_DATE = self::DATE;
const FIELD_DATETIME = self::DATETIME;
const FIELD_TIME = self::TIME;
/**#@-*/
const IDENTIFIER = 'n';
/**#@+
* dibi version
*/
const VERSION = '1.1';
const VERSION = '1.0';
const REVISION = '$WCREV$ released on $WCDATE$';
/**#@-*/
/**#@+
/**
* Configuration options
*/
const RESULT_WITH_TABLES = 'resultWithTables'; // for MySQL
const ROW_CLASS = 'rowClass';
const ASC = 'ASC', DESC = 'DESC';
/**#@-*/
/** @var DibiConnection[] Connection registry storage for DibiConnection objects */
private static $registry = array();
@@ -140,10 +127,10 @@ class dibi
private static $connection;
/** @var array Substitutions for identifiers */
public static $substs = array();
private static $substs = array();
/** @var callback Substitution fallback */
public static $substFallBack = array(__CLASS__, 'defaultSubstFallback');
private static $substFallBack;
/** @var array @see addHandler */
private static $handlers = array();
@@ -272,7 +259,7 @@ class dibi
/**
* Generates and executes SQL query - Monostate for DibiConnection::query().
* @param array|mixed one or more arguments
* @return DibiResult|int result set object (if any)
* @return DibiResult|NULL result set object (if any)
* @throws DibiException
*/
public static function query($args)
@@ -286,7 +273,7 @@ class dibi
/**
* Executes the SQL query - Monostate for DibiConnection::nativeQuery().
* @param string SQL statement.
* @return DibiResult|int result set object (if any)
* @return DibiResult|NULL result set object (if any)
*/
public static function nativeQuery($sql)
{
@@ -308,19 +295,6 @@ class dibi
/**
* Generates and returns SQL query as DibiDataSource - Monostate for DibiConnection::test().
* @param array|mixed one or more arguments
* @return DibiDataSource
*/
public static function dataSource($args)
{
$args = func_get_args();
return self::getConnection()->dataSource($args);
}
/**
* Executes SQL query and fetch result - Monostate for DibiConnection::query() & fetch().
* @param array|mixed one or more arguments
@@ -379,91 +353,63 @@ class dibi
/**
* Gets the number of affected rows.
* Monostate for DibiConnection::getAffectedRows()
* @return int number of rows
* @throws DibiException
*/
public static function getAffectedRows()
{
return self::getConnection()->getAffectedRows();
}
/**
* Gets the number of affected rows. Alias for getAffectedRows().
* Monostate for DibiConnection::affectedRows()
* @return int number of rows
* @throws DibiException
*/
public static function affectedRows()
{
return self::getConnection()->getAffectedRows();
return self::getConnection()->affectedRows();
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* Monostate for DibiConnection::getInsertId()
* @param string optional sequence name
* @return int
* @throws DibiException
*/
public static function getInsertId($sequence=NULL)
{
return self::getConnection()->getInsertId($sequence);
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
* Monostate for DibiConnection::insertId()
* @param string optional sequence name
* @return int
* @throws DibiException
*/
public static function insertId($sequence=NULL)
{
return self::getConnection()->getInsertId($sequence);
return self::getConnection()->insertId($sequence);
}
/**
* Begins a transaction - Monostate for DibiConnection::begin().
* @param string optional savepoint name
* @return void
* @throws DibiException
*/
public static function begin($savepoint = NULL)
public static function begin()
{
self::getConnection()->begin($savepoint);
self::getConnection()->begin();
}
/**
* Commits statements in a transaction - Monostate for DibiConnection::commit($savepoint = NULL).
* @param string optional savepoint name
* Commits statements in a transaction - Monostate for DibiConnection::commit().
* @return void
* @throws DibiException
*/
public static function commit($savepoint = NULL)
public static function commit()
{
self::getConnection()->commit($savepoint);
self::getConnection()->commit();
}
/**
* Rollback changes in a transaction - Monostate for DibiConnection::rollback().
* @param string optional savepoint name
* @return void
* @throws DibiException
*/
public static function rollback($savepoint = NULL)
public static function rollback()
{
self::getConnection()->rollback($savepoint);
self::getConnection()->rollback();
}
@@ -525,7 +471,7 @@ class dibi
public static function select($args)
{
$args = func_get_args();
return call_user_func_array(array(self::getConnection(), 'select'), $args);
return self::getConnection()->command()->__call('select', $args);
}
@@ -535,7 +481,7 @@ class dibi
* @param array
* @return DibiFluent
*/
public static function update($table, $args)
public static function update($table, array $args)
{
return self::getConnection()->update($table, $args);
}
@@ -547,7 +493,7 @@ class dibi
* @param array
* @return DibiFluent
*/
public static function insert($table, $args)
public static function insert($table, array $args)
{
return self::getConnection()->insert($table, $args);
}
@@ -578,17 +524,12 @@ class dibi
{
if ($time === NULL) {
$time = time(); // current time
} elseif (is_numeric($time)) {
$time = (int) $time; // timestamp
} elseif ($time instanceof DateTime) {
$time = $time->format('U');
} else {
} elseif (is_string($time)) {
$time = strtotime($time); // try convert to timestamp
} else {
$time = (int) $time;
}
return new DibiVariable($time, dibi::DATETIME);
return new DibiVariable($time, dibi::FIELD_DATETIME);
}
@@ -601,7 +542,7 @@ class dibi
public static function date($date = NULL)
{
$var = self::datetime($date);
$var->modifier = dibi::DATE;
$var->modifier = dibi::FIELD_DATE;
return $var;
}
@@ -624,6 +565,22 @@ class dibi
/**
* Sets substitution fallback handler.
* @param callback
* @return void
*/
public static function setSubstFallback($callback)
{
if (!is_callable($callback)) {
throw new InvalidArgumentException("Invalid callback.");
}
self::$substFallBack = $callback;
}
/**
* Remove substitution pair.
* @param mixed from or TRUE
@@ -641,30 +598,39 @@ class dibi
/**
* Sets substitution fallback handler.
* @param callback
* @return void
* Provides substitution.
* @param string
* @return string
*/
public static function setSubstFallback($callback)
public static function substitute($value)
{
if (!is_callable($callback)) {
$able = is_callable($callback, TRUE, $textual);
throw new InvalidArgumentException("Handler '$textual' is not " . ($able ? 'callable.' : 'valid PHP callback.'));
}
if (strpos($value, ':') === FALSE) {
return $value;
self::$substFallBack = $callback;
} else {
return preg_replace_callback('#:(.*):#U', array('dibi', 'subCb'), $value);
}
}
/**
* Default substitution fallback handler.
* @param string
* @return mixed
* Substitution callback.
* @param array
* @return string
*/
public static function defaultSubstFallback($expr)
private static function subCb($m)
{
throw new InvalidStateException("Missing substitution for '$expr' expression.");
$m = $m[1];
if (isset(self::$substs[$m])) {
return self::$substs[$m];
} elseif (self::$substFallBack) {
return self::$substs[$m] = call_user_func(self::$substFallBack, $m);
} else {
return $m;
}
}
@@ -692,7 +658,7 @@ class dibi
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|TRUE|FALSE';
// insert new lines
$sql = " $sql ";
$sql = ' ' . $sql;
$sql = preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i", "\n\$1", $sql);
// reduce spaces

View File

@@ -1,834 +0,0 @@
<?php
/**
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
*/
/**
* The dibi driver for Firebird/InterBase database.
*
* Connection options:
* - 'database' - the path to database file (server:/path/database.fdb)
* - 'username' (or 'user')
* - 'password' (or 'pass')
* - 'charset' - character encoding to set
* - 'buffers' - buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.
* - 'lazy' - if TRUE, connection will be established only when required
* - 'resource' - connection resource (optional)
*
* @author Tomáš Kraina, Roman Sklenář
* @copyright Copyright (c) 2009
* @package dibi
*/
class DibiFirebirdDriver extends DibiObject implements IDibiDriver
{
const ERROR_EXCEPTION_THROWN = -836;
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
/** @var resource Resultset resource */
private $transaction;
/** @var bool */
private $inTransaction = FALSE;
/**
* @throws DibiException
*/
public function __construct()
{
if (!extension_loaded('interbase')) {
throw new DibiDriverException("PHP extension 'interbase' is not loaded.");
}
}
/**
* Connects to a database.
* @return void
* @throws DibiException
*/
public function connect(array &$config)
{
DibiConnection::alias($config, 'database', 'db');
if (isset($config['resource'])) {
$this->connection = $config['resource'];
} else {
// default values
if (!isset($config['username'])) $config['username'] = ini_get('ibase.default_password');
if (!isset($config['password'])) $config['password'] = ini_get('ibase.default_user');
if (!isset($config['database'])) $config['database'] = ini_get('ibase.default_db');
if (!isset($config['charset'])) $config['charset'] = ini_get('ibase.default_charset');
if (!isset($config['buffers'])) $config['buffers'] = 0;
DibiDriverException::tryError();
if (empty($config['persistent'])) {
$this->connection = ibase_connect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
} else {
$this->connection = ibase_pconnect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
}
if (DibiDriverException::catchError($msg)) {
throw new DibiDriverException($msg, ibase_errcode());
}
if (!is_resource($this->connection)) {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode());
}
}
}
/**
* Disconnects from a database.
* @return void
*/
public function disconnect()
{
ibase_close($this->connection);
}
/**
* Executes the SQL query.
* @param string SQL statement.
* @return IDibiDriver|NULL
* @throws DibiDriverException|DibiException
*/
public function query($sql)
{
DibiDriverException::tryError();
$resource = $this->inTransaction ? $this->transaction : $this->connection;
$this->resultSet = ibase_query($resource, $sql);
if (DibiDriverException::catchError($msg)) {
if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) {
preg_match('/exception (\d+) (\w+) (.*)/i', ibase_errmsg(), $match);
throw new DibiProcedureException($match[3], $match[1], $match[2], dibi::$sql);
} else {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode(), dibi::$sql);
}
}
if ($this->resultSet === FALSE) {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode(), $sql);
}
return is_resource($this->resultSet) ? clone $this : NULL;
}
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
{
return ibase_affected_rows($this->connection);
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @param string generator name
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
{
return ibase_gen_id($sequence, 0, $this->connection);
//throw new NotSupportedException('Firebird/InterBase does not support autoincrementing.');
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
{
if ($savepoint !== NULL) {
throw new DibiDriverException('Savepoints are not supported in Firebird/Interbase.');
}
$this->transaction = ibase_trans($this->resource);
$this->inTransaction = TRUE;
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
{
if ($savepoint !== NULL) {
throw new DibiDriverException('Savepoints are not supported in Firebird/Interbase.');
}
if (!ibase_commit($this->transaction)) {
DibiDriverException('Unable to handle operation - failure when commiting transaction.');
}
$this->inTransaction = FALSE;
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
{
if ($savepoint !== NULL) {
throw new DibiDriverException('Savepoints are not supported in Firebird/Interbase.');
}
if (!ibase_rollback($this->transaction)) {
DibiDriverException('Unable to handle operation - failure when rolbacking transaction.');
}
$this->inTransaction = FALSE;
}
/**
* Returns the connection resource.
* @return resource
*/
public function getResource()
{
return $this->connection;
}
/********************* SQL ********************/
/**
* Encodes data for use in a SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::BINARY:
return "'" . str_replace("'", "''", $value) . "'";
case dibi::IDENTIFIER:
return $value;
case dibi::BOOL:
return $value ? 1 : 0;
case dibi::DATE:
return date("'Y-m-d'", $value);
case dibi::DATETIME:
return date("'Y-m-d H:i:s'", $value);
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
/**
* 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)
{
if ($limit < 0 && $offset < 1) return;
// see http://scott.yang.id.au/2004/01/limit-in-select-statements-in-firebird/
$sql = 'SELECT FIRST ' . (int) $limit . ($offset > 0 ? ' SKIP ' . (int) $offset : '') . ' * FROM (' . $sql . ')';
}
/********************* result set ********************/
/**
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
{
return ibase_num_fields($this->resultSet);
}
/**
* Fetches the row at current position and moves the internal cursor to the next position.
* @param bool TRUE for associative array, FALSE for numeric
* @return array array on success, nonarray if no next record
* @internal
*/
public function fetch($assoc)
{
DibiDriverException::tryError();
$result = $assoc ? ibase_fetch_assoc($this->resultSet) : ibase_fetch_row($this->resultSet); // intentionally @
if (DibiDriverException::catchError($msg)) {
if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) {
preg_match('/exception (\d+) (\w+) (.*)/i', ibase_errmsg(), $match);
throw new DibiProcedureException($match[3], $match[1], $match[2], dibi::$sql);
} else {
throw new DibiDriverException($msg, ibase_errcode(), dibi::$sql);
}
}
return $result;
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
*/
public function seek($row)
{
throw new DibiDriverException("Firebird/Interbase do not support seek in result set.");
}
/**
* Frees the resources allocated for this result set.
* @return void
*/
public function free()
{
ibase_free_result($this->resultSet);
$this->resultSet = NULL;
}
/**
* Returns the result set resource.
* @return mysqli_result
*/
public function getResultResource()
{
return $this->resultSet;
}
/**
* Returns metadata for all columns in a result set.
* @return array
*/
public function getColumnsMeta()
{
throw new NotImplementedException;
}
/********************* reflection ********************/
/**
* Returns list of tables.
* @return array
*/
public function getTables()
{
$this->query("
SELECT TRIM(RDB\$RELATION_NAME),
CASE RDB\$VIEW_BLR WHEN NULL THEN 'TRUE' ELSE 'FALSE' END
FROM RDB\$RELATIONS
WHERE RDB\$SYSTEM_FLAG = 0;"
);
$res = array();
while ($row = $this->fetch(FALSE)) {
$res[] = array(
'name' => $row[0],
'view' => $row[1] === 'TRUE',
);
}
$this->free();
return $res;
}
/**
* Returns metadata for all columns in a table.
* @param string
* @return array
*/
public function getColumns($table)
{
$table = strtoupper($table);
$this->query("
SELECT TRIM(r.RDB\$FIELD_NAME) AS FIELD_NAME,
CASE f.RDB\$FIELD_TYPE
WHEN 261 THEN 'BLOB'
WHEN 14 THEN 'CHAR'
WHEN 40 THEN 'CSTRING'
WHEN 11 THEN 'D_FLOAT'
WHEN 27 THEN 'DOUBLE'
WHEN 10 THEN 'FLOAT'
WHEN 16 THEN 'INT64'
WHEN 8 THEN 'INTEGER'
WHEN 9 THEN 'QUAD'
WHEN 7 THEN 'SMALLINT'
WHEN 12 THEN 'DATE'
WHEN 13 THEN 'TIME'
WHEN 35 THEN 'TIMESTAMP'
WHEN 37 THEN 'VARCHAR'
ELSE 'UNKNOWN'
END AS FIELD_TYPE,
f.RDB\$FIELD_LENGTH AS FIELD_LENGTH,
r.RDB\$DEFAULT_VALUE AS DEFAULT_VALUE,
CASE r.RDB\$NULL_FLAG
WHEN 1 THEN 'FALSE' ELSE 'TRUE'
END AS NULLABLE
FROM RDB\$RELATION_FIELDS r
LEFT JOIN RDB\$FIELDS f ON r.RDB\$FIELD_SOURCE = f.RDB\$FIELD_NAME
WHERE r.RDB\$RELATION_NAME = '$table'
ORDER BY r.RDB\$FIELD_POSITION;"
);
$res = array();
while ($row = $this->fetch(TRUE)) {
$key = $row['FIELD_NAME'];
$res[$key] = array(
'name' => $key,
'table' => $table,
'nativetype' => trim($row['FIELD_TYPE']),
'size' => $row['FIELD_LENGTH'],
'nullable' => $row['NULLABLE'] === 'TRUE',
'default' => $row['DEFAULT_VALUE'],
'autoincrement' => FALSE,
);
}
$this->free();
return $res;
}
/**
* Returns metadata for all indexes in a table (the constraints are included).
* @param string
* @return array
*/
public function getIndexes($table)
{
$table = strtoupper($table);
$this->query("
SELECT TRIM(s.RDB\$INDEX_NAME) AS INDEX_NAME,
TRIM(s.RDB\$FIELD_NAME) AS FIELD_NAME,
i.RDB\$UNIQUE_FLAG AS UNIQUE_FLAG,
i.RDB\$FOREIGN_KEY AS FOREIGN_KEY,
TRIM(r.RDB\$CONSTRAINT_TYPE) AS CONSTRAINT_TYPE,
s.RDB\$FIELD_POSITION AS FIELD_POSITION
FROM RDB\$INDEX_SEGMENTS s
LEFT JOIN RDB\$INDICES i ON i.RDB\$INDEX_NAME = s.RDB\$INDEX_NAME
LEFT JOIN RDB\$RELATION_CONSTRAINTS r ON r.RDB\$INDEX_NAME = s.RDB\$INDEX_NAME
WHERE UPPER(i.RDB\$RELATION_NAME) = '$table'
ORDER BY s.RDB\$FIELD_POSITION"
);
$res = array();
while ($row = $this->fetch(TRUE)) {
$key = $row['INDEX_NAME'];
$res[$key]['name'] = $key;
$res[$key]['unique'] = $row['UNIQUE_FLAG'] === 1;
$res[$key]['primary'] = $row['CONSTRAINT_TYPE'] === 'PRIMARY KEY';
$res[$key]['table'] = $table;
$res[$key]['columns'][$row['FIELD_POSITION']] = $row['FIELD_NAME'];
}
$this->free();
return $res;
}
/**
* Returns metadata for all foreign keys in a table.
* @param string
* @return array
*/
public function getForeignKeys($table)
{
$table = strtoupper($table);
$this->query("
SELECT TRIM(s.RDB\$INDEX_NAME) AS INDEX_NAME,
TRIM(s.RDB\$FIELD_NAME) AS FIELD_NAME,
FROM RDB\$INDEX_SEGMENTS s
LEFT JOIN RDB\$RELATION_CONSTRAINTS r ON r.RDB\$INDEX_NAME = s.RDB\$INDEX_NAME
WHERE UPPER(i.RDB\$RELATION_NAME) = '$table'
AND r.RDB\$CONSTRAINT_TYPE = 'FOREIGN KEY'
ORDER BY s.RDB\$FIELD_POSITION"
);
$res = array();
while ($row = $this->fetch(TRUE)) {
$key = $row['INDEX_NAME'];
$res[$key] = array(
'name' => $key,
'column' => $row['FIELD_NAME'],
'table' => $table,
);
}
$this->free();
return $res;
}
/**
* Returns list of indices in given table (the constraints are not listed).
* @param string
* @return array
*/
public function getIndices($table)
{
$this->query("
SELECT TRIM(RDB\$INDEX_NAME)
FROM RDB\$INDICES
WHERE RDB\$RELATION_NAME = UPPER('$table')
AND RDB\$UNIQUE_FLAG IS NULL
AND RDB\$FOREIGN_KEY IS NULL;"
);
$res = array();
while ($row = $this->fetch(FALSE)) {
$res[] = $row[0];
}
$this->free();
return $res;
}
/**
* Returns list of constraints in given table.
* @param string
* @return array
*/
public function getConstraints($table)
{
$this->query("
SELECT TRIM(RDB\$INDEX_NAME)
FROM RDB\$INDICES
WHERE RDB\$RELATION_NAME = UPPER('$table')
AND (
RDB\$UNIQUE_FLAG IS NOT NULL
OR RDB\$FOREIGN_KEY IS NOT NULL
);"
);
$res = array();
while ($row = $this->fetch(FALSE)) {
$res[] = $row[0];
}
$this->free();
return $res;
}
/**
* Returns metadata for all triggers in a table or database.
* (Only if user has permissions on ALTER TABLE, INSERT/UPDATE/DELETE record in table)
* @param string
* @param string
* @return array
*/
public function getTriggersMeta($table = NULL)
{
$this->query("
SELECT TRIM(RDB\$TRIGGER_NAME) AS TRIGGER_NAME,
TRIM(RDB\$RELATION_NAME) AS TABLE_NAME,
CASE RDB\$TRIGGER_TYPE
WHEN 1 THEN 'BEFORE'
WHEN 2 THEN 'AFTER'
WHEN 3 THEN 'BEFORE'
WHEN 4 THEN 'AFTER'
WHEN 5 THEN 'BEFORE'
WHEN 6 THEN 'AFTER'
END AS TRIGGER_TYPE,
CASE RDB\$TRIGGER_TYPE
WHEN 1 THEN 'INSERT'
WHEN 2 THEN 'INSERT'
WHEN 3 THEN 'UPDATE'
WHEN 4 THEN 'UPDATE'
WHEN 5 THEN 'DELETE'
WHEN 6 THEN 'DELETE'
END AS TRIGGER_EVENT,
CASE RDB\$TRIGGER_INACTIVE
WHEN 1 THEN 'FALSE' ELSE 'TRUE'
END AS TRIGGER_ENABLED
FROM RDB\$TRIGGERS
WHERE RDB\$SYSTEM_FLAG = 0"
. ($table === NULL ? ";" : " AND RDB\$RELATION_NAME = UPPER('$table');")
);
$res = array();
while ($row = $this->fetch(TRUE)) {
$res[$row['TRIGGER_NAME']] = array(
'name' => $row['TRIGGER_NAME'],
'table' => $row['TABLE_NAME'],
'type' => trim($row['TRIGGER_TYPE']),
'event' => trim($row['TRIGGER_EVENT']),
'enabled' => trim($row['TRIGGER_ENABLED']) === 'TRUE',
);
}
$this->free();
return $res;
}
/**
* Returns list of triggers for given table.
* (Only if user has permissions on ALTER TABLE, INSERT/UPDATE/DELETE record in table)
* @param string
* @return array
*/
public function getTriggers($table = NULL)
{
$q = "SELECT TRIM(RDB\$TRIGGER_NAME)
FROM RDB\$TRIGGERS
WHERE RDB\$SYSTEM_FLAG = 0";
$q .= $table === NULL ? ";" : " AND RDB\$RELATION_NAME = UPPER('$table')";
$this->query($q);
$res = array();
while ($row = $this->fetch(FALSE)) {
$res[] = $row[0];
}
$this->free();
return $res;
}
/**
* Returns metadata from stored procedures and their input and output parameters.
* @param string
* @return array
*/
public function getProceduresMeta()
{
$this->query("
SELECT
TRIM(p.RDB\$PARAMETER_NAME) AS PARAMETER_NAME,
TRIM(p.RDB\$PROCEDURE_NAME) AS PROCEDURE_NAME,
CASE p.RDB\$PARAMETER_TYPE
WHEN 0 THEN 'INPUT'
WHEN 1 THEN 'OUTPUT'
ELSE 'UNKNOWN'
END AS PARAMETER_TYPE,
CASE f.RDB\$FIELD_TYPE
WHEN 261 THEN 'BLOB'
WHEN 14 THEN 'CHAR'
WHEN 40 THEN 'CSTRING'
WHEN 11 THEN 'D_FLOAT'
WHEN 27 THEN 'DOUBLE'
WHEN 10 THEN 'FLOAT'
WHEN 16 THEN 'INT64'
WHEN 8 THEN 'INTEGER'
WHEN 9 THEN 'QUAD'
WHEN 7 THEN 'SMALLINT'
WHEN 12 THEN 'DATE'
WHEN 13 THEN 'TIME'
WHEN 35 THEN 'TIMESTAMP'
WHEN 37 THEN 'VARCHAR'
ELSE 'UNKNOWN'
END AS FIELD_TYPE,
f.RDB\$FIELD_LENGTH AS FIELD_LENGTH,
p.RDB\$PARAMETER_NUMBER AS PARAMETER_NUMBER
FROM RDB\$PROCEDURE_PARAMETERS p
LEFT JOIN RDB\$FIELDS f ON f.RDB\$FIELD_NAME = p.RDB\$FIELD_SOURCE
ORDER BY p.RDB\$PARAMETER_TYPE, p.RDB\$PARAMETER_NUMBER;"
);
$res = array();
while ($row = $this->fetch(TRUE)) {
$key = $row['PROCEDURE_NAME'];
$io = trim($row['PARAMETER_TYPE']);
$num = $row['PARAMETER_NUMBER'];
$res[$key]['name'] = $row['PROCEDURE_NAME'];
$res[$key]['params'][$io][$num]['name'] = $row['PARAMETER_NAME'];
$res[$key]['params'][$io][$num]['type'] = trim($row['FIELD_TYPE']);
$res[$key]['params'][$io][$num]['size'] = $row['FIELD_LENGTH'];
}
$this->free();
return $res;
}
/**
* Returns list of stored procedures.
* @return array
*/
public function getProcedures()
{
$this->query("
SELECT TRIM(RDB\$PROCEDURE_NAME)
FROM RDB\$PROCEDURES;"
);
$res = array();
while ($row = $this->fetch(FALSE)) {
$res[] = $row[0];
}
$this->free();
return $res;
}
/**
* Returns list of generators.
* @return array
*/
public function getGenerators()
{
$this->query("
SELECT TRIM(RDB\$GENERATOR_NAME)
FROM RDB\$GENERATORS
WHERE RDB\$SYSTEM_FLAG = 0;"
);
$res = array();
while ($row = $this->fetch(FALSE)) {
$res[] = $row[0];
}
$this->free();
return $res;
}
/**
* Returns list of user defined functions (UDF).
* @return array
*/
public function getFunctions()
{
$this->query("
SELECT TRIM(RDB\$FUNCTION_NAME)
FROM RDB\$FUNCTIONS
WHERE RDB\$SYSTEM_FLAG = 0;"
);
$res = array();
while ($row = $this->fetch(FALSE)) {
$res[] = $row[0];
}
$this->free();
return $res;
}
}
/**
* Database procedure exception.
*
* @author Roman Sklenář
* @copyright Copyright (c) 2009
* @package dibi
*/
class DibiProcedureException extends DibiException
{
/** @var string */
protected $severity;
/**
* Construct the exception.
* @param string Message describing the exception
* @param int Some code
* @param string SQL command
*/
public function __construct($message = NULL, $code = 0, $severity = NULL, $sql = NULL)
{
parent::__construct($message, (int) $code, $sql);
$this->severity = $severity;
}
/**
* Gets the exception severity.
* @return string
*/
public function getSeverity()
{
$this->severity;
}
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -28,17 +29,18 @@
* - 'persistent' - try to find a persistent link?
* - 'database' - the database name to select
* - 'lazy' - if TRUE, connection will be established only when required
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiMsSqlDriver extends DibiObject implements IDibiDriver
{
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
@@ -63,9 +65,11 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
*/
public function connect(array &$config)
{
if (isset($config['resource'])) {
$this->connection = $config['resource'];
} elseif (empty($config['persistent'])) {
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'host', 'hostname');
if (empty($config['persistent'])) {
$this->connection = @mssql_connect($config['host'], $config['username'], $config['password'], TRUE); // intentionally @
} else {
$this->connection = @mssql_pconnect($config['host'], $config['username'], $config['password']); // intentionally @
@@ -116,7 +120,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
return mssql_rows_affected($this->connection);
}
@@ -127,25 +131,19 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
$res = mssql_query('SELECT @@IDENTITY', $this->connection);
if (is_resource($res)) {
$row = mssql_fetch_row($res);
return $row[0];
}
return FALSE;
throw new NotSupportedException('MS SQL does not support autoincrementing.');
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
$this->query('BEGIN TRANSACTION');
}
@@ -154,11 +152,10 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
$this->query('COMMIT');
}
@@ -167,11 +164,10 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
$this->query('ROLLBACK');
}
@@ -194,17 +190,17 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::BINARY:
case dibi::FIELD_TEXT:
case dibi::FIELD_BINARY:
return "'" . str_replace("'", "''", $value) . "'";
case dibi::IDENTIFIER:
@@ -212,13 +208,13 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
$value = str_replace(array('[', ']'), array('[[', ']]'), $value);
return '[' . str_replace('.', '].[', $value) . ']';
case dibi::BOOL:
return $value ? 1 : 0;
case dibi::FIELD_BOOL:
return $value ? -1 : 0;
case dibi::DATE:
case dibi::FIELD_DATE:
return date("'Y-m-d'", $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date("'Y-m-d H:i:s'", $value);
default:
@@ -231,15 +227,12 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -254,7 +247,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
*/
public function applyLimit(&$sql, $limit, $offset)
{
// offset support is missing
// offset suppot is missing...
if ($limit >= 0) {
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ')';
}
@@ -274,7 +267,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
return mssql_num_rows($this->resultSet);
}
@@ -298,6 +291,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
*/
public function seek($row)
{

View File

@@ -1,410 +0,0 @@
<?php
/**
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
*/
/**
* The dibi driver for MS SQL Driver 2005 database.
*
* Connection options:
* - 'host' - the MS SQL server host name. It can also include a port number (hostname:port)
* - 'options' - connection info array {@link http://msdn.microsoft.com/en-us/library/cc296161(SQL.90).aspx}
* - 'lazy' - if TRUE, connection will be established only when required
* - 'charset' - character encoding to set (default is UTF-8)
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @package dibi
*/
class DibiMsSql2005Driver extends DibiObject implements IDibiDriver
{
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
/** @var string character encoding */
private $charset;
/**
* @throws DibiException
*/
public function __construct()
{
if (!extension_loaded('sqlsrv')) {
throw new DibiDriverException("PHP extension 'sqlsrv' is not loaded.");
}
}
/**
* Connects to a database.
* @return void
* @throws DibiException
*/
public function connect(array &$config)
{
if (isset($config['resource'])) {
$this->connection = $config['resource'];
} elseif (isset($config['options'])) {
$this->connection = sqlsrv_connect($config['host'], $config['options']);
} else {
$this->connection = sqlsrv_connect($config['host']);
}
if (!is_resource($this->connection)) {
$info = sqlsrv_errors();
throw new DibiDriverException($info[0]['message'], $info[0]['code']);
}
$this->charset = empty($config['charset']) ? 'UTF-8' : $config['charset'];
}
/**
* Disconnects from a database.
* @return void
*/
public function disconnect()
{
sqlsrv_close($this->connection);
}
/**
* Executes the SQL query.
* @param string SQL statement.
* @return IDibiDriver|NULL
* @throws DibiDriverException
*/
public function query($sql)
{
$sql = iconv($this->charset, 'UTF-16LE', $sql);
$this->resultSet = sqlsrv_query($this->connection, $sql);
if ($this->resultSet === FALSE) {
$info = sqlsrv_errors();
throw new DibiDriverException($info[0]['message'], $info[0]['code'], $sql);
}
return is_resource($this->resultSet) ? clone $this : NULL;
}
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
{
return sqlsrv_rows_affected($this->resultSet);
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
{
$res = sqlsrv_query($this->connection, 'SELECT @@IDENTITY');
if (is_resource($res)) {
$row = sqlsrv_fetch_array($res, SQLSRV_FETCH_NUMERIC);
return $row[0];
}
return FALSE;
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
{
$this->query('BEGIN TRANSACTION');
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
{
$this->query('COMMIT');
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
{
$this->query('ROLLBACK');
}
/**
* Returns the connection resource.
* @return mixed
*/
public function getResource()
{
return $this->connection;
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::BINARY:
return "'" . str_replace("'", "''", $value) . "'";
case dibi::IDENTIFIER:
// @see http://msdn.microsoft.com/en-us/library/ms176027.aspx
$value = str_replace(array('[', ']'), array('[[', ']]'), $value);
return '[' . str_replace('.', '].[', $value) . ']';
case dibi::BOOL:
return $value ? 1 : 0;
case dibi::DATE:
return date("'Y-m-d'", $value);
case dibi::DATETIME:
return date("'Y-m-d H:i:s'", $value);
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
/**
* 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)
{
// offset support is missing
if ($limit >= 0) {
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ')';
}
if ($offset) {
throw new NotImplementedException('Offset is not implemented.');
}
}
/********************* result set ****************d*g**/
/**
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
{
throw new NotSupportedException('Row count is not available for unbuffered queries.');
}
/**
* Fetches the row at current position and moves the internal cursor to the next position.
* @param bool TRUE for associative array, FALSE for numeric
* @return array array on success, nonarray if no next record
* @internal
*/
public function fetch($assoc)
{
$row = sqlsrv_fetch_array($this->resultSet, $assoc ? SQLSRV_FETCH_ASSOC : SQLSRV_FETCH_NUMERIC);
foreach ($row as $k => $v) {
if (is_string($v)) {
$row[$k] = iconv('UTF-16LE', $this->charset, $v);
}
}
return $row;
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
*/
public function seek($row)
{
throw new NotSupportedException('Cannot seek an unbuffered result set.');
}
/**
* Frees the resources allocated for this result set.
* @return void
*/
public function free()
{
sqlsrv_free_stmt($this->resultSet);
$this->resultSet = NULL;
}
/**
* Returns metadata for all columns in a result set.
* @return array
*/
public function getColumnsMeta()
{
$count = sqlsrv_num_fields($this->resultSet);
$res = array();
for ($i = 0; $i < $count; $i++) {
$row = (array) sqlsrv_field_metadata($this->resultSet, $i);
$res[] = array(
'name' => $row['Name'],
'fullname' => $row['Name'],
'nativetype' => $row['Type'],
);
}
return $res;
}
/**
* Returns the result set resource.
* @return mixed
*/
public function getResultResource()
{
return $this->resultSet;
}
/********************* reflection ****************d*g**/
/**
* Returns list of tables.
* @return array
*/
public function getTables()
{
throw new NotImplementedException;
}
/**
* Returns metadata for all columns in a table.
* @param string
* @return array
*/
public function getColumns($table)
{
throw new NotImplementedException;
}
/**
* Returns metadata for all indexes in a table.
* @param string
* @return array
*/
public function getIndexes($table)
{
throw new NotImplementedException;
}
/**
* Returns metadata for all foreign keys in a table.
* @param string
* @return array
*/
public function getForeignKeys($table)
{
throw new NotImplementedException;
}
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -34,24 +35,22 @@
* - 'options' - driver specific constants (MYSQL_*)
* - 'sqlmode' - see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
* - 'lazy' - if TRUE, connection will be established only when required
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiMySqlDriver extends DibiObject implements IDibiDriver
{
const ERROR_ACCESS_DENIED = 1045;
const ERROR_DUPLICATE_ENTRY = 1062;
const ERROR_DATA_TRUNCATED = 1265;
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
/** @var bool Is buffered (seekable and countable)? */
private $buffered;
@@ -76,37 +75,35 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver
*/
public function connect(array &$config)
{
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'host', 'hostname');
DibiConnection::alias($config, 'options');
if (isset($config['resource'])) {
$this->connection = $config['resource'];
// default values
if (!isset($config['username'])) $config['username'] = ini_get('mysql.default_user');
if (!isset($config['password'])) $config['password'] = ini_get('mysql.default_password');
if (!isset($config['host'])) {
$host = ini_get('mysql.default_host');
if ($host) {
$config['host'] = $host;
$config['port'] = ini_get('mysql.default_port');
} else {
if (!isset($config['socket'])) $config['socket'] = ini_get('mysql.default_socket');
$config['host'] = NULL;
}
}
if (empty($config['socket'])) {
$host = $config['host'] . (empty($config['port']) ? '' : ':' . $config['port']);
} else {
// default values
if (!isset($config['username'])) $config['username'] = ini_get('mysql.default_user');
if (!isset($config['password'])) $config['password'] = ini_get('mysql.default_password');
if (!isset($config['host'])) {
$host = ini_get('mysql.default_host');
if ($host) {
$config['host'] = $host;
$config['port'] = ini_get('mysql.default_port');
} else {
if (!isset($config['socket'])) $config['socket'] = ini_get('mysql.default_socket');
$config['host'] = NULL;
}
}
$host = ':' . $config['socket'];
}
if (empty($config['socket'])) {
$host = $config['host'] . (empty($config['port']) ? '' : ':' . $config['port']);
} else {
$host = ':' . $config['socket'];
}
if (empty($config['persistent'])) {
$this->connection = @mysql_connect($host, $config['username'], $config['password'], TRUE, $config['options']); // intentionally @
} else {
$this->connection = @mysql_pconnect($host, $config['username'], $config['password'], $config['options']); // intentionally @
}
if (empty($config['persistent'])) {
$this->connection = @mysql_connect($host, $config['username'], $config['password'], TRUE, $config['options']); // intentionally @
} else {
$this->connection = @mysql_pconnect($host, $config['username'], $config['password'], $config['options']); // intentionally @
}
if (!is_resource($this->connection)) {
@@ -178,27 +175,11 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver
/**
* Retrieves information about the most recently executed query.
* @return array
*/
public function getInfo()
{
$res = array();
preg_match_all('#(.+?): +(\d+) *#', mysql_info($this->connection), $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$res[$m[1]] = (int) $m[2];
}
return $res;
}
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
return mysql_affected_rows($this->connection);
}
@@ -209,7 +190,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
return mysql_insert_id($this->connection);
}
@@ -218,39 +199,36 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
$this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
$this->query('START TRANSACTION');
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
$this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
$this->query('COMMIT');
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
$this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
$this->query('ROLLBACK');
}
@@ -271,33 +249,31 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::FIELD_TEXT:
case dibi::FIELD_BINARY:
return "'" . mysql_real_escape_string($value, $this->connection) . "'";
case dibi::BINARY:
return "_binary'" . mysql_real_escape_string($value, $this->connection) . "'";
case dibi::IDENTIFIER:
// @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
$value = str_replace('`', '``', $value);
return '`' . str_replace('.', '`.`', $value) . '`';
case dibi::BOOL:
case dibi::FIELD_BOOL:
return $value ? 1 : 0;
case dibi::DATE:
case dibi::FIELD_DATE:
return date("'Y-m-d'", $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date("'Y-m-d H:i:s'", $value);
default:
@@ -310,15 +286,12 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -350,7 +323,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
if (!$this->buffered) {
throw new DibiDriverException('Row count is not available for unbuffered queries.');

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -34,24 +35,22 @@
* - 'options' - driver specific constants (MYSQLI_*)
* - 'sqlmode' - see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
* - 'lazy' - if TRUE, connection will be established only when required
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiMySqliDriver extends DibiObject implements IDibiDriver
{
const ERROR_ACCESS_DENIED = 1045;
const ERROR_DUPLICATE_ENTRY = 1062;
const ERROR_DATA_TRUNCATED = 1265;
/** @var mysqli Connection resource */
private $connection;
/** @var mysqli_result Resultset resource */
private $resultSet;
/** @var bool Is buffered (seekable and countable)? */
private $buffered;
@@ -76,35 +75,33 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
*/
public function connect(array &$config)
{
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'host', 'hostname');
DibiConnection::alias($config, 'options');
DibiConnection::alias($config, 'database');
if (isset($config['resource'])) {
$this->connection = $config['resource'];
} else {
// default values
if (!isset($config['username'])) $config['username'] = ini_get('mysqli.default_user');
if (!isset($config['password'])) $config['password'] = ini_get('mysqli.default_pw');
if (!isset($config['socket'])) $config['socket'] = ini_get('mysqli.default_socket');
if (!isset($config['port'])) $config['port'] = NULL;
if (!isset($config['host'])) {
$host = ini_get('mysqli.default_host');
if ($host) {
$config['host'] = $host;
$config['port'] = ini_get('mysqli.default_port');
} else {
$config['host'] = NULL;
$config['port'] = NULL;
}
// default values
if (!isset($config['username'])) $config['username'] = ini_get('mysqli.default_user');
if (!isset($config['password'])) $config['password'] = ini_get('mysqli.default_pw');
if (!isset($config['socket'])) $config['socket'] = ini_get('mysqli.default_socket');
if (!isset($config['port'])) $config['port'] = NULL;
if (!isset($config['host'])) {
$host = ini_get('mysqli.default_host');
if ($host) {
$config['host'] = $host;
$config['port'] = ini_get('mysqli.default_port');
} else {
$config['host'] = NULL;
$config['port'] = NULL;
}
}
$this->connection = mysqli_init();
@mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']); // intentionally @
$this->connection = mysqli_init();
@mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']); // intentionally @
if ($errno = mysqli_connect_errno()) {
throw new DibiDriverException(mysqli_connect_error(), $errno);
}
if ($errno = mysqli_connect_errno()) {
throw new DibiDriverException(mysqli_connect_error(), $errno);
}
if (isset($config['charset'])) {
@@ -162,27 +159,11 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
/**
* Retrieves information about the most recently executed query.
* @return array
*/
public function getInfo()
{
$res = array();
preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$res[$m[1]] = (int) $m[2];
}
return $res;
}
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
return mysqli_affected_rows($this->connection);
}
@@ -193,7 +174,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
return mysqli_insert_id($this->connection);
}
@@ -202,39 +183,36 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
$this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
$this->query('START TRANSACTION');
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
$this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
$this->query('COMMIT');
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
$this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
$this->query('ROLLBACK');
}
@@ -255,32 +233,30 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::FIELD_TEXT:
case dibi::FIELD_BINARY:
return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
case dibi::BINARY:
return "_binary'" . mysqli_real_escape_string($this->connection, $value) . "'";
case dibi::IDENTIFIER:
$value = str_replace('`', '``', $value);
return '`' . str_replace('.', '`.`', $value) . '`';
case dibi::BOOL:
case dibi::FIELD_BOOL:
return $value ? 1 : 0;
case dibi::DATE:
case dibi::FIELD_DATE:
return date("'Y-m-d'", $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date("'Y-m-d H:i:s'", $value);
default:
@@ -293,15 +269,12 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -333,7 +306,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
if (!$this->buffered) {
throw new DibiDriverException('Row count is not available for unbuffered queries.');
@@ -464,7 +437,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
*/
public function getColumns($table)
{
/*$table = $this->escape($table, dibi::TEXT);
/*$table = $this->escape($table, dibi::FIELD_TEXT);
$this->query("
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
@@ -497,7 +470,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver
*/
public function getIndexes($table)
{
/*$table = $this->escape($table, dibi::TEXT);
/*$table = $this->escape($table, dibi::FIELD_TEXT);
$this->query("
SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -27,20 +28,22 @@
* - 'password' (or 'pass')
* - 'persistent' - try to find a persistent link?
* - 'lazy' - if TRUE, connection will be established only when required
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiOdbcDriver extends DibiObject implements IDibiDriver
{
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
/** @var int Cursor */
private $row = 0;
@@ -65,19 +68,18 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
*/
public function connect(array &$config)
{
if (isset($config['resource'])) {
$this->connection = $config['resource'];
} else {
// 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');
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
if (empty($config['persistent'])) {
$this->connection = @odbc_connect($config['dsn'], $config['username'], $config['password']); // intentionally @
} else {
$this->connection = @odbc_pconnect($config['dsn'], $config['username'], $config['password']); // intentionally @
}
// 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 (empty($config['persistent'])) {
$this->connection = @odbc_connect($config['dsn'], $config['username'], $config['password']); // intentionally @
} else {
$this->connection = @odbc_pconnect($config['dsn'], $config['username'], $config['password']); // intentionally @
}
if (!is_resource($this->connection)) {
@@ -121,7 +123,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
return odbc_num_rows($this->resultSet);
}
@@ -132,7 +134,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
throw new NotSupportedException('ODBC does not support autoincrementing.');
}
@@ -141,11 +143,10 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
if (!odbc_autocommit($this->connection, FALSE)) {
throw new DibiDriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection));
@@ -156,11 +157,10 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
if (!odbc_commit($this->connection)) {
throw new DibiDriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection));
@@ -172,11 +172,10 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
if (!odbc_rollback($this->connection)) {
throw new DibiDriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection));
@@ -202,30 +201,30 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::BINARY:
case dibi::FIELD_TEXT:
case dibi::FIELD_BINARY:
return "'" . str_replace("'", "''", $value) . "'";
case dibi::IDENTIFIER:
$value = str_replace(array('[', ']'), array('[[', ']]'), $value);
return '[' . str_replace('.', '].[', $value) . ']';
case dibi::BOOL:
return $value ? 1 : 0;
case dibi::FIELD_BOOL:
return $value ? -1 : 0;
case dibi::DATE:
case dibi::FIELD_DATE:
return date("#m/d/Y#", $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date("#m/d/Y H:i:s#", $value);
default:
@@ -238,15 +237,12 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -261,7 +257,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
*/
public function applyLimit(&$sql, $limit, $offset)
{
// offset support is missing
// offset suppot is missing...
if ($limit >= 0) {
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ')';
}
@@ -279,7 +275,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
// will return -1 with many drivers :-(
return odbc_num_rows($this->resultSet);
@@ -313,6 +309,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
*/
public function seek($row)
{

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -27,20 +28,22 @@
* - 'password' (or 'pass')
* - 'charset' - character encoding to set
* - 'lazy' - if TRUE, connection will be established only when required
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiOracleDriver extends DibiObject implements IDibiDriver
{
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
/** @var bool */
private $autocommit = TRUE;
@@ -65,13 +68,12 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
*/
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 (isset($config['resource'])) {
$this->connection = $config['resource'];
} else {
$this->connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']); // intentionally @
}
$this->connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']); // intentionally @
if (!$this->connection) {
$err = oci_error();
@@ -122,7 +124,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
throw new NotImplementedException;
}
@@ -133,7 +135,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
throw new NotSupportedException('Oracle does not support autoincrementing.');
}
@@ -142,10 +144,10 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
$this->autocommit = FALSE;
}
@@ -154,11 +156,10 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
if (!oci_commit($this->connection)) {
$err = oci_error($this->connection);
@@ -171,11 +172,10 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
if (!oci_rollback($this->connection)) {
$err = oci_error($this->connection);
@@ -202,17 +202,17 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::BINARY:
case dibi::FIELD_TEXT:
case dibi::FIELD_BINARY:
return "'" . str_replace("'", "''", $value) . "'"; // TODO: not tested
case dibi::IDENTIFIER:
@@ -220,13 +220,13 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
$value = str_replace('"', '""', $value);
return '"' . str_replace('.', '"."', $value) . '"';
case dibi::BOOL:
case dibi::FIELD_BOOL:
return $value ? 1 : 0;
case dibi::DATE:
case dibi::FIELD_DATE:
return date("U", $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date("U", $value);
default:
@@ -239,15 +239,12 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -262,13 +259,8 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
*/
public function applyLimit(&$sql, $limit, $offset)
{
if ($offset > 0) {
// see http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html
$sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t ' . ($limit >= 0 ? 'WHERE ROWNUM <= ' . ((int) $offset + (int) $limit) : '') . ') WHERE "__rnum" > '. (int) $offset;
} elseif ($limit >= 0) {
$sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . (int) $limit;
}
if ($limit < 0 && $offset < 1) return;
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
}
@@ -281,9 +273,9 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
throw new NotSupportedException('Row count is not available for unbuffered queries.');
return oci_num_rows($this->resultSet);
}
@@ -305,6 +297,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
*/
public function seek($row)
{
@@ -367,18 +360,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver
*/
public function getTables()
{
$this->query('SELECT * FROM cat');
$res = array();
while ($row = $this->fetch(FALSE)) {
if ($row[1] === 'TABLE' || $row[1] === 'VIEW') {
$res[] = array(
'name' => $row[0],
'view' => $row[1] === 'VIEW',
);
}
}
$this->free();
return $res;
throw new NotImplementedException;
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -26,21 +27,24 @@
* - 'username' (or 'user')
* - 'password' (or 'pass')
* - 'options' - driver specific options array
* - 'resource' - PDO object (optional)
* - 'pdo' - PDO object (optional)
* - 'lazy' - if TRUE, connection will be established only when required
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiPdoDriver extends DibiObject implements IDibiDriver
{
/** @var PDO Connection resource */
private $connection;
/** @var PDOStatement Resultset resource */
private $resultSet;
/** @var int|FALSE Affected rows */
private $affectedRows = FALSE;
@@ -65,12 +69,14 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
*/
public function connect(array &$config)
{
DibiConnection::alias($config, 'username', 'user');
DibiConnection::alias($config, 'password', 'pass');
DibiConnection::alias($config, 'dsn');
DibiConnection::alias($config, 'resource', 'pdo');
DibiConnection::alias($config, 'pdo');
DibiConnection::alias($config, 'options');
if ($config['resource'] instanceof PDO) {
$this->connection = $config['resource'];
if ($config['pdo'] instanceof PDO) {
$this->connection = $config['pdo'];
} else try {
$this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']);
@@ -139,7 +145,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
return $this->affectedRows;
}
@@ -150,7 +156,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
return $this->connection->lastInsertId();
}
@@ -159,11 +165,10 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
if (!$this->connection->beginTransaction()) {
$err = $this->connection->errorInfo();
@@ -175,11 +180,10 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
if (!$this->connection->commit()) {
$err = $this->connection->errorInfo();
@@ -191,11 +195,10 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
if (!$this->connection->rollBack()) {
$err = $this->connection->errorInfo();
@@ -221,19 +224,19 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::FIELD_TEXT:
return $this->connection->quote($value, PDO::PARAM_STR);
case dibi::BINARY:
case dibi::FIELD_BINARY:
return $this->connection->quote($value, PDO::PARAM_LOB);
case dibi::IDENTIFIER:
@@ -263,13 +266,13 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
return $value;
}
case dibi::BOOL:
case dibi::FIELD_BOOL:
return $this->connection->quote($value, PDO::PARAM_BOOL);
case dibi::DATE:
case dibi::FIELD_DATE:
return date("'Y-m-d'", $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date("'Y-m-d H:i:s'", $value);
default:
@@ -282,15 +285,12 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -305,43 +305,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
*/
public function applyLimit(&$sql, $limit, $offset)
{
if ($limit < 0 && $offset < 1) return;
switch ($this->connection->getAttribute(PDO::ATTR_DRIVER_NAME)) {
case 'mysql':
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
break;
case 'pgsql':
if ($limit >= 0) $sql .= ' LIMIT ' . (int) $limit;
if ($offset > 0) $sql .= ' OFFSET ' . (int) $offset;
break;
case 'sqlite':
case 'sqlite2':
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
break;
case 'oci':
if ($offset > 0) {
$sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t ' . ($limit >= 0 ? 'WHERE ROWNUM <= ' . ((int) $offset + (int) $limit) : '') . ') WHERE "__rnum" > '. (int) $offset;
} elseif ($limit >= 0) {
$sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . (int) $limit;
}
break;
case 'odbc':
case 'mssql':
if ($offset < 1) {
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ')';
break;
}
// intentionally break omitted
default:
throw new NotSupportedException('PDO or driver does not support applying limit or offset.');
}
throw new NotSupportedException('PDO does not support applying limit or offset.');
}
@@ -354,9 +318,9 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
throw new NotSupportedException('Row count is not available for unbuffered queries.');
throw new DibiDriverException('Row count is not available for unbuffered queries.');
}
@@ -378,10 +342,11 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
*/
public function seek($row)
{
throw new NotSupportedException('Cannot seek an unbuffered result set.');
throw new DibiDriverException('Cannot seek an unbuffered result set.');
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -28,20 +29,22 @@
* - 'charset' - character encoding to set
* - 'schema' - the schema search path
* - 'lazy' - if TRUE, connection will be established only when required
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiPostgreDriver extends DibiObject implements IDibiDriver
{
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
/** @var bool Escape method */
private $escMethod = FALSE;
@@ -66,28 +69,23 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
*/
public function connect(array &$config)
{
if (isset($config['resource'])) {
$this->connection = $config['resource'];
if (isset($config['string'])) {
$string = $config['string'];
} else {
if (isset($config['string'])) {
$string = $config['string'];
} else {
$string = '';
foreach (array('host','hostaddr','port','dbname','user','password','connect_timeout','options','sslmode','service') as $key) {
if (isset($config[$key])) $string .= $key . '=' . $config[$key] . ' ';
}
$string = '';
foreach (array('host','hostaddr','port','dbname','user','password','connect_timeout','options','sslmode','service') as $key) {
if (isset($config[$key])) $string .= $key . '=' . $config[$key] . ' ';
}
}
DibiDriverException::tryError();
if (empty($config['persistent'])) {
$this->connection = pg_connect($string, PGSQL_CONNECT_FORCE_NEW);
} else {
$this->connection = pg_pconnect($string, PGSQL_CONNECT_FORCE_NEW);
}
if (DibiDriverException::catchError($msg)) {
throw new DibiDriverException($msg, 0);
}
DibiDriverException::tryError();
if (empty($config['persistent'])) {
$this->connection = pg_connect($string, PGSQL_CONNECT_FORCE_NEW);
} else {
$this->connection = pg_pconnect($string, PGSQL_CONNECT_FORCE_NEW);
}
if (DibiDriverException::catchError($msg)) {
throw new DibiDriverException($msg, 0);
}
if (!is_resource($this->connection)) {
@@ -103,7 +101,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
}
if (isset($config['schema'])) {
$this->query('SET search_path TO "' . $config['schema'] . '"');
$this->query('SET search_path TO ' . $config['schema']);
}
$this->escMethod = version_compare(PHP_VERSION , '5.2.0', '>=');
@@ -146,7 +144,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
return pg_affected_rows($this->resultSet);
}
@@ -157,7 +155,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
if ($sequence === NULL) {
// PostgreSQL 8.1 is needed
@@ -177,39 +175,36 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
$this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
$this->query('START TRANSACTION');
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
$this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
$this->query('COMMIT');
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
$this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
$this->query('ROLLBACK');
}
@@ -230,23 +225,23 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::FIELD_TEXT:
if ($this->escMethod) {
return "'" . pg_escape_string($this->connection, $value) . "'";
} else {
return "'" . pg_escape_string($value) . "'";
}
case dibi::BINARY:
case dibi::FIELD_BINARY:
if ($this->escMethod) {
return "'" . pg_escape_bytea($this->connection, $value) . "'";
} else {
@@ -263,13 +258,13 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
return substr($value, 0, $a) . '."' . str_replace('"', '""', substr($value, $a + 1)) . '"';
}
case dibi::BOOL:
case dibi::FIELD_BOOL:
return $value ? 'TRUE' : 'FALSE';
case dibi::DATE:
case dibi::FIELD_DATE:
return date("'Y-m-d'", $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date("'Y-m-d H:i:s'", $value);
default:
@@ -282,16 +277,19 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
switch ($type) {
case dibi::FIELD_BINARY:
return pg_unescape_bytea($value);
default:
throw new InvalidArgumentException('Unsupported type.');
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -322,7 +320,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
return pg_num_rows($this->resultSet);
}
@@ -346,6 +344,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
*/
public function seek($row)
{
@@ -412,7 +411,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
{
$version = pg_version($this->connection);
if ($version['server'] < 8) {
throw new DibiDriverException('Reflection requires PostgreSQL 8.');
throw new NotSupportedException('Reflection requires PostgreSQL 8.');
}
$this->query("
@@ -434,7 +433,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
*/
public function getColumns($table)
{
$_table = $this->escape($table, dibi::TEXT);
$_table = $this->escape($table, dibi::FIELD_TEXT);
$this->query("
SELECT indkey
FROM pg_class
@@ -476,7 +475,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver
*/
public function getIndexes($table)
{
$_table = $this->escape($table, dibi::TEXT);
$_table = $this->escape($table, dibi::FIELD_TEXT);
$this->query("
SELECT ordinal_position, column_name
FROM information_schema.columns

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -28,31 +29,29 @@
* - 'lazy' - if TRUE, connection will be established only when required
* - 'formatDate' - how to format date in SQL (@see date)
* - 'formatDateTime' - how to format datetime in SQL (@see date)
* - 'dbcharset' - database character encoding (will be converted to 'charset')
* - 'charset' - character encoding to set (default is UTF-8)
* - 'resource' - connection resource (optional)
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiSqliteDriver extends DibiObject implements IDibiDriver
{
/** @var resource Connection resource */
private $connection;
/** @var resource Resultset resource */
private $resultSet;
/** @var bool Is buffered (seekable and countable)? */
private $buffered;
/** @var string Date and datetime format */
private $fmtDate, $fmtDateTime;
/** @var string character encoding */
private $dbcharset, $charset;
/**
@@ -79,9 +78,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
$this->fmtDateTime = isset($config['formatDateTime']) ? $config['formatDateTime'] : 'U';
$errorMsg = '';
if (isset($config['resource'])) {
$this->connection = $config['resource'];
} elseif (empty($config['persistent'])) {
if (empty($config['persistent'])) {
$this->connection = @sqlite_open($config['database'], 0666, $errorMsg); // intentionally @
} else {
$this->connection = @sqlite_popen($config['database'], 0666, $errorMsg); // intentionally @
@@ -92,12 +89,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
}
$this->buffered = empty($config['unbuffered']);
$this->dbcharset = empty($config['dbcharset']) ? 'UTF-8' : $config['dbcharset'];
$this->charset = empty($config['charset']) ? 'UTF-8' : $config['charset'];
if (strcasecmp($this->dbcharset, $this->charset) === 0) {
$this->dbcharset = $this->charset = NULL;
}
}
@@ -121,10 +112,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
*/
public function query($sql)
{
if ($this->dbcharset !== NULL) {
$sql = iconv($this->charset, $this->dbcharset . '//IGNORE', $sql);
}
DibiDriverException::tryError();
if ($this->buffered) {
$this->resultSet = sqlite_query($this->connection, $sql);
@@ -144,7 +131,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
public function getAffectedRows()
public function affectedRows()
{
return sqlite_changes($this->connection);
}
@@ -155,7 +142,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
public function getInsertId($sequence)
public function insertId($sequence)
{
return sqlite_last_insert_rowid($this->connection);
}
@@ -164,11 +151,10 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function begin($savepoint = NULL)
public function begin()
{
$this->query('BEGIN');
}
@@ -177,11 +163,10 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function commit($savepoint = NULL)
public function commit()
{
$this->query('COMMIT');
}
@@ -190,11 +175,10 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
public function rollback($savepoint = NULL)
public function rollback()
{
$this->query('ROLLBACK');
}
@@ -217,32 +201,29 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
case dibi::BINARY:
case dibi::FIELD_TEXT:
case dibi::FIELD_BINARY:
return "'" . sqlite_escape_string($value) . "'";
/*case dibi::BINARY: // SQLite 3
return "X'" . bin2hex((string) $value) . "'";*/
case dibi::IDENTIFIER:
return '[' . str_replace('.', '].[', strtr($value, '[]', ' ')) . ']';
case dibi::BOOL:
case dibi::FIELD_BOOL:
return $value ? 1 : 0;
case dibi::DATE:
case dibi::FIELD_DATE:
return date($this->fmtDate, $value);
case dibi::DATETIME:
case dibi::FIELD_DATETIME:
return date($this->fmtDateTime, $value);
default:
@@ -255,15 +236,12 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
public function unescape($value, $type)
{
if ($type === dibi::BINARY) {
return $value;
}
throw new InvalidArgumentException('Unsupported type.');
}
@@ -292,7 +270,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
public function getRowCount()
public function rowCount()
{
if (!$this->buffered) {
throw new DibiDriverException('Row count is not available for unbuffered queries.');
@@ -311,13 +289,9 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
public function fetch($assoc)
{
$row = sqlite_fetch_array($this->resultSet, $assoc ? SQLITE_ASSOC : SQLITE_NUM);
$charset = $this->charset === NULL ? NULL : $this->charset . '//TRANSLIT';
if ($row && ($assoc || $charset)) {
if ($assoc && $row) {
$tmp = array();
foreach ($row as $k => $v) {
if ($charset !== NULL && is_string($v)) {
$v = iconv($this->dbcharset, $charset, $v);
}
$tmp[str_replace(array('[', ']'), '', $k)] = $v;
}
return $tmp;
@@ -404,10 +378,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
SELECT name, type = 'view' as view FROM sqlite_temp_master WHERE type IN ('table', 'view')
ORDER BY name
");
$res = array();
while ($row = $this->fetch(TRUE)) {
$res[] = $row;
}
$res = sqlite_fetch_all($this->resultSet, SQLITE_ASSOC);
$this->free();
return $res;
}
@@ -448,37 +419,4 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver
throw new NotImplementedException;
}
/********************* user defined functions ****************d*g**/
/**
* Registers an user defined function for use in SQL statements.
* @param string function name
* @param mixed callback
* @param int num of arguments
* @return void
*/
public function registerFunction($name, $callback, $numArgs = -1)
{
sqlite_create_function($this->connection, $name, $callback, $numArgs);
}
/**
* Registers an aggregating user defined function for use in SQL statements.
* @param string function name
* @param mixed callback called for each row of the result set
* @param mixed callback called to aggregate the "stepped" data from each row
* @param int num of arguments
* @return void
*/
public function registerAggregateFunction($name, $rowCallback, $agrCallback, $numArgs = -1)
{
sqlite_create_aggregate($this->connection, $name, $rowCallback, $agrCallback, $numArgs);
}
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -23,7 +24,7 @@
* dibi connection.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiConnection extends DibiObject
@@ -53,8 +54,8 @@ class DibiConnection extends DibiObject
*/
public function __construct($config, $name = NULL)
{
if (class_exists(/*Nette\*/'Debug', FALSE)) {
/*Nette\*/Debug::addColophon(array('dibi', 'getColophon'));
if (class_exists(/*Nette::*/'Debug', FALSE)) {
/*Nette::*/Debug::addColophon(array('dibi', 'getColophon'));
}
// DSN string
@@ -68,10 +69,6 @@ class DibiConnection extends DibiObject
throw new InvalidArgumentException('Configuration must be array, string or ArrayObject.');
}
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'host', 'hostname');
if (!isset($config['driver'])) {
$config['driver'] = dibi::$defaultDriver;
}
@@ -101,12 +98,6 @@ class DibiConnection extends DibiObject
$this->setProfiler(new $class);
}
if (!empty($config['substitutes'])) {
foreach ($config['substitutes'] as $key => $value) {
dibi::addSubst($key, $value);
}
}
if (empty($config['lazy'])) {
$this->connect();
}
@@ -217,25 +208,12 @@ class DibiConnection extends DibiObject
/**
* Returns the connection resource.
* @return IDibiDriver
*/
final public function getDriver()
{
return $this->driver;
}
/**
* Returns the connection resource.
* @return resource
* @deprecated use getDriver()->getResource()
*/
final public function getResource()
{
trigger_error('Deprecated: use getDriver()->getResource(...) instead.', E_USER_WARNING);
return $this->driver->getResource();
}
@@ -244,31 +222,19 @@ class DibiConnection extends DibiObject
/**
* Generates (translates) and executes SQL query.
* @param array|mixed one or more arguments
* @return DibiResult|int result set object (if any)
* @return DibiResult|NULL result set object (if any)
* @throws DibiException
*/
final public function query($args)
{
$args = func_get_args();
$this->connect();
$translator = new DibiTranslator($this->driver);
return $this->nativeQuery($translator->translate($args));
}
/**
* Generates and returns SQL query.
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
*/
final public function sql($args)
{
$args = func_get_args();
$this->connect();
$translator = new DibiTranslator($this->driver);
return $translator->translate($args);
$trans = new DibiTranslator($this->driver);
if ($trans->translate($args)) {
return $this->nativeQuery($trans->sql);
} else {
throw new DibiException('SQL translate error: ' . $trans->sql);
}
}
@@ -282,31 +248,10 @@ class DibiConnection extends DibiObject
{
$args = func_get_args();
$this->connect();
try {
$translator = new DibiTranslator($this->driver);
dibi::dump($translator->translate($args));
return TRUE;
} catch (DibiException $e) {
dibi::dump($e->getSql());
return FALSE;
}
}
/**
* Generates (translates) and returns SQL query as DibiDataSource.
* @param array|mixed one or more arguments
* @return DibiDataSource
* @throws DibiException
*/
final public function dataSource($args)
{
$args = func_get_args();
$this->connect();
$translator = new DibiTranslator($this->driver);
return new DibiDataSource($translator->translate($args), $this);
$trans = new DibiTranslator($this->driver);
$ok = $trans->translate($args);
dibi::dump($trans->sql);
return $ok;
}
@@ -314,7 +259,7 @@ class DibiConnection extends DibiObject
/**
* Executes the SQL query.
* @param string SQL statement.
* @return DibiResult|int result set object (if any)
* @return DibiResult|NULL result set object (if any)
* @throws DibiException
*/
final public function nativeQuery($sql)
@@ -340,8 +285,6 @@ class DibiConnection extends DibiObject
if ($res = $this->driver->query($sql)) { // intentionally =
$res = new DibiResult($res, $this->config);
} else {
$res = $this->driver->getAffectedRows();
}
$time += microtime(TRUE);
@@ -361,23 +304,11 @@ class DibiConnection extends DibiObject
* @return int number of rows
* @throws DibiException
*/
public function getAffectedRows()
{
$rows = $this->driver->getAffectedRows();
if (!is_int($rows) || $rows < 0) throw new DibiException('Cannot retrieve number of affected rows.');
return $rows;
}
/**
* Gets the number of affected rows. Alias for getAffectedRows().
* @return int number of rows
* @throws DibiException
*/
public function affectedRows()
{
return $this->getAffectedRows();
$rows = $this->driver->affectedRows();
if (!is_int($rows) || $rows < 0) throw new DibiException('Cannot retrieve number of affected rows.');
return $rows;
}
@@ -388,47 +319,29 @@ class DibiConnection extends DibiObject
* @return int
* @throws DibiException
*/
public function getInsertId($sequence = NULL)
public function insertId($sequence = NULL)
{
$id = $this->driver->getInsertId($sequence);
$id = $this->driver->insertId($sequence);
if ($id < 1) throw new DibiException('Cannot retrieve last generated ID.');
return (int) $id;
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
* @param string optional sequence name
* @return int
* @throws DibiException
*/
public function insertId($sequence = NULL)
{
return $this->getInsertId($sequence);
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
*/
public function begin($savepoint = NULL)
public function begin()
{
$this->connect();
if (!$savepoint && $this->inTxn) {
if ($this->inTxn) {
throw new DibiException('There is already an active transaction.');
}
if ($this->profiler !== NULL) {
$ticket = $this->profiler->before($this, IDibiProfiler::BEGIN, $savepoint);
$ticket = $this->profiler->before($this, IDibiProfiler::BEGIN);
}
if ($savepoint && !$this->inTxn) {
$this->driver->begin();
}
$this->driver->begin($savepoint);
$this->driver->begin();
$this->inTxn = TRUE;
if (isset($ticket)) {
$this->profiler->after($ticket);
@@ -439,19 +352,18 @@ class DibiConnection extends DibiObject
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
*/
public function commit($savepoint = NULL)
public function commit()
{
if (!$this->inTxn) {
throw new DibiException('There is no active transaction.');
}
if ($this->profiler !== NULL) {
$ticket = $this->profiler->before($this, IDibiProfiler::COMMIT, $savepoint);
$ticket = $this->profiler->before($this, IDibiProfiler::COMMIT);
}
$this->driver->commit($savepoint);
$this->inTxn = (bool) $savepoint;
$this->driver->commit();
$this->inTxn = FALSE;
if (isset($ticket)) {
$this->profiler->after($ticket);
}
@@ -461,19 +373,18 @@ class DibiConnection extends DibiObject
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
*/
public function rollback($savepoint = NULL)
public function rollback()
{
if (!$this->inTxn) {
throw new DibiException('There is no active transaction.');
}
if ($this->profiler !== NULL) {
$ticket = $this->profiler->before($this, IDibiProfiler::ROLLBACK, $savepoint);
$ticket = $this->profiler->before($this, IDibiProfiler::ROLLBACK);
}
$this->driver->rollback($savepoint);
$this->inTxn = (bool) $savepoint;
$this->driver->rollback();
$this->inTxn = FALSE;
if (isset($ticket)) {
$this->profiler->after($ticket);
}
@@ -482,26 +393,13 @@ class DibiConnection extends DibiObject
/**
* Is in transaction?
* @return bool
*/
public function inTransaction()
{
return $this->inTxn;
}
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string unescaped string
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string escaped and quoted string
* @deprecated
*/
public function escape($value, $type = dibi::TEXT)
public function escape($value, $type = dibi::FIELD_TEXT)
{
trigger_error('Deprecated: use getDriver()->escape(...) instead.', E_USER_WARNING);
$this->connect(); // MySQL & PDO require connection
return $this->driver->escape($value, $type);
}
@@ -511,13 +409,11 @@ class DibiConnection extends DibiObject
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @deprecated
*/
public function unescape($value, $type = dibi::BINARY)
public function unescape($value, $type = dibi::FIELD_BINARY)
{
trigger_error('Deprecated: use getDriver()->unescape(...) instead.', E_USER_WARNING);
return $this->driver->unescape($value, $type);
}
@@ -527,11 +423,9 @@ class DibiConnection extends DibiObject
* Delimites identifier (table's or column's name, etc.).
* @param string identifier
* @return string delimited identifier
* @deprecated
*/
public function delimite($value)
{
trigger_error('Deprecated: use getDriver()->escape(...) instead.', E_USER_WARNING);
return $this->driver->escape($value, dibi::IDENTIFIER);
}
@@ -543,11 +437,9 @@ class DibiConnection extends DibiObject
* @param int $limit
* @param int $offset
* @return void
* @deprecated
*/
public function applyLimit(&$sql, $limit, $offset)
{
trigger_error('Deprecated: use getDriver()->applyLimit(...) instead.', E_USER_WARNING);
$this->driver->applyLimit($sql, $limit, $offset);
}
@@ -584,11 +476,8 @@ class DibiConnection extends DibiObject
* @param array
* @return DibiFluent
*/
public function update($table, $args)
public function update($table, array $args)
{
if (!(is_array($args) || $args instanceof ArrayObject)) {
throw new InvalidArgumentException('Arguments must be array or ArrayObject.');
}
return $this->command()->update('%n', $table)->set($args);
}
@@ -599,15 +488,10 @@ class DibiConnection extends DibiObject
* @param array
* @return DibiFluent
*/
public function insert($table, $args)
public function insert($table, array $args)
{
if ($args instanceof ArrayObject) {
$args = (array) $args;
} elseif (!is_array($args)) {
throw new InvalidArgumentException('Arguments must be array or ArrayObject.');
}
return $this->command()->insert()
->into('%n', $table, '(%n)', array_keys($args))->values('%l', $args);
->into('%n', $table, '(%n)', array_keys($args))->values('%l', array_values($args));
}
@@ -648,66 +532,6 @@ class DibiConnection extends DibiObject
/********************* shortcuts ****************d*g**/
/**
* Executes SQL query and fetch result - shortcut for query() & fetch().
* @param array|mixed one or more arguments
* @return DibiRow
* @throws DibiException
*/
public function fetch($args)
{
$args = func_get_args();
return $this->query($args)->fetch();
}
/**
* Executes SQL query and fetch results - shortcut for query() & fetchAll().
* @param array|mixed one or more arguments
* @return array of DibiRow
* @throws DibiException
*/
public function fetchAll($args)
{
$args = func_get_args();
return $this->query($args)->fetchAll();
}
/**
* Executes SQL query and fetch first column - shortcut for query() & fetchSingle().
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
*/
public function fetchSingle($args)
{
$args = func_get_args();
return $this->query($args)->fetchSingle();
}
/**
* Executes SQL query and fetch pairs - shortcut for query() & fetchPairs().
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
*/
public function fetchPairs($args)
{
$args = func_get_args();
return $this->query($args)->fetchPairs();
}
/********************* misc ****************d*g**/
@@ -751,7 +575,6 @@ class DibiConnection extends DibiObject
*/
public function getDatabaseInfo()
{
$this->connect();
return new DibiDatabaseInfo($this->driver, isset($this->config['database']) ? $this->config['database'] : NULL);
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -23,7 +24,7 @@
* Default implementation of IDataSource for dibi.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiDataSource extends DibiObject implements IDataSource
@@ -34,306 +35,58 @@ class DibiDataSource extends DibiObject implements IDataSource
/** @var string */
private $sql;
/** @var DibiResult */
private $result;
/** @var int */
private $count;
/** @var int */
private $totalCount;
/** @var array */
private $cols = array();
/** @var array */
private $sorting = array();
/** @var array */
private $conds = array();
/** @var int */
private $offset;
/** @var int */
private $limit;
/**
* @param string SQL command or table or view name, as data source
* @param string SQL command or table name, as data source
* @param DibiConnection connection
*/
public function __construct($sql, DibiConnection $connection)
public function __construct($sql, DibiConnection $connection = NULL)
{
if (strpos($sql, ' ') === FALSE) {
$this->sql = $connection->getDriver()->escape($sql, dibi::IDENTIFIER); // table name
// table name
$this->sql = $sql;
} else {
$this->sql = '(' . $sql . ') t'; // SQL command
// SQL command
$this->sql = '(' . $sql . ') AS [source]';
}
$this->connection = $connection;
$this->connection = $connection === NULL ? dibi::getConnection() : $connection;
}
/**
* Selects columns to query.
* @param string|array column name or array of column names
* @param string column alias
* @return DibiDataSource provides a fluent interface
* @param int offset
* @param int limit
* @param array columns
* @return ArrayIterator
*/
public function select($col, $as = NULL)
public function getIterator($offset = NULL, $limit = NULL)
{
if (is_array($col)) {
$this->cols = $col;
} else {
$this->cols[$col] = $as;
}
$this->result = NULL;
return $this;
}
/**
* Adds conditions to query.
* @param mixed conditions
* @return DibiDataSource provides a fluent interface
*/
public function where($cond)
{
if (is_array($cond)) {
// TODO: not consistent with select and orderBy
$this->conds[] = $cond;
} else {
$this->conds[] = func_get_args();
}
$this->result = $this->count = NULL;
return $this;
}
/**
* Selects columns to order by.
* @param string|array column name or array of column names
* @param string sorting direction
* @return DibiDataSource provides a fluent interface
*/
public function orderBy($row, $sorting = 'ASC')
{
if (is_array($row)) {
$this->sorting = $row;
} else {
$this->sorting[$row] = $sorting;
}
$this->result = NULL;
return $this;
}
/**
* Limits number of rows.
* @param int limit
* @param int offset
* @return DibiDataSource provides a fluent interface
*/
public function applyLimit($limit, $offset = NULL)
{
$this->limit = $limit;
$this->offset = $offset;
$this->result = $this->count = NULL;
return $this;
}
/**
* Returns the dibi connection.
* @return DibiConnection
*/
final public function getConnection()
{
return $this->connection;
}
/********************* executing ****************d*g**/
/**
* Returns (and queries) DibiResult.
* @return DibiResult
*/
public function getResult()
{
if ($this->result === NULL) {
$this->result = $this->connection->nativeQuery($this->__toString());
}
return $this->result;
}
/**
* @return DibiResultIterator
*/
public function getIterator()
{
return $this->getResult()->getIterator();
}
/**
* Generates, executes SQL query and fetches the single row.
* @return DibiRow|FALSE array on success, FALSE if no next record
*/
public function fetch()
{
return $this->getResult()->fetch();
}
/**
* Like fetch(), but returns only first field.
* @return mixed value on success, FALSE if no next record
*/
public function fetchSingle()
{
return $this->getResult()->fetchSingle();
}
/**
* Fetches all records from table.
* @return array
*/
public function fetchAll()
{
return $this->getResult()->fetchAll();
}
/**
* Fetches all records from table and returns associative tree.
* @param string associative descriptor
* @return array
*/
public function fetchAssoc($assoc)
{
return $this->getResult()->fetchAssoc($assoc);
}
/**
* Fetches all records from table like $key => $value pairs.
* @param string associative key
* @param string value
* @return array
*/
public function fetchPairs($key = NULL, $value = NULL)
{
return $this->getResult()->fetchPairs($key, $value);
}
/**
* Discards the internal cache.
* @return void
*/
public function release()
{
$this->result = $this->count = $this->totalCount = NULL;
}
/********************* exporting ****************d*g**/
/**
* Returns this data source wrapped in DibiFluent object.
* @return DibiFluent
*/
public function toFluent()
{
return $this->connection->select('*')->from('(%SQL) AS t', $this->__toString());
}
/**
* Returns this data source wrapped in DibiDataSource object.
* @return DibiDataSource
*/
public function toDataSource()
{
return new self($this->__toString(), $this->connection);
}
/**
* Returns SQL query.
* @return string
*/
final public function __toString()
{
return $this->connection->sql('
SELECT %n', (empty($this->cols) ? '*' : $this->cols), '
FROM %SQL', $this->sql, '
%ex', $this->conds ? array('WHERE %and', $this->conds) : NULL, '
%ex', $this->sorting ? array('ORDER BY %by', $this->sorting) : NULL, '
%ofs %lmt', $this->offset, $this->limit
return $this->connection->query('
SELECT *
FROM', $this->sql, '
%ofs %lmt', $offset, $limit
);
}
/********************* counting ****************d*g**/
/**
* Returns the number of rows in a given data source.
* @return int
*/
public function count()
{
if ($this->count === NULL) {
$this->count = $this->conds || $this->offset || $this->limit
? (int) $this->connection->nativeQuery(
'SELECT COUNT(*) FROM (' . $this->__toString() . ') AS t'
)->fetchSingle()
: $this->getTotalCount();
$this->count = $this->connection->query('
SELECT COUNT(*) FROM', $this->sql
)->fetchSingle();
}
return $this->count;
}
/**
* Returns the number of rows in a given data source.
* @return int
*/
public function getTotalCount()
{
if ($this->totalCount === NULL) {
$this->totalCount = (int) $this->connection->nativeQuery(
'SELECT COUNT(*) FROM ' . $this->sql
)->fetchSingle();
}
return $this->totalCount;
}
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -23,7 +24,7 @@
* Reflection metadata class for a database.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiDatabaseInfo extends DibiObject
@@ -84,7 +85,7 @@ class DibiDatabaseInfo extends DibiObject
/**
* @param string
* @param string
* @return DibiTableInfo
*/
public function getTable($name)
@@ -102,7 +103,7 @@ class DibiDatabaseInfo extends DibiObject
/**
* @param string
* @param string
* @return bool
*/
public function hasTable($name)
@@ -135,7 +136,7 @@ class DibiDatabaseInfo extends DibiObject
* Reflection metadata class for a database table.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiTableInfo extends DibiObject
@@ -219,7 +220,7 @@ class DibiTableInfo extends DibiObject
/**
* @param string
* @param string
* @return DibiColumnInfo
*/
public function getColumn($name)
@@ -237,7 +238,7 @@ class DibiTableInfo extends DibiObject
/**
* @param string
* @param string
* @return bool
*/
public function hasColumn($name)
@@ -335,7 +336,7 @@ class DibiTableInfo extends DibiObject
* Reflection metadata class for a table column.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiColumnInfo extends DibiObject
@@ -475,18 +476,17 @@ class DibiColumnInfo extends DibiObject
public static function detectType($type)
{
static $patterns = array(
'BYTEA|BLOB|BIN' => dibi::BINARY,
'TEXT|CHAR' => dibi::TEXT,
'BYTE|COUNTER|SERIAL|INT|LONG' => dibi::INTEGER,
'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER' => dibi::FLOAT,
'^TIME$' => dibi::TIME,
'TIME' => dibi::DATETIME, // DATETIME, TIMESTAMP
'YEAR|DATE' => dibi::DATE,
'BOOL|BIT' => dibi::BOOL,
'BYTE|COUNTER|SERIAL|INT|LONG' => dibi::FIELD_INTEGER,
'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC' => dibi::FIELD_FLOAT,
'^TIME$' => dibi::FIELD_TIME,
'TIME' => dibi::FIELD_DATETIME, // DATETIME, TIMESTAMP
'YEAR|DATE' => dibi::FIELD_DATE,
'BYTEA|BLOB|BIN' => dibi::FIELD_BINARY,
'BOOL|BIT' => dibi::FIELD_BOOL,
);
if (!isset(self::$types[$type])) {
self::$types[$type] = dibi::TEXT;
self::$types[$type] = dibi::FIELD_TEXT;
foreach ($patterns as $s => $val) {
if (preg_match("#$s#i", $type)) {
return self::$types[$type] = $val;
@@ -505,7 +505,7 @@ class DibiColumnInfo extends DibiObject
* Reflection metadata class for a foreign key.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
* @todo
*/
@@ -551,10 +551,10 @@ class DibiForeignKeyInfo extends DibiObject
/**
* Reflection metadata class for a index or primary key.
* Reflection metadata class for a index or primary key
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiIndexInfo extends DibiObject
@@ -600,6 +600,7 @@ class DibiIndexInfo extends DibiObject
/**
* @return bool
*/

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -23,19 +24,36 @@
* dibi common exception.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiException extends Exception implements /*Nette\*/IDebuggable
class DibiException extends Exception
{
}
/**
* database server exception.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiDriverException extends DibiException implements /*Nette::*/IDebuggable
{
/** @var string */
private static $errorMsg;
/** @var string */
private $sql;
/**
* Construct a dibi exception.
* @param string Message describing the exception
* @param int Some code
* Construct an dibi driver exception.
* @param string Message describing the exception
* @param int Some code
* @param string SQL command
*/
public function __construct($message = NULL, $code = 0, $sql = NULL)
@@ -67,7 +85,7 @@ class DibiException extends Exception implements /*Nette\*/IDebuggable
/********************* interface Nette\IDebuggable ****************d*g**/
/********************* interface Nette::IDebuggable ****************d*g**/
/**
@@ -86,32 +104,14 @@ class DibiException extends Exception implements /*Nette\*/IDebuggable
return $panels;
}
}
/**
* database server exception.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @package dibi
*/
class DibiDriverException extends DibiException
{
/********************* error catching ****************d*g**/
/** @var string */
private static $errorMsg;
/**
* Starts catching potential errors/warnings.
* Starts catching potential errors/warnings
* @return void
*/
public static function tryError()

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -23,24 +24,23 @@
* dibi SQL builder via fluent interfaces. EXPERIMENTAL!
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiFluent extends DibiObject implements IDataSource
class DibiFluent extends DibiObject
{
/** @var array */
public static $masks = array(
'SELECT' => array('SELECT', 'DISTINCT', 'FROM', 'WHERE', 'GROUP BY',
'HAVING', 'ORDER BY', 'LIMIT', 'OFFSET'),
'UPDATE' => array('UPDATE', 'SET', 'WHERE', 'ORDER BY', 'LIMIT'),
'INSERT' => array('INSERT', 'INTO', 'VALUES', 'SELECT'),
'DELETE' => array('DELETE', 'FROM', 'USING', 'WHERE', 'ORDER BY', 'LIMIT'),
'HAVING', 'ORDER BY', 'LIMIT', 'OFFSET', '%end'),
'UPDATE' => array('UPDATE', 'SET', 'WHERE', 'ORDER BY', 'LIMIT', '%end'),
'INSERT' => array('INSERT', 'INTO', 'VALUES', 'SELECT', '%end'),
'DELETE' => array('DELETE', 'FROM', 'USING', 'WHERE', 'ORDER BY', 'LIMIT', '%end'),
);
/** @var array default modifiers for arrays */
/** @var array */
public static $modifiers = array(
'SELECT' => '%n',
'FROM' => '%n',
'IN' => '%l',
'VALUES' => '%l',
'SET' => '%a',
@@ -50,7 +50,7 @@ class DibiFluent extends DibiObject implements IDataSource
'GROUP BY' => '%by',
);
/** @var array clauses separators */
/** @var array */
public static $separators = array(
'SELECT' => ',',
'FROM' => FALSE,
@@ -119,20 +119,17 @@ class DibiFluent extends DibiObject implements IDataSource
if ($arg === TRUE) { // flag
$args = array();
} elseif (is_string($arg) && preg_match('#^[a-z:_][a-z0-9_.:]*$#i', $arg)) { // identifier
} elseif (is_string($arg) && preg_match('#^[a-z][a-z0-9_.]*$#i', $arg)) { // identifier
$args = array('%n', $arg);
} elseif ($arg instanceof self) {
$args = array_merge(array('('), $arg->_export(), array(')'));
} elseif (is_array($arg) || $arg instanceof ArrayObject) { // any array
} elseif (is_array($arg)) { // any array
if (isset(self::$modifiers[$clause])) {
$args = array(self::$modifiers[$clause], $arg);
} elseif (is_string(key($arg))) { // associative array
$args = array('%a', $arg);
}
} // case $arg === FALSE is handled below
}
}
if (array_key_exists($clause, $this->clauses)) {
@@ -237,31 +234,14 @@ class DibiFluent extends DibiObject implements IDataSource
/**
* Returns the dibi connection.
* @return DibiConnection
*/
final public function getConnection()
{
return $this->connection;
}
/********************* executing ****************d*g**/
/**
* Generates and executes SQL query.
* @param mixed what to return?
* @return DibiResult|int result set object (if any)
* @return DibiResult|NULL result set object (if any)
* @throws DibiException
*/
public function execute($return = NULL)
public function execute()
{
$res = $this->connection->query($this->_export());
return $return === dibi::IDENTIFIER ? $this->connection->getInsertId() : $res;
return $this->connection->query($this->_export());
}
@@ -269,14 +249,14 @@ class DibiFluent extends DibiObject implements IDataSource
/**
* Generates, executes SQL query and fetches the single row.
* @return DibiRow|FALSE array on success, FALSE if no next record
* @throws DibiException
*/
public function fetch()
{
if ($this->command === 'SELECT') {
return $this->connection->query($this->_export(NULL, array('%lmt', 1)))->fetch();
} else {
return $this->connection->query($this->_export())->fetch();
$this->clauses['LIMIT'] = array(1);
}
return $this->execute()->fetch();
}
@@ -288,10 +268,9 @@ class DibiFluent extends DibiObject implements IDataSource
public function fetchSingle()
{
if ($this->command === 'SELECT') {
return $this->connection->query($this->_export(NULL, array('%lmt', 1)))->fetchSingle();
} else {
return $this->connection->query($this->_export())->fetchSingle();
$this->clauses['LIMIT'] = array(1);
}
return $this->execute()->fetchSingle();
}
@@ -304,19 +283,22 @@ class DibiFluent extends DibiObject implements IDataSource
*/
public function fetchAll($offset = NULL, $limit = NULL)
{
return $this->connection->query($this->_export(NULL, array('%ofs %lmt', $offset, $limit)))->fetchAll();
return $this->execute()->fetchAll($offset, $limit);
}
/**
* Fetches all records from table and returns associative tree.
* Associative descriptor: assoc1,#,assoc2,=,assoc3,@
* builds a tree: $data[assoc1][index][assoc2]['assoc3']->value = {record}
* @param string associative descriptor
* @return array
* @throws InvalidArgumentException
*/
public function fetchAssoc($assoc)
{
return $this->connection->query($this->_export())->fetchAssoc($assoc);
return $this->execute()->fetchAssoc($assoc);
}
@@ -326,23 +308,11 @@ class DibiFluent extends DibiObject implements IDataSource
* @param string associative key
* @param string value
* @return array
* @throws InvalidArgumentException
*/
public function fetchPairs($key = NULL, $value = NULL)
{
return $this->connection->query($this->_export())->fetchPairs($key, $value);
}
/**
* Required by the IteratorAggregate interface.
* @param int offset
* @param int limit
* @return DibiResultIterator
*/
public function getIterator($offset = NULL, $limit = NULL)
{
return $this->connection->query($this->_export(NULL, array('%ofs %lmt', $offset, $limit)))->getIterator();
return $this->execute()->fetchPairs($key, $value);
}
@@ -359,49 +329,12 @@ class DibiFluent extends DibiObject implements IDataSource
/**
* @return int
*/
public function count()
{
return (int) $this->connection->query(
'SELECT COUNT(*) FROM (%ex', $this->_export(), ') AS [data]'
)->fetchSingle();
}
/********************* exporting ****************d*g**/
/**
* @return DibiDataSource
*/
public function toDataSource()
{
return new DibiDataSource($this->connection->sql($this->_export()), $this->connection);
}
/**
* Returns SQL query.
* @return string
*/
final public function __toString()
{
return $this->connection->sql($this->_export());
}
/**
* Generates parameters for DibiTranslator.
* @param string clause name
* @return array
*/
protected function _export($clause = NULL, $args = array())
protected function _export($clause = NULL)
{
if ($clause === NULL) {
$data = $this->clauses;
@@ -415,16 +348,18 @@ class DibiFluent extends DibiObject implements IDataSource
}
}
$args = array();
foreach ($data as $clause => $statement) {
if ($statement !== NULL) {
$args[] = $clause;
if ($clause === $this->command) {
$args[] = implode(' ', array_keys($this->flags));
if ($clause[0] !== '%') {
$args[] = $clause;
if ($clause === $this->command) {
$args[] = implode(' ', array_keys($this->flags));
}
}
array_splice($args, count($args), 0, $statement);
}
}
return $args;
}
@@ -445,6 +380,19 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Returns (highlighted) SQL query.
* @return string
*/
final public function __toString()
{
ob_start();
$this->test();
return ob_get_clean();
}
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -22,7 +23,7 @@
/**
* DibiObject is the ultimate ancestor of all instantiable classes.
*
* DibiObject is copy of Nette\Object from Nette Framework (http://nettephp.com).
* DibiObject is copy of Nette::Object from Nette Framework (http://nettephp.com).
*
* It defines some handful methods and enhances object core of PHP:
* - access to undeclared members throws exceptions
@@ -58,7 +59,7 @@
* </code>
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
abstract class DibiObject
@@ -81,11 +82,11 @@ abstract class DibiObject
/**
* Access to reflection.
* @return \ReflectionObject
* @return ReflectionObject
*/
final public function getReflection()
{
return new /*\*/ReflectionObject($this);
return new ReflectionObject($this);
}
@@ -95,22 +96,22 @@ abstract class DibiObject
* @param string method name
* @param array arguments
* @return mixed
* @throws \MemberAccessException
* @throws ::MemberAccessException
*/
public function __call($name, $args)
{
$class = get_class($this);
if ($name === '') {
throw new /*\*/MemberAccessException("Call to class '$class' method without name.");
throw new /*::*/MemberAccessException("Call to class '$class' method without name.");
}
// event functionality
if (preg_match('#^on[A-Z]#', $name)) {
$rp = new /*\*/ReflectionProperty($class, $name);
$rp = new ReflectionProperty($class, $name);
if ($rp->isPublic() && !$rp->isStatic()) {
$list = $this->$name;
if (is_array($list) || $list instanceof /*\*/Traversable) {
if (is_array($list) || $list instanceof Traversable) {
foreach ($list as $handler) {
/**/if (is_object($handler)) {
call_user_func_array(array($handler, '__invoke'), $args);
@@ -130,7 +131,7 @@ abstract class DibiObject
return call_user_func_array($cb, $args);
}
throw new /*\*/MemberAccessException("Call to undefined method $class::$name().");
throw new /*::*/MemberAccessException("Call to undefined method $class::$name().");
}
@@ -140,12 +141,12 @@ abstract class DibiObject
* @param string method name (in lower case!)
* @param array arguments
* @return mixed
* @throws \MemberAccessException
* @throws ::MemberAccessException
*/
public static function __callStatic($name, $args)
{
$class = get_called_class();
throw new /*\*/MemberAccessException("Call to undefined static method $class::$name().");
throw new /*::*/MemberAccessException("Call to undefined static method $class::$name().");
}
@@ -216,14 +217,14 @@ abstract class DibiObject
* Returns property value. Do not call directly.
* @param string property name
* @return mixed property value
* @throws \MemberAccessException if the property is not defined.
* @throws ::MemberAccessException if the property is not defined.
*/
public function &__get($name)
{
$class = get_class($this);
if ($name === '') {
throw new /*\*/MemberAccessException("Cannot read a class '$class' property without name.");
throw new /*::*/MemberAccessException("Cannot read an class '$class' property without name.");
}
// property getter support
@@ -231,7 +232,7 @@ abstract class DibiObject
$m = 'get' . $name;
if (self::hasAccessor($class, $m)) {
// ampersands:
// - uses &__get() because declaration should be forward compatible (e.g. with Nette\Web\Html)
// - uses &__get() because declaration should be forward compatible (e.g. with Nette::Web::Html)
// - doesn't call &$this->$m because user could bypass property setter by: $x = & $obj->property; $x = 'new value';
$val = $this->$m();
return $val;
@@ -244,7 +245,7 @@ abstract class DibiObject
}
$name = func_get_arg(0);
throw new /*\*/MemberAccessException("Cannot read an undeclared property $class::\$$name.");
throw new /*::*/MemberAccessException("Cannot read an undeclared property $class::\$$name.");
}
@@ -254,14 +255,14 @@ abstract class DibiObject
* @param string property name
* @param mixed property value
* @return void
* @throws \MemberAccessException if the property is not defined or is read-only
* @throws ::MemberAccessException if the property is not defined or is read-only
*/
public function __set($name, $value)
{
$class = get_class($this);
if ($name === '') {
throw new /*\*/MemberAccessException("Cannot assign to a class '$class' property without name.");
throw new /*::*/MemberAccessException("Cannot assign to an class '$class' property without name.");
}
// property setter support
@@ -274,12 +275,12 @@ abstract class DibiObject
} else {
$name = func_get_arg(0);
throw new /*\*/MemberAccessException("Cannot assign to a read-only property $class::\$$name.");
throw new /*::*/MemberAccessException("Cannot assign to a read-only property $class::\$$name.");
}
}
$name = func_get_arg(0);
throw new /*\*/MemberAccessException("Cannot assign to an undeclared property $class::\$$name.");
throw new /*::*/MemberAccessException("Cannot assign to an undeclared property $class::\$$name.");
}
@@ -301,12 +302,12 @@ abstract class DibiObject
* Access to undeclared property.
* @param string property name
* @return void
* @throws \MemberAccessException
* @throws ::MemberAccessException
*/
public function __unset($name)
{
$class = get_class($this);
throw new /*\*/MemberAccessException("Cannot unset the property $class::\$$name.");
throw new /*::*/MemberAccessException("Cannot unset an property $class::\$$name.");
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -23,22 +24,16 @@
* dibi basic logger & profiler (experimental).
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiProfiler extends DibiObject implements IDibiProfiler
{
/** maximum number of rows */
const FIREBUG_MAX_ROWS = 30;
/** maximum SQL length */
const FIREBUG_MAX_LENGTH = 500;
/** @var string Name of the file where SQL errors should be logged */
private $file;
/** @var bool log to firebug? */
public $useFirebug;
private $useFirebug;
/** @var int */
private $filter = self::ALL;
@@ -109,26 +104,17 @@ class DibiProfiler extends DibiObject implements IDibiProfiler
}
list($connection, $event, $sql) = $this->tickets[$ticket];
$sql = trim($sql);
if (($event & $this->filter) === 0) return;
if ($event & self::QUERY) {
try {
$count = $res instanceof DibiResult ? count($res) : '-';
} catch (Exception $e) {
$count = '?';
}
if ($this->useFirebug && !headers_sent()) {
if (count(self::$table) < self::FIREBUG_MAX_ROWS) {
self::$table[] = array(
sprintf('%0.3f', dibi::$elapsedTime * 1000),
strlen($sql) > self::FIREBUG_MAX_LENGTH ? substr($sql, 0, self::FIREBUG_MAX_LENGTH) . '...' : $sql,
$count,
$connection->getConfig('driver') . '/' . $connection->getConfig('name')
);
}
if ($this->useFirebug) {
self::$table[] = array(
sprintf('%0.3f', dibi::$elapsedTime * 1000),
trim($sql),
$res instanceof DibiResult ? count($res) : '-',
$connection->getConfig('driver') . '/' . $connection->getConfig('name')
);
header('X-Wf-Protocol-dibi: http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
header('X-Wf-dibi-Plugin-1: http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.2.0');
@@ -147,12 +133,13 @@ class DibiProfiler extends DibiObject implements IDibiProfiler
header("X-Wf-dibi-1-1-d$num: |$s|\\"); // protocol-, structure-, plugin-, message-index
}
header("X-Wf-dibi-1-1-d$num: |$s|");
header("X-Wf-dibi-Index: d$num");
}
if ($this->file) {
$this->writeFile(
"OK: " . $sql
. ($res instanceof DibiResult ? ";\n-- rows: " . $count : '')
. ($res instanceof DibiResult ? ";\n-- rows: " . count($res) : '')
. "\n-- takes: " . sprintf('%0.3f', dibi::$elapsedTime * 1000) . ' ms'
. "\n-- driver: " . $connection->getConfig('driver') . '/' . $connection->getConfig('name')
. "\n-- " . date('Y-m-d H:i:s')

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -36,7 +37,7 @@
* </code>
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiResult extends DibiObject implements IDataSource
@@ -56,9 +57,6 @@ class DibiResult extends DibiObject implements IDataSource
/** @var array|FALSE Qualifiy each column name with the table name? */
private $withTables = FALSE;
/** @var string returned object class */
private $class = 'DibiRow';
/**
@@ -115,20 +113,9 @@ class DibiResult extends DibiObject implements IDataSource
* Returns the number of rows in a result set.
* @return int
*/
final public function getRowCount()
{
return $this->getDriver()->getRowCount();
}
/**
* Returns the number of rows in a result set. Alias for getRowCount().
* @return int
*/
final public function rowCount()
{
return $this->getDriver()->getRowCount();
return $this->getDriver()->rowCount();
}
@@ -150,7 +137,7 @@ class DibiResult extends DibiObject implements IDataSource
/**
* Qualifiy each column name with the table name?
* @param bool
* @return DibiResult provides a fluent interface
* @return void
* @throws DibiException
*/
final public function setWithTables($val)
@@ -171,7 +158,6 @@ class DibiResult extends DibiObject implements IDataSource
} else {
$this->withTables = FALSE;
}
return $this;
}
@@ -187,30 +173,6 @@ class DibiResult extends DibiObject implements IDataSource
/**
* Set fetched object class. This class should extend the DibiRow class.
* @param string
* @return DibiResult provides a fluent interface
*/
public function setRowClass($class)
{
$this->class = $class;
return $this;
}
/**
* Returns fetched object class name.
* @return string
*/
public function getRowClass()
{
return $this->class;
}
/**
* Fetches the row at current position, process optional type conversion.
* and moves the internal cursor to the next position
@@ -239,7 +201,7 @@ class DibiResult extends DibiObject implements IDataSource
}
}
return new $this->class($row);
return new DibiRow($row, 2);
}
@@ -441,9 +403,9 @@ class DibiResult extends DibiObject implements IDataSource
/**
* Define column type.
* @param string column
* @param string type (use constant Dibi::*)
* @param string optional format
* @param string column
* @param string type (use constant Dibi::FIELD_*)
* @param string optional format
* @return void
*/
final public function setType($col, $type, $format = NULL)
@@ -468,7 +430,7 @@ class DibiResult extends DibiObject implements IDataSource
/**
* Define multiple columns types.
* @param array
* @param array
* @return void
* @internal
*/
@@ -491,11 +453,8 @@ class DibiResult extends DibiObject implements IDataSource
/**
* Converts value to specified type and format.
* @param mixed value
* @param int type
* @param string format
* @return mixed
* Converts value to specified type and format
* @return array ($type, $format)
*/
final public function convert($value, $type, $format = NULL)
{
@@ -504,24 +463,24 @@ class DibiResult extends DibiObject implements IDataSource
}
switch ($type) {
case dibi::TEXT:
case dibi::FIELD_TEXT:
return (string) $value;
case dibi::BINARY:
case dibi::FIELD_BINARY:
return $this->getDriver()->unescape($value, $type);
case dibi::INTEGER:
case dibi::FIELD_INTEGER:
return (int) $value;
case dibi::FLOAT:
case dibi::FIELD_FLOAT:
return (float) $value;
case dibi::DATE:
case dibi::DATETIME:
$value = is_numeric($value) ? (int) $value : strtotime($value);
case dibi::FIELD_DATE:
case dibi::FIELD_DATETIME:
$value = strtotime($value);
return $format === NULL ? $value : date($format, $value);
case dibi::BOOL:
case dibi::FIELD_BOOL:
return ((bool) $value) && $value !== 'f' && $value !== 'F';
default:
@@ -539,7 +498,7 @@ class DibiResult extends DibiObject implements IDataSource
{
$cols = array();
foreach ($this->getMeta() as $info) {
$cols[] = new DibiColumnInfo($this->getDriver(), $info);
$cols[] = new DibiColumnInfo($this->driver, $info);
}
return $cols;
}
@@ -602,11 +561,11 @@ class DibiResult extends DibiObject implements IDataSource
* Required by the IteratorAggregate interface.
* @param int offset
* @param int limit
* @return DibiResultIterator
* @return ArrayIterator
*/
final public function getIterator($offset = NULL, $limit = NULL)
{
return new DibiResultIterator($this, $offset, $limit);
return new ArrayIterator($this->fetchAll($offset, $limit));
}
@@ -617,7 +576,7 @@ class DibiResult extends DibiObject implements IDataSource
*/
final public function count()
{
return $this->getRowCount();
return $this->rowCount();
}
@@ -630,7 +589,7 @@ class DibiResult extends DibiObject implements IDataSource
private function getDriver()
{
if ($this->driver === NULL) {
throw new InvalidStateException('Result-set was released from memory.');
throw new InvalidStateException('Resultset was released from memory.');
}
return $this->driver;
@@ -654,3 +613,17 @@ class DibiResult extends DibiObject implements IDataSource
}
}
/**
* dibi result-set row
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
class DibiRow extends ArrayObject
{
}

View File

@@ -1,145 +0,0 @@
<?php
/**
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
*/
/**
* External result set iterator.
*
* This can be returned by DibiResult::getIterator() method or using foreach
* <code>
* $result = dibi::query('SELECT * FROM table');
* foreach ($result as $row) {
* print_r($row);
* }
* unset($result);
* </code>
*
* Optionally you can specify offset and limit:
* <code>
* foreach ($result->getIterator(2, 3) as $row) {
* print_r($row);
* }
* </code>
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @package dibi
*/
class DibiResultIterator implements Iterator, Countable
{
/** @var DibiResult */
private $result;
/** @var int */
private $offset;
/** @var int */
private $limit;
/** @var int */
private $row;
/** @var int */
private $pointer;
/**
* @param DibiResult
* @param int offset
* @param int limit
*/
public function __construct(DibiResult $result, $offset = NULL, $limit = NULL)
{
$this->result = $result;
$this->offset = (int) $offset;
$this->limit = $limit === NULL ? -1 : (int) $limit;
}
/**
* Rewinds the iterator to the first element.
* @return void
*/
public function rewind()
{
$this->pointer = 0;
$this->result->seek($this->offset);
$this->row = $this->result->fetch();
}
/**
* Returns the key of the current element.
* @return mixed
*/
public function key()
{
return $this->pointer;
}
/**
* Returns the current element.
* @return mixed
*/
public function current()
{
return $this->row;
}
/**
* Moves forward to next element.
* @return void
*/
public function next()
{
//$this->result->seek($this->offset + $this->pointer + 1);
$this->row = $this->result->fetch();
$this->pointer++;
}
/**
* Checks if there is a current element after calls to rewind() or next().
* @return bool
*/
public function valid()
{
return !empty($this->row) && ($this->limit < 0 || $this->pointer < $this->limit);
}
/**
* Required by the Countable interface.
* @return int
*/
public function count()
{
return $this->result->getRowCount();
}
}

View File

@@ -1,89 +0,0 @@
<?php
/**
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
*/
/**
* Result-set single row.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @package dibi
*/
class DibiRow extends ArrayObject
{
/**
* @param array
*/
public function __construct($arr)
{
parent::__construct($arr, 2);
}
/**
* Converts value to date-time format.
* @param string key
* @param string format
* @return mixed
*/
public function asDate($key, $format = NULL)
{
$value = $this[$key];
if ($value === NULL || $value === FALSE) {
return $value;
} else {
$value = is_numeric($value) ? (int) $value : strtotime($value);
return $format === NULL ? $value : date($format, $value);
}
}
/**
* Converts value to boolean.
* @param string key
* @return mixed
*/
public function asBool($key)
{
$value = $this[$key];
if ($value === NULL || $value === FALSE) {
return $value;
} else {
return ((bool) $value) && $value !== 'f' && $value !== 'F';
}
}
/**
* PHP < 5.3 workaround
* @return void
*/
public function __wakeup()
{
$this->setFlags(2);
}
}

420
dibi/libs/DibiTableX.php Normal file
View File

@@ -0,0 +1,420 @@
<?php
/**
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
/**
* Experimental object-oriented interface to database tables.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
abstract class DibiTableX extends DibiObject
{
/** @var string primary key mask */
public static $primaryMask = 'id';
/** @var bool */
public static $lowerCase = TRUE;
/** @var DibiConnection */
private $connection;
/** @var string table name */
protected $name;
/** @var string primary key name */
protected $primary;
/** @var string primary key type */
protected $primaryModifier = '%i';
/** @var bool primary key is auto increment */
protected $primaryAutoIncrement = TRUE;
/** @var array */
protected $blankRow = array();
/** @var mixed; TRUE means autodetect, or array of pairs [type, format] */
protected $types = array();
/**
* Table constructor.
* @param DibiConnection
* @return void
*/
public function __construct(DibiConnection $connection = NULL)
{
$this->connection = $connection === NULL ? dibi::getConnection() : $connection;
$this->setup();
}
/**
* Returns the table name.
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns the primary key name.
* @return string
*/
public function getPrimary()
{
return $this->primary;
}
/**
* Returns the dibi connection.
* @return DibiConnection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Setup object.
* @return void
*/
protected function setup()
{
// autodetect table name
if ($this->name === NULL) {
$name = $this->getClass();
if (FALSE !== ($pos = strrpos($name, ':'))) {
$name = substr($name, $pos + 1);
}
if (self::$lowerCase) {
$name = strtolower($name);
}
$this->name = $name;
}
// autodetect primary key name
if ($this->primary === NULL) {
$this->primary = str_replace(
array('%p', '%s'),
array($this->name, trim($this->name, 's')), // the simplest inflector in the world :-))
self::$primaryMask
);
}
}
/********************* basic commands ****************d*g**/
/**
* Inserts row into a table.
* @param array|object
* @return int new primary key
*/
public function insert($data)
{
$this->connection->query(
'INSERT INTO %n', $this->name, '%v', $this->prepare($data)
);
return $this->primaryAutoIncrement ? $this->connection->insertId() : NULL;
}
/**
* Updates rows in a table.
* @param mixed primary key value(s)
* @param array|object
* @return int number of updated rows
*/
public function update($where, $data)
{
$data = $this->prepare($data);
if ($where === NULL && isset($data[$this->primary])) {;
$where = $data[$this->primary];
unset($data[$this->primary]);
}
$this->connection->query(
'UPDATE %n', $this->name,
'SET %a', $data,
'WHERE %n', $this->primary, 'IN (' . $this->primaryModifier, $where, ')'
);
return $this->connection->affectedRows();
}
/**
* Inserts or updates rows in a table.
* @param array|object
* @return int (new) primary key
*/
public function insertOrUpdate($data)
{
$data = $this->prepare($data);
if (!isset($data[$this->primary])) {
throw new InvalidArgumentException("Missing primary key '$this->primary' in dataset.");
}
try {
$this->connection->query(
'INSERT INTO %n', $this->name, '%v', $data
);
} catch (DibiDriverException $e) {
$where = $data[$this->primary];
unset($data[$this->primary]);
$this->connection->query(
'UPDATE %n', $this->name,
'SET %a', $data,
'WHERE %n', $this->primary, 'IN (' . $this->primaryModifier, $where, ')'
);
}
}
/**
* Deletes rows from a table by primary key.
* @param mixed primary key value(s)
* @return int number of deleted rows
*/
public function delete($where)
{
$this->connection->query(
'DELETE FROM %n', $this->name,
'WHERE %n', $this->primary, 'IN (' . $this->primaryModifier, $where, ')'
);
return $this->connection->affectedRows();
}
/**
* Finds rows by primary key.
* @param mixed primary key value(s)
* @return DibiResult
*/
public function find($what)
{
if (!is_array($what)) {
$what = func_get_args();
}
return $this->complete($this->connection->query(
'SELECT * FROM %n', $this->name,
'WHERE %n', $this->primary, 'IN (' . $this->primaryModifier, $what, ')'
));
}
/**
* Selects all rows.
* @param array conditions
* @param string|array column to order by
* @return DibiResult
*/
public function findAll($conditions = NULL, $order = NULL)
{
if (!is_array($order)) {
$order = func_get_args();
if (is_array($conditions)) {
array_shift($order);
} else {
$conditions = NULL;
}
}
return $this->complete($this->connection->query(
'SELECT * FROM %n', $this->name,
'%ex', $conditions ? array('WHERE %and', $conditions) : NULL,
'%ex', $order ? array('ORDER BY %by', $order) : NULL
));
}
/**
* Fetches single row.
* @param scalar|array primary key value
* @return DibiRow
*/
public function fetch($conditions)
{
if (is_array($conditions)) {
return $this->complete($this->connection->query(
'SELECT * FROM %n', $this->name,
'WHERE %and', $conditions
))->fetch();
}
return $this->complete($this->connection->query(
'SELECT * FROM %n', $this->name,
'WHERE %n=' . $this->primaryModifier, $this->primary, $conditions
))->fetch();
}
/**
* Returns a blank row (not fetched from database).
* @return DibiRow
*/
public function createBlank()
{
$row = new DibiRow($this->blankRow, 2);
$row[$this->primary] = NULL;
return $row;
}
/**
* User data pre-processing.
* @param array|object
* @return array
*/
protected function prepare($data)
{
if (is_object($data)) {
return (array) $data;
} elseif (is_array($data)) {
return $data;
}
throw new InvalidArgumentException('Dataset must be array or anonymous object.');
}
/**
* User DibiResult post-processing.
* @param DibiResult
* @return DibiResult
*/
protected function complete($res)
{
if (is_array($this->types)) {
$res->setTypes($this->types);
} elseif ($this->types === TRUE) {
$res->detectTypes();
}
return $res;
}
/********************* fluent SQL builders ****************d*g**/
/**
* Creates fluent SQL builder.
* @return DibiFluent
*/
public function command()
{
return new DibiFluent($this->connection);
}
/**
* @param string column name
* @return DibiFluent
*/
public function select($args)
{
$args = func_get_args();
return $this->command()->__call('select', $args)->from($this->name);
}
/********************* magic fetching ****************d*g**/
/**
* Magic fetch.
* - $row = $model->fetchByUrl('about-us');
* - $arr = $model->fetchAllByCategoryIdAndVisibility(5, TRUE);
*
* @param string
* @param array
* @return DibiRow|array
*/
public function __call($name, $args)
{
if (strncmp($name, 'fetchBy', 7) === 0) { // single row
$single = TRUE;
$name = substr($name, 7);
} elseif (strncmp($name, 'fetchAllBy', 10) === 0) { // multi row
$name = substr($name, 10);
} else {
parent::__call($name, $args);
}
// ProductIdAndTitle -> array('product', 'title')
$parts = explode('_and_', strtolower(preg_replace('#(.)(?=[A-Z])#', '$1_', $name)));
if (count($parts) !== count($args)) {
throw new InvalidArgumentException("Magic fetch expects " . count($parts) . " parameters, but " . count($args) . " was given.");
}
if (isset($single)) {
return $this->complete($this->connection->query(
'SELECT * FROM %n', $this->name,
'WHERE %and', array_combine($parts, $args),
'LIMIT 1'
))->fetch();
} else {
return $this->complete($this->connection->query(
'SELECT * FROM %n', $this->name,
'WHERE %and', array_combine($parts, $args)
))->fetchAll();
}
}
}
abstract class DibiTable extends DibiTableX
{
}

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -23,11 +24,14 @@
* dibi SQL translator.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
final class DibiTranslator extends DibiObject
{
/** @var string */
public $sql;
/** @var IDibiDriver */
private $driver;
@@ -77,8 +81,7 @@ final class DibiTranslator extends DibiObject
/**
* Generates SQL.
* @param array
* @return string
* @throws DibiException
* @return bool
*/
public function translate(array $args)
{
@@ -108,7 +111,7 @@ final class DibiTranslator extends DibiObject
// simple string means SQL
if (is_string($arg)) {
// speed-up - is regexp required?
$toSkip = strcspn($arg, '`[\'":%');
$toSkip = strcspn($arg, '`[\'"%');
if (strlen($arg) === $toSkip) { // needn't be translated
$sql[] = $arg;
@@ -116,19 +119,17 @@ final class DibiTranslator extends DibiObject
$sql[] = substr($arg, 0, $toSkip)
/*
preg_replace_callback('/
(?=[`[\'":%?]) ## speed-up
(?=`|\[|\'|"|%) ## speed-up
(?:
`(.+?)`| ## 1) `identifier`
\[(.+?)\]| ## 2) [identifier]
(\')((?:\'\'|[^\'])*)\'| ## 3,4) 'string'
(\')((?:\'\'|[^\'])*)\'| ## 3,4) string
(")((?:""|[^"])*)"| ## 5,6) "string"
(\'|")| ## 7) lone quote
:(\S*?:)([a-zA-Z0-9._]?)| ## 8,9) substitution
%([a-zA-Z]{1,4})(?![a-zA-Z]) ## 10) modifier
(\?) ## 11) placeholder
(\'|") ## 7) lone-quote
%([a-zA-Z]{1,4})(?![a-zA-Z])|## 8) modifier
)/xs',
*/ // note: this can change $this->args & $this->cursor & ...
. preg_replace_callback('/(?=[`[\'":%?])(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"|(\'|")|:(\S*?:)([a-zA-Z0-9._]?)|%([a-zA-Z]{1,4})(?![a-zA-Z])|(\?))/s',
. preg_replace_callback('/(?=`|\[|\'|"|%)(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"|(\'|")|%([a-zA-Z]{1,4})(?![a-zA-Z]))/s',
array($this, 'cb'),
substr($arg, $toSkip)
);
@@ -142,10 +143,6 @@ final class DibiTranslator extends DibiObject
continue;
}
if ($arg instanceof ArrayObject) {
$arg = (array) $arg;
}
if (is_array($arg)) {
if (is_string(key($arg))) {
// associative array -> autoselect between SET or VALUES & LIST
@@ -177,16 +174,13 @@ final class DibiTranslator extends DibiObject
$sql = implode(' ', $sql);
if ($this->hasError) {
throw new DibiException('SQL translate error', 0, $sql);
}
// apply limit
if ($this->limit > -1 || $this->offset > 0) {
$this->driver->applyLimit($sql, $this->limit, $this->offset);
}
return $sql;
$this->sql = $sql;
return !$this->hasError;
}
@@ -200,105 +194,58 @@ final class DibiTranslator extends DibiObject
public function formatValue($value, $modifier)
{
// array processing (with or without modifier)
if ($value instanceof ArrayObject) {
$value = (array) $value;
}
if (is_array($value) || $value instanceof ArrayObject) {
if (is_array($value)) {
$vx = $kx = array();
$operator = ', ';
switch ($modifier) {
case 'and':
case 'or': // key=val AND key IS NULL AND ...
$operator = ' ' . strtoupper($modifier) . ' ';
if (empty($value)) {
return '1=1';
}
return '1';
foreach ($value as $k => $v) {
if (is_string($k)) {
} elseif (!is_string(key($value))) {
foreach ($value as $v) {
$vx[] = $this->formatValue($v, 'sql');
}
} else {
foreach ($value as $k => $v) {
$pair = explode('%', $k, 2); // split into identifier & modifier
$k = $this->delimite($pair[0]) . ' ';
if (!isset($pair[1])) {
$v = $this->formatValue($v, FALSE);
$vx[] = $k . ($v === 'NULL' ? 'IS ' : '= ') . $v;
} elseif ($pair[1] === 'ex') { // TODO: this will be removed
$vx[] = $k . $this->formatValue($v, 'ex');
} else {
$v = $this->formatValue($v, $pair[1]);
$vx[] = $k . ($pair[1] === 'l' ? 'IN ' : ($v === 'NULL' ? 'IS ' : '= ')) . $v;
}
} else {
$vx[] = $this->formatValue($v, 'ex');
$k = $this->delimite($pair[0]);
$v = $this->formatValue($v, isset($pair[1]) ? $pair[1] : FALSE);
$op = isset($pair[1]) && $pair[1] === 'l' ? 'IN' : ($v === 'NULL' ? 'IS' : '=');
$vx[] = $k . ' ' . $op . ' ' . $v;
}
}
return '(' . implode(') ' . strtoupper($modifier) . ' (', $vx) . ')';
case 'n': // key, key, ... identifier names
foreach ($value as $k => $v) {
if (is_string($k)) {
$vx[] = $this->delimite($k) . (empty($v) ? '' : ' AS ' . $v);
} else {
$pair = explode('%', $v, 2); // split into identifier & modifier
$vx[] = $this->delimite($pair[0]);
}
}
return implode(', ', $vx);
return implode($operator, $vx);
case 'a': // key=val, key=val, ...
foreach ($value as $k => $v) {
$pair = explode('%', $k, 2); // split into identifier & modifier
$vx[] = $this->delimite($pair[0]) . '='
. $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
. $this->formatValue($v, isset($pair[1]) ? $pair[1] : FALSE);
}
return implode(', ', $vx);
return implode($operator, $vx);
case 'l': // (val, val, ...)
foreach ($value as $k => $v) {
$pair = explode('%', $k, 2); // split into identifier & modifier
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : FALSE);
}
return '(' . ($vx ? implode(', ', $vx) : 'NULL') . ')';
return '(' . implode(', ', $vx) . ')';
case 'v': // (key, key, ...) VALUES (val, val, ...)
foreach ($value as $k => $v) {
$pair = explode('%', $k, 2); // split into identifier & modifier
$kx[] = $this->delimite($pair[0]);
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : FALSE);
}
return '(' . implode(', ', $kx) . ') VALUES (' . implode(', ', $vx) . ')';
case 'm': // (key, key, ...) VALUES (val, val, ...), (val, val, ...), ...
foreach ($value as $k => $v) {
if (is_array($v)) {
if (isset($proto)) {
if ($proto !== array_keys($v)) {
$this->hasError = TRUE;
return '**Multi-insert array "' . $k . '" is different.**';
}
} else {
$proto = array_keys($v);
}
} else {
$this->hasError = TRUE;
return '**Unexpected type ' . gettype($v) . '**';
}
$pair = explode('%', $k, 2); // split into identifier & modifier
$kx[] = $this->delimite($pair[0]);
foreach ($v as $k2 => $v2) {
$vx[$k2][] = $this->formatValue($v2, isset($pair[1]) ? $pair[1] : (is_array($v2) ? 'ex' : FALSE));
}
}
foreach ($vx as $k => $v) {
$vx[$k] = '(' . ($v ? implode(', ', $v) : 'NULL') . ')';
}
return '(' . implode(', ', $kx) . ') VALUES ' . implode(', ', $vx);
case 'by': // key ASC, key DESC
foreach ($value as $k => $v) {
if (is_string($k)) {
@@ -310,29 +257,26 @@ final class DibiTranslator extends DibiObject
}
return implode(', ', $vx);
case 'ex':
case 'sql':
$translator = new self($this->driver);
return $translator->translate($value);
default: // value, value, value - all with the same modifier
foreach ($value as $v) {
$vx[] = $this->formatValue($v, $modifier);
}
return $vx ? implode(', ', $vx) : 'NULL';
return implode(', ', $vx);
}
}
// with modifier procession
if ($modifier) {
if ($value === NULL) {
return 'NULL';
}
if ($value instanceof IDibiVariable) {
return $value->toSql($this, $modifier);
}
} elseif ($value instanceof DateTime) {
$value = $value->format('U');
} elseif ($value !== NULL && !is_scalar($value)) { // array is already processed
if (!is_scalar($value)) { // array is already processed
$this->hasError = TRUE;
return '**Unexpected type ' . gettype($value) . '**';
}
@@ -341,63 +285,48 @@ final class DibiTranslator extends DibiObject
case 's': // string
case 'bin':// binary
case 'b': // boolean
return $value === NULL ? 'NULL' : $this->driver->escape($value, $modifier);
return $this->driver->escape($value, $modifier);
case 'sn': // string or NULL
return $value == '' ? 'NULL' : $this->driver->escape($value, dibi::TEXT); // notice two equal signs
case 'in': // signed int or NULL
if ($value == '') $value = NULL;
// intentionally break omitted
return $value == '' ? 'NULL' : $this->driver->escape($value, dibi::FIELD_TEXT); // notice two equal signs
case 'i': // signed int
case 'u': // unsigned int, ignored
// support for long numbers - keep them unchanged
if (is_string($value) && preg_match('#[+-]?\d+(e\d+)?$#A', $value)) {
return $value;
} else {
return $value === NULL ? 'NULL' : (string) (int) ($value + 0);
}
return (string) (int) ($value + 0);
case 'f': // float
// support for extreme numbers - keep them unchanged
if (is_string($value) && is_numeric($value) && strpos($value, 'x') === FALSE) {
return $value; // something like -9E-005 is accepted by SQL, HEX values are not
} else {
return $value === NULL ? 'NULL' : rtrim(rtrim(number_format($value, 5, '.', ''), '0'), '.');
}
return rtrim(rtrim(number_format($value, 5, '.', ''), '0'), '.');
case 'd': // date
case 't': // datetime
if ($value === NULL) {
return 'NULL';
} else {
return $this->driver->escape(is_numeric($value) ? (int) $value : strtotime($value), $modifier);
}
return $this->driver->escape(is_string($value) ? strtotime($value) : $value, $modifier);
case 'by':
case 'n': // identifier name
return $this->delimite($value);
case 'ex':
case 'sql': // preserve as dibi-SQL (TODO: leave only %ex)
case 'sql':// preserve as SQL
$value = (string) $value;
// speed-up - is regexp required?
$toSkip = strcspn($value, '`[\'":');
$toSkip = strcspn($value, '`[\'"');
if (strlen($value) === $toSkip) { // needn't be translated
return $value;
} else {
return substr($value, 0, $toSkip)
. preg_replace_callback(
'/(?=[`[\'":])(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"|(\'|")|:(\S*?:)([a-zA-Z0-9._]?))/s',
array($this, 'cb'),
substr($value, $toSkip)
. preg_replace_callback('/(?=`|\[|\'|")(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"(\'|"))/s',
array($this, 'cb'),
substr($value, $toSkip)
);
}
case 'SQL': // preserve as real SQL (TODO: rename to %sql)
return (string) $value;
case 'and':
case 'or':
case 'a':
@@ -415,13 +344,13 @@ final class DibiTranslator extends DibiObject
// without modifier procession
if (is_string($value))
return $this->driver->escape($value, dibi::TEXT);
return $this->driver->escape($value, dibi::FIELD_TEXT);
if (is_int($value) || is_float($value))
return rtrim(rtrim(number_format($value, 5, '.', ''), '0'), '.');
if (is_bool($value))
return $this->driver->escape($value, dibi::BOOL);
return $this->driver->escape($value, dibi::FIELD_BOOL);
if ($value === NULL)
return 'NULL';
@@ -429,9 +358,6 @@ final class DibiTranslator extends DibiObject
if ($value instanceof IDibiVariable)
return $value->toSql($this, NULL);
if ($value instanceof DateTime)
return $value = $value->format('U');
$this->hasError = TRUE;
return '**Unexpected ' . gettype($value) . '**';
}
@@ -452,26 +378,10 @@ final class DibiTranslator extends DibiObject
// [5] => "
// [6] => string
// [7] => lone-quote
// [8] => substitution
// [9] => substitution flag
// [10] => modifier (when called from self::translate())
// [11] => placeholder (when called from self::translate())
// [8] => modifier (when called from self::translate())
if (!empty($matches[11])) { // placeholder
$cursor = & $this->cursor;
if ($cursor >= count($this->args)) {
$this->hasError = TRUE;
return "**Extra placeholder**";
}
$cursor++;
return $this->formatValue($this->args[$cursor - 1], FALSE);
}
if (!empty($matches[10])) { // modifier
$mod = $matches[10];
if (!empty($matches[8])) { // modifier
$mod = $matches[8];
$cursor = & $this->cursor;
if ($cursor >= count($this->args) && $mod !== 'else' && $mod !== 'end') {
@@ -540,22 +450,16 @@ final class DibiTranslator extends DibiObject
return $this->delimite($matches[2]);
if ($matches[3]) // SQL strings: '...'
return $this->driver->escape( str_replace("''", "'", $matches[4]), dibi::TEXT);
return $this->driver->escape( str_replace("''", "'", $matches[4]), dibi::FIELD_TEXT);
if ($matches[5]) // SQL strings: "..."
return $this->driver->escape( str_replace('""', '"', $matches[6]), dibi::TEXT);
return $this->driver->escape( str_replace('""', '"', $matches[6]), dibi::FIELD_TEXT);
if ($matches[7]) { // string quote
$this->hasError = TRUE;
return '**Alone quote**';
}
if ($matches[8]) { // SQL identifier substitution
$m = substr($matches[8], 0, -1);
$m = isset(dibi::$substs[$m]) ? dibi::$substs[$m] : call_user_func(dibi::$substFallBack, $m);
return $matches[9] == '' ? $this->formatValue($m, FALSE) : $m . $matches[9]; // value or identifier
}
die('this should be never executed');
}
@@ -568,27 +472,8 @@ final class DibiTranslator extends DibiObject
*/
private function delimite($value)
{
if ($value === '*') {
return '*';
} elseif (strpos($value, ':') !== FALSE) { // provide substitution
$value = preg_replace_callback('#:(.*):#U', array(__CLASS__, 'subCb'), $value);
}
return $this->driver->escape($value, dibi::IDENTIFIER);
return $this->driver->escape(dibi::substitute($value), dibi::IDENTIFIER);
}
/**
* Substitution callback.
* @param array
* @return string
*/
private static function subCb($m)
{
$m = $m[1];
return isset(dibi::$substs[$m]) ? dibi::$substs[$m] : call_user_func(dibi::$substFallBack, $m);
}
}
} // class DibiTranslator

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/

View File

@@ -4,17 +4,18 @@
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
* Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
* Copyright (c) 2005, 2008 David Grudl (http://davidgrudl.com)
*
* This source file is subject to the "dibi license" that is bundled
* with this package in the file license.txt.
*
* For more information please see http://dibiphp.com
*
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
* @version $Id$
*/
@@ -107,7 +108,7 @@ interface IDibiProfiler
* dibi driver interface.
*
* @author David Grudl
* @copyright Copyright (c) 2005, 2009 David Grudl
* @copyright Copyright (c) 2005, 2008 David Grudl
* @package dibi
*/
interface IDibiDriver
@@ -121,6 +122,8 @@ interface IDibiDriver
*/
function connect(array &$config);
/**
* Disconnects from a database.
* @return void
@@ -128,6 +131,8 @@ interface IDibiDriver
*/
function disconnect();
/**
* Internal: Executes the SQL query.
* @param string SQL statement.
@@ -136,41 +141,50 @@ interface IDibiDriver
*/
function query($sql);
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int|FALSE number of rows or FALSE on error
*/
function getAffectedRows();
function affectedRows();
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @return int|FALSE int on success or FALSE on failure
*/
function getInsertId($sequence);
function insertId($sequence);
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
function begin($savepoint = NULL);
function begin();
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
function commit($savepoint = NULL);
function commit();
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
*/
function rollback($savepoint = NULL);
function rollback();
/**
* Returns the connection resource.
@@ -185,23 +199,27 @@ interface IDibiDriver
/**
* Encodes data for use in a SQL statement.
* Encodes data for use in an SQL statement.
* @param string value
* @param string type (dibi::TEXT, dibi::BOOL, ...)
* @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...)
* @return string encoded value
* @throws InvalidArgumentException
*/
function escape($value, $type);
/**
* Decodes data from result set.
* @param string value
* @param string type (dibi::BINARY)
* @param string type (dibi::FIELD_BINARY)
* @return string decoded value
* @throws InvalidArgumentException
*/
function unescape($value, $type);
/**
* Injects LIMIT/OFFSET to the SQL query.
* @param string &$sql The SQL query that will be modified.
@@ -221,7 +239,9 @@ interface IDibiDriver
* Returns the number of rows in a result set.
* @return int
*/
function getRowCount();
function rowCount();
/**
* Moves cursor position without fetching row.
@@ -231,6 +251,8 @@ interface IDibiDriver
*/
function seek($row);
/**
* Fetches the row at current position and moves the internal cursor to the next position.
* @param bool TRUE for associative array, FALSE for numeric
@@ -239,6 +261,8 @@ interface IDibiDriver
*/
function fetch($type);
/**
* Frees the resources allocated for this result set.
* @param resource result set resource
@@ -246,6 +270,8 @@ interface IDibiDriver
*/
function free();
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -253,6 +279,8 @@ interface IDibiDriver
*/
function getColumnsMeta();
/**
* Returns the result set resource.
* @return mixed
@@ -271,6 +299,8 @@ interface IDibiDriver
*/
function getTables();
/**
* Returns metadata for all columns in a table.
* @param string
@@ -278,6 +308,8 @@ interface IDibiDriver
*/
function getColumns($table);
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -285,6 +317,8 @@ interface IDibiDriver
*/
function getIndexes($table);
/**
* Returns metadata for all foreign keys in a table.
* @param string

3
examples/.gitignore vendored
View File

@@ -1,3 +0,0 @@
_test.bat
ref
output

File diff suppressed because it is too large Load Diff

View File

@@ -1 +0,0 @@
Disallow: /

View File

@@ -4,6 +4,8 @@
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
// required since PHP 5.1.0
date_default_timezone_set('Europe/Prague');

101
examples/dibi.table.php Normal file
View File

@@ -0,0 +1,101 @@
<h1>DibiTableX demo</h1>
<pre>
<?php
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'sample.sdb',
));
dibi::begin();
// autodetection: primary keys are customer_id, order_id, ...
DibiTableX::$primaryMask = '%s_id';
// table products
class Products extends DibiTableX
{
// rely on autodetection...
// protected $name = 'products';
// protected $primary = 'product_id';
}
// create table object
$products = new Products;
echo "Table name: $products->name\n";
echo "Primary key: $products->primary\n";
// Finds rows by primary key
foreach ($products->find(1, 3) as $row) {
Debug::dump($row);
}
// select all
$products->findAll()->dump();
// select all, order by title, product_id
$products->findAll('title', $products->primary)->dump();
$products->findAll(array('title' => 'Chair'), 'title')->dump();
// fetches single row with id 3
$row = $products->fetch(3);
// deletes row from a table
$count = $products->delete(1);
// deletes multiple rows
$count = $products->delete(array(1, 2, 3));
Debug::dump($count); // number of deleted rows
// update row #2 in a table
$data = (object) NULL;
$data->title = 'New title';
$count = $products->update(2, $data);
Debug::dump($count); // number of updated rows
// update multiple rows in a table
$count = $products->update(array(3, 5), $data);
Debug::dump($count); // number of updated rows
// inserts row into a table
$data = array();
$data['title'] = 'New product';
$id = $products->insert($data);
Debug::dump($id); // generated id
// inserts or updates row into a table
$data = array();
$data['title'] = 'New product';
$data[$products->primary] = 5;
$products->insertOrUpdate($data);
// is absolutely SQL injection safe
$key = '3 OR 1=1';
$products->delete($key);
// --> DELETE FROM [products] WHERE [product_id] IN ( 3 )
// select all using fluent interface
Debug::dump($products->select('*')->orderBy('title')->fetchAll());

View File

@@ -4,8 +4,6 @@
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
dibi::connect(array(
'driver' => 'sqlite',

View File

@@ -4,8 +4,6 @@
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
dibi::connect(array(
'driver' => 'sqlite',

View File

@@ -5,8 +5,6 @@
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
dibi::connect(array(
'driver' => 'sqlite',
@@ -17,8 +15,8 @@ dibi::connect(array(
$res = dibi::query('SELECT * FROM [customers]');
// auto-converts this column to integer
$res->setType('customer_id', Dibi::INTEGER);
$res->setType('added', Dibi::DATETIME, 'H:i j.n.Y');
$res->setType('customer_id', Dibi::FIELD_INTEGER);
$res->setType('added', Dibi::FIELD_DATETIME, 'H:i j.n.Y');
$row = $res->fetch();
Debug::dump($row);

View File

@@ -1,7 +1,7 @@
<h1>Nette\Debug & dibi example</h1>
<h1>Nette::Debug & dibi example</h1>
<p>Dibi can display and log exceptions via Nette\Debug, part of Nette Framework.</p>
<p>Dibi can display and log exceptions via Nette::Debug, part of Nette Framework.</p>
<ul>
<li>Nette Framework: http://nettephp.com
@@ -13,7 +13,7 @@ require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
// enable Nette\Debug
// enable Nette::Debug
Debug::enable();

View File

@@ -1,28 +0,0 @@
<h1>Nette\Debug & dibi example 2</h1>
<p>Dibi can dump variables via Nette\Debug, part of Nette Framework.</p>
<ul>
<li>Nette Framework: http://nettephp.com
</ul>
<?php
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
// enable Nette\Debug
Debug::enable();
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'sample.sdb',
));
// throws error
Debug::consoleDump( dibi::fetchAll('SELECT * FROM [customers] WHERE [customer_id] < %i', 38), '[customers]' );

Binary file not shown.

Binary file not shown.

View File

@@ -8,6 +8,7 @@ pre.dibi { padding-bottom: 10px; }
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
// required since PHP 5.1.0
date_default_timezone_set('Europe/Prague');

View File

@@ -16,8 +16,8 @@ dibi::connect(array(
// create new substitution :blog: ==> wp_
dibi::addSubst('blog', 'wp_');
dibi::test("UPDATE :blog:items SET [text]='Hello World'");
// -> UPDATE wp_items SET [text]='Hello World'
dibi::test("UPDATE [:blog:items] SET [text]='Hello World'");
// -> UPDATE [wp_items] SET [text]='Hello World'
@@ -36,14 +36,10 @@ dibi::test("UPDATE [database.::table] SET [text]='Hello World'");
// create substitution fallback
function substFallBack($expr)
{
if (defined($expr)) {
return constant($expr);
} else {
return 'the_' . $expr;
}
return 'the_' . $expr;
}
dibi::setSubstFallBack('substFallBack');
dibi::test("UPDATE [:account:user] SET [name]='John Doe', [active]=:true:");
// -> UPDATE [the_accountuser] SET [name]='John Doe', [active]=1
dibi::test("UPDATE [:account:user] SET [name]='John Doe'");
// -> UPDATE [the_accountuser] SET [name]='John Doe'

View File

@@ -1,4 +1,4 @@
Dibi (c) David Grudl, 2005-2009 (http://davidgrudl.com)
Dibi (c) David Grudl, 2005-2008 (http://davidgrudl.com)
@@ -25,8 +25,8 @@ http://dibiphp.com
Dibi.minified
-------------
Dibi.compact
------------
This is shrinked single-file version of whole Dibi, useful when you don't
want to modify library, but just use it.

View File

@@ -1 +1 @@
Dibi 1.1 (revision $WCREV$ released on $WCDATE$)
Dibi 1.0 (revision $WCREV$ released on $WCDATE$)