1
0
mirror of synced 2024-12-13 22:56:04 +03:00
doctrine2/lib/Doctrine/Db.php

632 lines
18 KiB
PHP
Raw Normal View History

2006-05-30 12:42:10 +04:00
<?php
2006-08-23 00:14:29 +04:00
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.phpdoctrine.com>.
*/
/**
* Doctrine_Db
* A thin wrapper layer on top of PDO / Doctrine_Adapter
*
2006-11-13 21:16:10 +03:00
* Doctrine_Db provides the following things to underlying database hanlder
*
2006-11-13 21:16:10 +03:00
* 1. Event listeners
* An easy to use, pluggable eventlistener architecture. Aspects such as
* logging, query profiling and caching can be easily implemented through
* the use of these listeners
*
2006-11-13 21:16:10 +03:00
* 2. Lazy-connecting
* Creating an instance of Doctrine_Db does not connect
* to database. Connecting to database is only invoked when actually needed
* (for example when query() is being called)
*
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @package Doctrine
* @category Object Relational Mapping
* @link www.phpdoctrine.com
* @since 1.0
* @version $Revision$
*/
2006-12-29 17:40:47 +03:00
class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Interface
{
/**
* @var array $instances all the instances of this class
*/
protected static $instances = array();
2006-05-30 12:42:10 +04:00
/**
* @var array $isConnected whether or not a connection has been established
2006-05-30 12:42:10 +04:00
*/
protected $isConnected = false;
2006-05-30 12:42:10 +04:00
/**
* @var PDO $dbh the database handler
2006-05-30 12:42:10 +04:00
*/
protected $dbh;
2006-05-30 12:42:10 +04:00
/**
* @var array $options
2006-05-30 12:42:10 +04:00
*/
protected $options = array('dsn' => null,
'username' => null,
'password' => null,
);
/**
* @var array $pendingAttributes An array of pending attributes. When setting attributes
* no connection is needed. When connected all the pending
* attributes are passed to the underlying PDO instance.
*/
protected $pendingAttributes = array();
/**
2006-12-29 17:01:31 +03:00
* @var Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener
* listener for listening events
*/
protected $listener;
/**
* @var string $name name of this connection
* @see Doctrine_Manager::openConnection()
*/
protected $name;
2007-02-05 15:04:56 +03:00
protected $count = 0;
private static $driverMap = array('oracle' => 'oci8',
'postgres' => 'pgsql',
'oci' => 'oci8',
'sqlite2' => 'sqlite',
'sqlite3' => 'sqlite');
2006-05-30 12:42:10 +04:00
/**
* constructor
*
* @param string $dsn data source name
* @param string $user database username
* @param string $pass database password
2006-05-30 12:42:10 +04:00
*/
2007-01-01 20:47:04 +03:00
public function __construct($dsn, $user = null, $pass = null)
2006-12-29 17:40:47 +03:00
{
2007-01-12 02:57:30 +03:00
// check if dsn is PEAR-like or not
if ( ! isset($user) || strpos($dsn, '://')) {
$a = self::parseDSN($dsn);
extract($a);
} else {
$e = explode(':', $dsn);
if($e[0] == 'uri') {
$e[0] = 'odbc';
}
$this->pendingAttributes[Doctrine::ATTR_DRIVER_NAME] = $e[0];
}
$this->options['dsn'] = $dsn;
$this->options['username'] = $user;
$this->options['password'] = $pass;
$this->listener = new Doctrine_Db_EventListener();
2006-05-30 12:42:10 +04:00
}
2007-02-05 15:04:56 +03:00
public function incrementQueryCount()
2006-12-29 17:40:47 +03:00
{
2007-02-05 15:04:56 +03:00
$this->count++;
}
/**
2007-02-05 15:04:56 +03:00
* getDbh
*/
2007-02-05 15:04:56 +03:00
public function getDbh()
2006-12-29 17:40:47 +03:00
{
2007-02-05 15:04:56 +03:00
return $this->dbh;
}
/**
2007-02-05 15:04:56 +03:00
* getAdapter
*
* @return Doctrine_Adapter_Interface|PDO $adapter
*/
2007-02-05 15:04:56 +03:00
public function getAdapter()
2006-12-29 17:40:47 +03:00
{
return $this->dbh;
}
/**
* setAdapter
*
* @param Doctrine_Adapter_Interface|PDO $adapter
* @return void
*/
public function setAdapter($adapter)
{
$this->dbh = $adapter;
}
/**
* setName
* this method should only be used by doctrine internally and
* also for testing purposes
*
* @param string $name connection name
* @return void
*/
public function setName($name)
{
$this->name = $name;
}
/**
* getName
*
* @return string the name of the associated connection
*/
public function getName()
{
return $this->name;
}
2006-12-29 17:40:47 +03:00
public function getOption($name)
{
2006-12-29 17:01:31 +03:00
if ( ! array_key_exists($name, $this->options)) {
throw new Doctrine_Db_Exception('Unknown option ' . $name);
2006-12-29 17:01:31 +03:00
}
return $this->options[$name];
2006-05-30 12:42:10 +04:00
}
/**
* addListener
*
* @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener
* @return Doctrine_Db
*/
2006-12-29 17:40:47 +03:00
public function addListener($listener, $name = null)
{
2006-12-29 17:01:31 +03:00
if ( ! ($this->listener instanceof Doctrine_Db_EventListener_Chain)) {
$this->listener = new Doctrine_Db_EventListener_Chain();
2006-12-29 17:01:31 +03:00
}
$this->listener->add($listener, $name);
2006-12-29 17:01:31 +03:00
return $this;
}
/**
* getListener
2006-12-29 17:01:31 +03:00
*
* @return Doctrine_Db_EventListener_Interface|Doctrine_Overloadable
*/
2006-12-29 17:40:47 +03:00
public function getListener()
{
return $this->listener;
}
2006-05-30 12:42:10 +04:00
/**
* setListener
*
* @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener
* @return Doctrine_Db
2006-05-30 12:42:10 +04:00
*/
2006-12-29 17:40:47 +03:00
public function setListener($listener)
{
2006-12-29 17:01:31 +03:00
if ( ! ($listener instanceof Doctrine_Db_EventListener_Interface)
&& ! ($listener instanceof Doctrine_Overloadable)
) {
throw new Doctrine_Db_Exception("Couldn't set eventlistener for database handler. EventListeners should implement either Doctrine_Db_EventListener_Interface or Doctrine_Overloadable");
2006-12-29 17:01:31 +03:00
}
$this->listener = $listener;
2006-05-30 12:42:10 +04:00
return $this;
}
/**
* connect
* connects into database
*
* @return boolean
*/
2006-12-29 17:40:47 +03:00
public function connect()
{
2006-12-29 17:01:31 +03:00
if ($this->isConnected)
return false;
2007-01-16 22:16:04 +03:00
$event = new Doctrine_Db_Event($this, Doctrine_Db_Event::CONNECT);
$this->listener->onPreConnect($event);
$e = explode(':', $this->options['dsn']);
$found = false;
if (extension_loaded('pdo')) {
if (in_array($e[0], PDO::getAvailableDrivers())) {
$this->dbh = new PDO($this->options['dsn'], $this->options['username'], $this->options['password']);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$this->dbh->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('Doctrine_Db_Statement', array($this)));
$found = true;
}
}
if ( ! $found) {
$class = 'Doctrine_Adapter_' . ucwords($e[0]);
if (class_exists($class)) {
$this->dbh = new $class($this->options['dsn'], $this->options['username'], $this->options['password']);
} else {
throw new Doctrine_Db_Exception("Couldn't locate driver named " . $e[0]);
}
}
foreach($this->pendingAttributes as $attr => $value) {
2007-01-16 20:59:35 +03:00
// some drivers don't support setting this so we just skip it
if($attr == Doctrine::ATTR_DRIVER_NAME) {
2007-01-16 20:59:35 +03:00
continue;
}
$this->dbh->setAttribute($attr, $value);
}
$this->isConnected = true;
2007-01-16 22:16:04 +03:00
$this->listener->onConnect($event);
return true;
}
/**
* getConnection
*
* @param string $dsn PEAR::DB like DSN or PDO like DSN
* format for PEAR::DB like DSN: schema://user:password@address/dbname
*
* @return
*/
2006-12-29 17:40:47 +03:00
public static function getConnection($dsn = null, $username = null, $password = null)
{
return new self($dsn, $username, $password);
}
/**
* driverName
2006-12-29 17:01:31 +03:00
* converts a driver name like (oracle) to appropriate PDO
* driver name (oci8 in the case of oracle)
*
* @param string $name
* @return string
*/
2006-12-29 17:40:47 +03:00
public static function driverName($name)
{
2006-12-29 17:01:31 +03:00
if (isset(self::$driverMap[$name])) {
return self::$driverMap[$name];
2006-12-29 17:01:31 +03:00
}
return $name;
}
/**
* parseDSN
*
2006-12-29 17:01:31 +03:00
* @param string $dsn
* @return array Parsed contents of DSN
*/
public function parseDSN($dsn)
2006-12-29 17:40:47 +03:00
{
// silence any warnings
2006-12-29 17:01:31 +03:00
$parts = @parse_url($dsn);
$names = array('scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment');
2006-12-29 17:01:31 +03:00
foreach ($names as $name) {
if ( ! isset($parts[$name])) {
$parts[$name] = null;
2006-12-29 17:01:31 +03:00
}
2006-05-30 12:42:10 +04:00
}
2006-12-29 17:01:31 +03:00
if (count($parts) == 0 || ! isset($parts['scheme'])) {
throw new Doctrine_Db_Exception('Empty data source name');
}
$drivers = self::getAvailableDrivers();
$parts['scheme'] = self::driverName($parts['scheme']);
2007-01-16 22:34:47 +03:00
/**
2006-12-29 17:01:31 +03:00
if ( ! in_array($parts['scheme'], $drivers)) {
throw new Doctrine_Db_Exception('Driver '.$parts['scheme'].' not availible or extension not loaded');
2006-12-29 17:01:31 +03:00
}
2007-01-16 22:34:47 +03:00
*/
2006-12-29 17:01:31 +03:00
switch ($parts['scheme']) {
case 'sqlite':
if (isset($parts['host']) && $parts['host'] == ':memory') {
$parts['database'] = ':memory:';
$parts['dsn'] = 'sqlite::memory:';
}
2006-12-30 00:46:14 +03:00
break;
case 'mysql':
case 'informix':
case 'oci8':
case 'mssql':
case 'firebird':
2007-03-14 22:57:38 +03:00
case 'dblib':
case 'pgsql':
case 'odbc':
2007-01-16 22:41:39 +03:00
case 'mock':
2007-04-18 02:16:11 +04:00
case 'oracle':
if ( ! isset($parts['path']) || $parts['path'] == '/') {
throw new Doctrine_Db_Exception('No database availible in data source name');
}
if (isset($parts['path'])) {
$parts['database'] = substr($parts['path'], 1);
}
if ( ! isset($parts['host'])) {
throw new Doctrine_Db_Exception('No hostname set in data source name');
}
2007-04-18 02:16:11 +04:00
if (isset(self::$driverMap[$parts['scheme']])) {
$parts['scheme'] = self::$driverMap[$parts['scheme']];
}
$parts['dsn'] = $parts['scheme'] . ':host='
. $parts['host'] . ';dbname='
. $parts['database'];
2007-04-04 01:28:06 +04:00
if (isset($parts['port'])) {
// append port to dsn if supplied
$parts['dsn'] .= ';port=' . $parts['port'];
}
break;
default:
throw new Doctrine_Db_Exception('Unknown driver '.$parts['scheme']);
2006-12-29 17:01:31 +03:00
}
$this->pendingAttributes[PDO::ATTR_DRIVER_NAME] = $parts['scheme'];
2006-12-29 17:01:31 +03:00
return $parts;
}
/**
* clear
* clears all instances from the memory
*
* @return void
*/
2006-12-29 17:40:47 +03:00
public static function clear()
{
self::$instances = array();
}
/**
* errorCode
* Fetch the SQLSTATE associated with the last operation on the database handle
*
* @return integer
*/
2006-12-29 17:40:47 +03:00
public function errorCode()
{
return $this->dbh->errorCode();
2006-05-30 12:42:10 +04:00
}
/**
* errorInfo
* Fetch extended error information associated with the last operation on the database handle
*
* @return array
2006-05-30 12:42:10 +04:00
*/
2006-12-29 17:40:47 +03:00
public function errorInfo()
{
return $this->dbh->errorInfo();
}
/**
* prepare
*
* @param string $statement
*/
2006-12-29 17:40:47 +03:00
public function prepare($statement)
{
$this->connect();
2006-05-30 12:42:10 +04:00
$event = new Doctrine_Db_Event($this, Doctrine_Db_Event::PREPARE, $statement);
2006-05-30 12:42:10 +04:00
$this->listener->onPrePrepare($event);
$stmt = $this->dbh->prepare($statement);
$this->listener->onPrepare($event);
return new Doctrine_Db_Statement($this, $stmt);
}
/**
* query
*
* @param string $statement
* @param array $params
* @return Doctrine_Db_Statement|boolean
*/
public function query($statement, array $params = array()) {
$this->connect();
2006-12-29 17:01:31 +03:00
$event = new Doctrine_Db_Event($this, Doctrine_Db_Event::QUERY, $statement);
2007-02-05 15:04:56 +03:00
$skip = $this->listener->onPreQuery($event);
2006-12-29 17:01:31 +03:00
if ( ! empty($params)) {
2007-02-05 15:04:56 +03:00
$stmt = $this->dbh->prepare($statement);
2007-02-09 23:56:04 +03:00
2007-02-05 15:04:56 +03:00
return $stmt->execute($params);
2007-03-14 22:57:38 +03:00
2006-12-29 17:01:31 +03:00
} else {
2007-02-05 15:04:56 +03:00
if ( ! $skip) {
$stmt = $this->dbh->query($statement);
$this->count++;
} else {
$stmt = new stdClass;
$stmt->queryString = $statement;
}
$stmt = new Doctrine_Db_Statement($this, $stmt);
2006-12-29 17:01:31 +03:00
}
2007-02-05 15:04:56 +03:00
$this->listener->onQuery($event);
return $stmt;
2006-05-30 12:42:10 +04:00
}
/**
* quote
* quotes a string for use in a query
*
* @param string $input
* @return string
2006-05-30 12:42:10 +04:00
*/
2006-12-29 17:40:47 +03:00
public function quote($input)
{
$this->connect();
2006-06-01 15:58:05 +04:00
return $this->dbh->quote($input);
2006-05-30 12:42:10 +04:00
}
/**
* exec
* executes an SQL statement and returns the number of affected rows
*
* @param string $statement
* @return integer
*/
2006-12-29 17:40:47 +03:00
public function exec($statement)
{
$this->connect();
$args = func_get_args();
2006-12-29 17:01:31 +03:00
$event = new Doctrine_Db_Event($this, Doctrine_Db_Event::EXEC, $statement);
$this->listener->onPreExec($event);
$rows = $this->dbh->exec($statement);
2007-02-05 15:04:56 +03:00
$this->count++;
$this->listener->onExec($event);
return $rows;
}
/**
* lastInsertId
*
* @return integer
2006-05-30 12:42:10 +04:00
*/
2006-12-29 17:40:47 +03:00
public function lastInsertId()
{
$this->connect();
return $this->dbh->lastInsertId();
2006-05-30 12:42:10 +04:00
}
/**
* begins a transaction
*
* @return boolean
*/
2006-12-29 17:40:47 +03:00
public function beginTransaction()
{
$this->connect();
$event = new Doctrine_Db_Event($this, Doctrine_Db_Event::BEGIN);
$this->listener->onPreBeginTransaction($event);
$return = $this->dbh->beginTransaction();
$this->listener->onBeginTransaction($event);
2006-12-29 17:01:31 +03:00
return $return;
2006-05-30 12:42:10 +04:00
}
/**
* commits a transaction
*
* @return boolean
2006-05-30 12:42:10 +04:00
*/
2006-12-29 17:40:47 +03:00
public function commit()
{
$this->connect();
2007-01-12 02:13:02 +03:00
$event = new Doctrine_Db_Event($this, Doctrine_Db_Event::COMMIT);
$this->listener->onPreCommit($event);
$return = $this->dbh->commit();
$this->listener->onCommit($event);
return $return;
2006-05-30 12:42:10 +04:00
}
/**
* rollBack
*
* @return boolean
*/
2006-12-29 17:40:47 +03:00
public function rollBack()
{
$this->connect();
$event = new Doctrine_Db_Event($this, Doctrine_Db_Event::ROLLBACK);
$this->listener->onPreRollback($event);
$this->dbh->rollBack();
2006-12-29 17:01:31 +03:00
$this->listener->onRollback($event);
}
/**
* getAttribute
* retrieves a database connection attribute
*
* @param integer $attribute
* @return mixed
*/
2006-12-29 17:40:47 +03:00
public function getAttribute($attribute)
{
if ($this->isConnected) {
return $this->dbh->getAttribute($attribute);
} else {
if ( ! isset($this->pendingAttributes[$attribute])) {
throw new Doctrine_Db_Exception('Attribute ' . $attribute . ' not found.');
}
return $this->pendingAttributes[$attribute];
}
}
/**
* returns an array of available PDO drivers
*/
2006-12-29 17:40:47 +03:00
public static function getAvailableDrivers()
{
return PDO::getAvailableDrivers();
}
/**
* setAttribute
* sets an attribute
*
* @param integer $attribute
* @param mixed $value
* @return boolean
*/
2006-12-29 17:40:47 +03:00
public function setAttribute($attribute, $value)
{
if ($this->isConnected) {
$this->dbh->setAttribute($attribute, $value);
} else {
$this->pendingAttributes[$attribute] = $value;
}
}
/**
* getIterator
*
2006-05-30 12:42:10 +04:00
* @return ArrayIterator
*/
2006-12-29 17:40:47 +03:00
public function getIterator()
{
2007-02-05 15:04:56 +03:00
if ($this->listener instanceof Doctrine_Db_Profiler) {
return $this->listener;
2007-02-05 15:04:56 +03:00
}
2006-05-30 12:42:10 +04:00
}
/**
* count
2006-05-30 12:42:10 +04:00
* returns the number of executed queries
*
2006-05-30 12:42:10 +04:00
* @return integer
*/
2006-12-29 17:40:47 +03:00
public function count()
{
2007-02-05 15:04:56 +03:00
return $this->count;
2006-12-29 17:01:31 +03:00
}
2006-05-30 12:42:10 +04:00
}