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

675 lines
14 KiB
PHP
Raw Normal View History

2008-07-17 03:51:29 +00:00
<?php
/**
* dibi - tiny'n'smart database abstraction layer
* ----------------------------------------------
*
2010-01-03 15:15:37 +01:00
* @copyright Copyright (c) 2005, 2010 David Grudl
2008-07-17 03:51:29 +00:00
* @license http://dibiphp.com/license dibi license
* @link http://dibiphp.com
* @package dibi
*/
/**
* dibi connection.
*
2010-01-03 15:15:37 +01:00
* @copyright Copyright (c) 2005, 2010 David Grudl
2008-07-17 03:51:29 +00:00
* @package dibi
2010-04-22 12:12:11 +02:00
*
* @property-read bool $connected
* @property-read mixed $config
* @property-read IDibiDriver $driver
* @property-read int $affectedRows
* @property-read int $insertId
* @property IDibiProfiler $profiler
* @property-read DibiDatabaseInfo $databaseInfo
2008-07-17 03:51:29 +00:00
*/
class DibiConnection extends DibiObject
2008-07-17 03:51:29 +00:00
{
2008-10-28 15:24:47 +00:00
/** @var array Current connection configuration */
2008-07-17 03:51:29 +00:00
private $config;
2010-08-03 02:43:37 +02:00
/** @var IDibiDriver */
2008-07-17 03:51:29 +00:00
private $driver;
2010-08-03 02:43:37 +02:00
/** @var DibiTranslator */
private $translator;
2010-08-03 02:43:37 +02:00
/** @var IDibiProfiler */
private $profiler;
2008-10-28 15:24:47 +00:00
/** @var bool Is connected? */
2008-07-17 03:51:29 +00:00
private $connected = FALSE;
/**
* Creates object and (optionally) connects to a database.
* @param mixed connection parameters
* @param string connection name
2008-07-17 03:51:29 +00:00
* @throws DibiException
*/
public function __construct($config, $name = NULL)
{
// DSN string
if (is_string($config)) {
parse_str($config, $config);
} elseif ($config instanceof Traversable) {
$tmp = array();
foreach ($config as $key => $val) {
$tmp[$key] = $val instanceof Traversable ? iterator_to_array($val) : $val;
}
$config = $tmp;
2008-07-17 03:51:29 +00:00
} elseif (!is_array($config)) {
throw new InvalidArgumentException('Configuration must be array, string or object.');
2008-07-17 03:51:29 +00:00
}
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'host', 'hostname');
self::alias($config, 'result|detectTypes', 'resultDetectTypes'); // back compatibility
self::alias($config, 'result|formatDateTime', 'resultDateTime');
2008-07-17 03:51:29 +00:00
if (!isset($config['driver'])) {
$config['driver'] = dibi::$defaultDriver;
}
$driver = preg_replace('#[^a-z0-9_]#', '_', strtolower($config['driver']));
2008-07-17 03:51:29 +00:00
$class = "Dibi" . $driver . "Driver";
if (!class_exists($class, FALSE)) {
include_once dirname(__FILE__) . "/../drivers/$driver.php";
2008-07-17 03:51:29 +00:00
if (!class_exists($class, FALSE)) {
throw new DibiException("Unable to create instance of dibi driver '$class'.");
2008-07-17 03:51:29 +00:00
}
}
$config['name'] = $name;
$this->config = $config;
$this->driver = new $class;
$this->translator = new DibiTranslator($this->driver);
2008-07-17 03:51:29 +00:00
// profiler
$profilerCfg = & $config['profiler'];
if (is_scalar($profilerCfg)) { // back compatibility
$profilerCfg = array(
'run' => (bool) $profilerCfg,
'class' => strlen($profilerCfg) > 1 ? $profilerCfg : NULL,
);
}
if (!empty($profilerCfg['run'])) {
$class = isset($profilerCfg['class']) ? $profilerCfg['class'] : 'DibiProfiler';
if (!class_exists($class)) {
throw new DibiException("Unable to create instance of dibi profiler '$class'.");
}
$this->setProfiler(new $class($profilerCfg));
}
if (!empty($config['substitutes'])) {
foreach ($config['substitutes'] as $key => $value) {
dibi::addSubst($key, $value);
}
}
2008-07-17 03:51:29 +00:00
if (empty($config['lazy'])) {
$this->connect();
}
}
/**
* Automatically frees the resources allocated for this result set.
* @return void
*/
public function __destruct()
{
// disconnects and rolls back transaction - do not rely on auto-disconnect and rollback!
$this->connected && $this->disconnect();
2008-07-17 03:51:29 +00:00
}
/**
* Connects to a database.
* @return void
*/
2010-06-18 18:59:29 +08:00
final public function connect()
2008-07-17 03:51:29 +00:00
{
if ($this->profiler !== NULL) {
$ticket = $this->profiler->before($this, IDibiProfiler::CONNECT);
}
$this->driver->connect($this->config);
$this->connected = TRUE;
if (isset($ticket)) {
$this->profiler->after($ticket);
2008-07-17 03:51:29 +00:00
}
}
/**
* Disconnects from a database.
* @return void
*/
final public function disconnect()
{
$this->driver->disconnect();
$this->connected = FALSE;
2008-07-17 03:51:29 +00:00
}
/**
* Returns TRUE when connection was established.
* @return bool
*/
final public function isConnected()
{
return $this->connected;
}
/**
* Returns configuration variable. If no $key is passed, returns the entire array.
* @see self::__construct
* @param string
* @param mixed default value to use if key not found
* @return mixed
*/
final public function getConfig($key = NULL, $default = NULL)
{
if ($key === NULL) {
return $this->config;
} elseif (isset($this->config[$key])) {
return $this->config[$key];
} else {
return $default;
}
}
/**
* Apply configuration alias or default values.
* @param array connect configuration
* @param string key
* @param string alias key
* @return void
*/
2010-05-19 15:29:38 +02:00
public static function alias(&$config, $key, $alias)
2008-07-17 03:51:29 +00:00
{
2010-05-19 15:29:38 +02:00
$foo = & $config;
foreach (explode('|', $key) as $key) $foo = & $foo[$key];
2008-07-17 03:51:29 +00:00
2010-05-19 15:29:38 +02:00
if (!isset($foo) && isset($config[$alias])) {
$foo = $config[$alias];
2008-07-17 03:51:29 +00:00
unset($config[$alias]);
}
}
/**
* Returns the driver and connects to a database in lazy mode.
* @return IDibiDriver
*/
final public function getDriver()
{
$this->connected || $this->connect();
return $this->driver;
}
2008-07-17 03:51:29 +00:00
/**
* Generates (translates) and executes SQL query.
* @param array|mixed one or more arguments
* @return DibiResult|int result set object (if any)
2008-07-17 03:51:29 +00:00
* @throws DibiException
*/
final public function query($args)
{
$this->connected || $this->connect();
2008-07-17 03:51:29 +00:00
$args = func_get_args();
return $this->nativeQuery($this->translator->translate($args));
2008-07-17 03:51:29 +00:00
}
/**
* Generates and returns SQL query.
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
*/
final public function sql($args)
{
$this->connected || $this->connect();
$args = func_get_args();
return $this->translator->translate($args);
}
2008-07-17 03:51:29 +00:00
/**
* Generates and prints SQL query.
* @param array|mixed one or more arguments
* @return bool
*/
final public function test($args)
{
$this->connected || $this->connect();
2008-07-17 03:51:29 +00:00
$args = func_get_args();
try {
dibi::dump($this->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)
{
$this->connected || $this->connect();
$args = func_get_args();
return new DibiDataSource($this->translator->translate($args), $this);
2008-07-17 03:51:29 +00:00
}
/**
* Executes the SQL query.
* @param string SQL statement.
* @return DibiResult|int result set object (if any)
2008-07-17 03:51:29 +00:00
* @throws DibiException
*/
final public function nativeQuery($sql)
{
$this->connected || $this->connect();
2008-07-17 03:51:29 +00:00
if ($this->profiler !== NULL) {
$event = IDibiProfiler::QUERY;
if (preg_match('#\s*(SELECT|UPDATE|INSERT|DELETE)#i', $sql, $matches)) {
static $events = array(
'SELECT' => IDibiProfiler::SELECT, 'UPDATE' => IDibiProfiler::UPDATE,
'INSERT' => IDibiProfiler::INSERT, 'DELETE' => IDibiProfiler::DELETE,
);
$event = $events[strtoupper($matches[1])];
}
$ticket = $this->profiler->before($this, $event, $sql);
}
2008-07-17 03:51:29 +00:00
dibi::$sql = $sql;
2008-07-17 03:51:29 +00:00
if ($res = $this->driver->query($sql)) { // intentionally =
$res = new DibiResult($res, $this->config['result']);
} else {
$res = $this->driver->getAffectedRows();
2008-07-17 03:51:29 +00:00
}
if (isset($ticket)) {
$this->profiler->after($ticket, $res);
}
2008-07-17 03:51:29 +00:00
return $res;
}
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int number of rows
* @throws DibiException
*/
public function getAffectedRows()
2008-07-17 03:51:29 +00:00
{
$this->connected || $this->connect();
$rows = $this->driver->getAffectedRows();
2008-07-17 03:51:29 +00:00
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();
}
2008-07-17 03:51:29 +00:00
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @param string optional sequence name
* @return int
* @throws DibiException
*/
public function getInsertId($sequence = NULL)
2008-07-17 03:51:29 +00:00
{
$this->connected || $this->connect();
$id = $this->driver->getInsertId($sequence);
2008-07-17 03:51:29 +00:00
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);
}
2008-07-17 03:51:29 +00:00
/**
* Begins a transaction (if supported).
2009-06-30 14:08:49 +00:00
* @param string optional savepoint name
2008-07-17 03:51:29 +00:00
* @return void
*/
2008-11-17 16:17:16 +00:00
public function begin($savepoint = NULL)
2008-07-17 03:51:29 +00:00
{
$this->connected || $this->connect();
if ($this->profiler !== NULL) {
2008-11-17 16:17:16 +00:00
$ticket = $this->profiler->before($this, IDibiProfiler::BEGIN, $savepoint);
}
2008-11-17 16:17:16 +00:00
$this->driver->begin($savepoint);
if (isset($ticket)) {
$this->profiler->after($ticket);
}
2008-07-17 03:51:29 +00:00
}
/**
* Commits statements in a transaction.
2009-06-30 14:08:49 +00:00
* @param string optional savepoint name
2008-07-17 03:51:29 +00:00
* @return void
*/
2008-11-17 16:17:16 +00:00
public function commit($savepoint = NULL)
2008-07-17 03:51:29 +00:00
{
$this->connected || $this->connect();
if ($this->profiler !== NULL) {
2008-11-17 16:17:16 +00:00
$ticket = $this->profiler->before($this, IDibiProfiler::COMMIT, $savepoint);
}
2008-11-17 16:17:16 +00:00
$this->driver->commit($savepoint);
if (isset($ticket)) {
$this->profiler->after($ticket);
}
2008-07-17 03:51:29 +00:00
}
/**
* Rollback changes in a transaction.
2009-06-30 14:08:49 +00:00
* @param string optional savepoint name
2008-07-17 03:51:29 +00:00
* @return void
*/
2008-11-17 16:17:16 +00:00
public function rollback($savepoint = NULL)
2008-07-17 03:51:29 +00:00
{
$this->connected || $this->connect();
if ($this->profiler !== NULL) {
2008-11-17 16:17:16 +00:00
$ticket = $this->profiler->before($this, IDibiProfiler::ROLLBACK, $savepoint);
}
2008-11-17 16:17:16 +00:00
$this->driver->rollback($savepoint);
if (isset($ticket)) {
$this->profiler->after($ticket);
}
2008-07-17 03:51:29 +00:00
}
/********************* fluent SQL builders ****************d*g**/
/**
* @return DibiFluent
*/
public function command()
{
return new DibiFluent($this);
}
/**
* @param string column name
* @return DibiFluent
*/
public function select($args)
{
$args = func_get_args();
return $this->command()->__call('select', $args);
}
/**
* @param string table
* @param array
* @return DibiFluent
*/
public function update($table, $args)
{
if (!(is_array($args) || $args instanceof Traversable)) {
throw new InvalidArgumentException('Arguments must be array or Traversable.');
}
return $this->command()->update('%n', $table)->set($args);
}
/**
* @param string table
* @param array
* @return DibiFluent
*/
public function insert($table, $args)
{
if ($args instanceof Traversable) {
$args = iterator_to_array($args);
} elseif (!is_array($args)) {
throw new InvalidArgumentException('Arguments must be array or Traversable.');
}
return $this->command()->insert()
->into('%n', $table, '(%n)', array_keys($args))->values('%l', $args);
}
/**
* @param string table
* @return DibiFluent
*/
public function delete($table)
{
return $this->command()->delete()->from('%n', $table);
}
/********************* profiler ****************d*g**/
/**
* @param IDibiProfiler
* @return DibiConnection provides a fluent interface
*/
public function setProfiler(IDibiProfiler $profiler = NULL)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return IDibiProfiler
*/
public function getProfiler()
{
return $this->profiler;
}
/********************* 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**/
2008-07-17 03:51:29 +00:00
/**
* Import SQL dump from file - extreme fast!
* @param string filename
* @return int count of sql commands
*/
public function loadFile($file)
{
$this->connected || $this->connect();
2008-07-17 03:51:29 +00:00
@set_time_limit(0); // intentionally @
$handle = @fopen($file, 'r'); // intentionally @
if (!$handle) {
throw new FileNotFoundException("Cannot open file '$file'.");
}
$count = 0;
$sql = '';
while (!feof($handle)) {
$s = fgets($handle);
$sql .= $s;
if (substr(rtrim($s), -1) === ';') {
$this->driver->query($sql);
$sql = '';
$count++;
}
}
fclose($handle);
return $count;
}
/**
* Gets a information about the current database.
* @return DibiDatabaseInfo
2008-07-17 03:51:29 +00:00
*/
public function getDatabaseInfo()
2008-07-17 03:51:29 +00:00
{
if (!($this->driver instanceof IDibiReflector)) {
throw new NotSupportedException('Driver '. get_class($this->driver) . ' has not reflection capabilities.');
}
$this->connected || $this->connect();
return new DibiDatabaseInfo($this->driver, isset($this->config['database']) ? $this->config['database'] : NULL);
2008-07-17 03:51:29 +00:00
}
/**
* Prevents unserialization.
*/
public function __wakeup()
{
throw new NotSupportedException('You cannot serialize or unserialize ' . $this->getClass() . ' instances.');
}
/**
* Prevents serialization.
*/
public function __sleep()
{
throw new NotSupportedException('You cannot serialize or unserialize ' . $this->getClass() . ' instances.');
}
}