Commit 70438ca2 authored by Benjamin Eberlei's avatar Benjamin Eberlei

Merge branch 'master' of git://github.com/doctrine/dbal

parents 91de30d5 dea79e7b
{
"name": "doctrine/dbal",
"type": "library",
"description": "Database Abstraction Layer",
"keywords": ["dbal", "database", "persistence", "queryobject"],
"homepage": "http://www.doctrine-project.org",
"license": "LGPL",
"authors": [
{"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"},
{"name": "Roman Borschel", "email": "roman@code-factory.org"},
{"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"},
{"name": "Jonathan Wage", "email": "jonwage@gmail.com"}
],
"require": {
"php": ">=5.3.2",
"doctrine/common": "2.*"
}
}
<?php
/*
* 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.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Cache;
use Doctrine\DBAL\Driver\ResultStatement;
use PDO;
class ArrayStatement implements ResultStatement
{
private $data;
private $columnCount = 0;
private $num = 0;
public function __construct(array $data)
{
$this->data = $data;
if (count($data)) {
$this->columnCount = count($data[0]);
}
}
public function closeCursor()
{
unset ($this->data);
}
public function columnCount()
{
return $this->columnCount;
}
public function fetch($fetchStyle = PDO::FETCH_BOTH)
{
if (isset($this->data[$this->num])) {
$row = $this->data[$this->num++];
if ($fetchStyle === PDO::FETCH_ASSOC) {
return $row;
} else if ($fetchStyle === PDO::FETCH_NUM) {
return array_values($row);
} else if ($fetchStyle === PDO::FETCH_BOTH) {
return array_merge($row, array_values($row));
}
}
return false;
}
public function fetchAll($fetchStyle = PDO::FETCH_BOTH)
{
$rows = array();
while ($row = $this->fetch($fetchStyle)) {
$rows[] = $row;
}
return $rows;
}
public function fetchColumn($columnIndex = 0)
{
$row = $this->fetch(PDO::FETCH_NUM);
if (!isset($row[$columnIndex])) {
// TODO: verify this is correct behavior
return false;
}
return $row[$columnIndex];
}
}
\ No newline at end of file
<?php
/*
* 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.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Cache;
/**
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @since 2.2
*/
class CacheException extends \Doctrine\DBAL\DBALException
{
static public function noCacheKey()
{
return new self("No cache key was set.");
}
static public function noResultDriverConfigured()
{
return new self("Trying to cache a query but no result driver is configured.");
}
}
\ No newline at end of file
<?php
/*
* 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.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Cache;
use Doctrine\Common\Cache\Cache;
/**
* Query Cache Profile handles the data relevant for query caching.
*
* It is a value object, setter methods return NEW instances.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class QueryCacheProfile
{
/**
* @var Cache
*/
private $resultCacheDriver;
/**
* @var int
*/
private $lifetime = 0;
/**
* @var string
*/
private $cacheKey;
/**
* @param int $lifetime
* @param string $cacheKey
* @param Cache $resultCache
*/
public function __construct($lifetime = 0, $cacheKey = null, Cache $resultCache = null)
{
$this->lifetime = $lifetime;
$this->cacheKey = $cacheKey;
$this->resultCacheDriver = $resultCache;
}
/**
* @return Cache
*/
public function getResultCacheDriver()
{
return $this->resultCacheDriver;
}
/**
* @return int
*/
public function getLifetime()
{
return $this->lifetime;
}
/**
* @return string
*/
public function getCacheKey()
{
if ($this->cacheKey === null) {
throw CacheException::noCacheKey();
}
return $this->cacheKey;
}
/**
* Generate the real cache key from query, params and types.
*
* @param string $query
* @param array $params
* @param array $types
* @return array
*/
public function generateCacheKeys($query, $params, $types)
{
$realCacheKey = $query . "-" . serialize($params) . "-" . serialize($types);
// should the key be automatically generated using the inputs or is the cache key set?
if ($this->cacheKey === null) {
$cacheKey = sha1($realCacheKey);
} else {
$cacheKey = $this->cacheKey;
}
return array($cacheKey, $realCacheKey);
}
/**
* @param Cache $cache
* @return QueryCacheProfile
*/
public function setResultCacheDriver(Cache $cache)
{
return new QueryCacheProfile($this->lifetime, $this->cacheKey, $cache);
}
/**
* @param string|null $cacheKey
* @return QueryCacheProfile
*/
public function setCacheKey($cacheKey)
{
return new QueryCacheProfile($this->lifetime, $cacheKey, $this->resultCacheDriver);
}
/**
* @param int $lifetime
* @return QueryCacheProfile
*/
public function setLifetime($lifetime)
{
return new QueryCacheProfile($lifetime, $this->cacheKey, $this->resultCacheDriver);
}
}
\ No newline at end of file
<?php
/*
* 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.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Cache;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\Connection;
use Doctrine\Common\Cache\Cache;
use PDO;
/**
* Cache statement for SQL results.
*
* A result is saved in multiple cache keys, there is the originally specified
* cache key which is just pointing to result rows by key. The following things
* have to be ensured:
*
* 1. lifetime of the original key has to be longer than that of all the individual rows keys
* 2. if any one row key is missing the query has to be re-executed.
*
* Also you have to realize that the cache will load the whole result into memory at once to ensure 2.
* This means that the memory usage for cached results might increase by using this feature.
*/
class ResultCacheStatement implements ResultStatement
{
/**
* @var \Doctrine\Common\Cache\Cache
*/
private $resultCache;
/**
*
* @var string
*/
private $cacheKey;
/**
* @var string
*/
private $realKey;
/**
* @var int
*/
private $lifetime;
/**
* @var Doctrine\DBAL\Driver\Statement
*/
private $statement;
/**
* Did we reach the end of the statement?
*
* @var bool
*/
private $emptied = false;
/**
* @var array
*/
private $data;
/**
* @param Statement $stmt
* @param Cache $resultCache
* @param string $cacheKey
* @param string $realKey
* @param int $lifetime
*/
public function __construct(Statement $stmt, Cache $resultCache, $cacheKey, $realKey, $lifetime)
{
$this->statement = $stmt;
$this->resultCache = $resultCache;
$this->cacheKey = $cacheKey;
$this->realKey = $realKey;
$this->lifetime = $lifetime;
}
/**
* Closes the cursor, enabling the statement to be executed again.
*
* @return boolean Returns TRUE on success or FALSE on failure.
*/
public function closeCursor()
{
$this->statement->closeCursor();
if ($this->emptied && $this->data !== null) {
$data = $this->resultCache->fetch($this->cacheKey);
if (!$data) {
$data = array();
}
$data[$this->realKey] = $this->data;
$this->resultCache->save($this->cacheKey, $data, $this->lifetime);
unset($this->data);
}
}
/**
* columnCount
* Returns the number of columns in the result set
*
* @return integer Returns the number of columns in the result set represented
* by the PDOStatement object. If there is no result set,
* this method should return 0.
*/
public function columnCount()
{
return $this->statement->columnCount();
}
/**
* fetch
*
* @see Query::HYDRATE_* constants
* @param integer $fetchStyle Controls how the next row will be returned to the caller.
* This value must be one of the Query::HYDRATE_* constants,
* defaulting to Query::HYDRATE_BOTH
*
* @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor,
* this value determines which row will be returned to the caller.
* This value must be one of the Query::HYDRATE_ORI_* constants, defaulting to
* Query::HYDRATE_ORI_NEXT. To request a scrollable cursor for your
* PDOStatement object,
* you must set the PDO::ATTR_CURSOR attribute to Doctrine::CURSOR_SCROLL when you
* prepare the SQL statement with Doctrine_Adapter_Interface->prepare().
*
* @param integer $cursorOffset For a PDOStatement object representing a scrollable cursor for which the
* $cursorOrientation parameter is set to Query::HYDRATE_ORI_ABS, this value specifies
* the absolute number of the row in the result set that shall be fetched.
*
* For a PDOStatement object representing a scrollable cursor for
* which the $cursorOrientation parameter is set to Query::HYDRATE_ORI_REL, this value
* specifies the row to fetch relative to the cursor position before
* PDOStatement->fetch() was called.
*
* @return mixed
*/
public function fetch($fetchStyle = PDO::FETCH_BOTH)
{
if ($this->data === null) {
$this->data = array();
}
$row = $this->statement->fetch(PDO::FETCH_ASSOC);
if ($row) {
$this->data[] = $row;
if ($fetchStyle == PDO::FETCH_ASSOC) {
return $row;
} else if ($fetchStyle == PDO::FETCH_NUM) {
return array_values($row);
} else if ($fetchStyle == PDO::FETCH_BOTH) {
return array_merge($row, array_values($row));
} else {
throw new \InvalidArgumentException("Invalid fetch-style given for caching result.");
}
}
$this->emptied = true;
return false;
}
/**
* Returns an array containing all of the result set rows
*
* @param integer $fetchStyle Controls how the next row will be returned to the caller.
* This value must be one of the Query::HYDRATE_* constants,
* defaulting to Query::HYDRATE_BOTH
*
* @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is
* Query::HYDRATE_COLUMN. Defaults to 0.
*
* @return array
*/
public function fetchAll($fetchStyle = PDO::FETCH_BOTH)
{
$rows = array();
while ($row = $this->fetch($fetchStyle)) {
$rows[] = $row;
}
return $rows;
}
/**
* fetchColumn
* Returns a single column from the next row of a
* result set or FALSE if there are no more rows.
*
* @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no
* value is supplied, PDOStatement->fetchColumn()
* fetches the first column.
*
* @return string returns a single column in the next row of a result set.
*/
public function fetchColumn($columnIndex = 0)
{
$row = $this->fetch(PDO::FETCH_NUM);
if (!isset($row[$columnIndex])) {
// TODO: verify this is correct behavior
return false;
}
return $row[$columnIndex];
}
/**
* rowCount
* rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement
* executed by the corresponding object.
*
* If the last SQL statement executed by the associated Statement object was a SELECT statement,
* some databases may return the number of rows returned by that statement. However,
* this behaviour is not guaranteed for all databases and should not be
* relied on for portable applications.
*
* @return integer Returns the number of rows.
*/
public function rowCount()
{
return $this->statement->rowCount();
}
}
\ No newline at end of file
......@@ -20,6 +20,7 @@
namespace Doctrine\DBAL;
use Doctrine\DBAL\Logging\SQLLogger;
use Doctrine\Common\Cache\Cache;
/**
* Configuration container for the Doctrine DBAL.
......@@ -61,4 +62,25 @@ class Configuration
return isset($this->_attributes['sqlLogger']) ?
$this->_attributes['sqlLogger'] : null;
}
/**
* Gets the cache driver implementation that is used for query result caching.
*
* @return \Doctrine\Common\Cache\Cache
*/
public function getResultCacheImpl()
{
return isset($this->_attributes['resultCacheImpl']) ?
$this->_attributes['resultCacheImpl'] : null;
}
/**
* Sets the cache driver implementation that is used for query result caching.
*
* @param \Doctrine\Common\Cache\Cache $cacheImpl
*/
public function setResultCacheImpl(Cache $cacheImpl)
{
$this->_attributes['resultCacheImpl'] = $cacheImpl;
}
}
\ No newline at end of file
......@@ -23,7 +23,11 @@ use PDO, Closure, Exception,
Doctrine\DBAL\Types\Type,
Doctrine\DBAL\Driver\Connection as DriverConnection,
Doctrine\Common\EventManager,
Doctrine\DBAL\DBALException;
Doctrine\DBAL\DBALException,
Doctrine\DBAL\Cache\ResultCacheStatement,
Doctrine\DBAL\Cache\QueryCacheProfile,
Doctrine\DBAL\Cache\ArrayStatement,
Doctrine\DBAL\Cache\CacheException;
/**
* A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
......@@ -276,7 +280,7 @@ class Connection implements DriverConnection
/**
* Gets the DBAL driver instance.
*
* @return Doctrine\DBAL\Driver
* @return \Doctrine\DBAL\Driver
*/
public function getDriver()
{
......@@ -286,7 +290,7 @@ class Connection implements DriverConnection
/**
* Gets the Configuration used by the Connection.
*
* @return Doctrine\DBAL\Configuration
* @return \Doctrine\DBAL\Configuration
*/
public function getConfiguration()
{
......@@ -296,7 +300,7 @@ class Connection implements DriverConnection
/**
* Gets the EventManager used by the Connection.
*
* @return Doctrine\Common\EventManager
* @return \Doctrine\Common\EventManager
*/
public function getEventManager()
{
......@@ -306,7 +310,7 @@ class Connection implements DriverConnection
/**
* Gets the DatabasePlatform for the connection.
*
* @return Doctrine\DBAL\Platforms\AbstractPlatform
* @return \Doctrine\DBAL\Platforms\AbstractPlatform
*/
public function getDatabasePlatform()
{
......@@ -316,7 +320,7 @@ class Connection implements DriverConnection
/**
* Gets the ExpressionBuilder for the connection.
*
* @return Doctrine\DBAL\Query\ExpressionBuilder
* @return \Doctrine\DBAL\Query\ExpressionBuilder
*/
public function getExpressionBuilder()
{
......@@ -593,11 +597,17 @@ class Connection implements DriverConnection
*
* @param string $query The SQL query to execute.
* @param array $params The parameters to bind to the query, if any.
* @param array $types The types the previous parameters are in.
* @param QueryCacheProfile $qcp
* @return Doctrine\DBAL\Driver\Statement The executed statement.
* @internal PERF: Directly prepares a driver statement, not a wrapper.
*/
public function executeQuery($query, array $params = array(), $types = array())
public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
{
if ($qcp !== null) {
return $this->executeCacheQuery($query, $params, $types, $qcp);
}
$this->connect();
$hasLogger = $this->_config->getSQLLogger() !== null;
......@@ -626,6 +636,36 @@ class Connection implements DriverConnection
return $stmt;
}
/**
* Execute a caching query and
*
* @param string $query
* @param array $params
* @param array $types
* @param QueryCacheProfile $qcp
* @return \Doctrine\DBAL\Driver\ResultStatement
*/
public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
{
$resultCache = $qcp->getResultCacheDriver() ?: $this->_config->getResultCacheImpl();
if (!$resultCache) {
throw CacheException::noResultDriverConfigured();
}
list($cacheKey, $realKey) = $qcp->generateCacheKeys($query, $params, $types);
// fetch the row pointers entry
if ($data = $resultCache->fetch($cacheKey)) {
// is the real key part of this row pointers map or is the cache only pointing to other cache keys?
if (isset($data[$realKey])) {
return new ArrayStatement($data[$realKey]);
} else if (array_key_exists($realKey, $data)) {
return new ArrayStatement(array());
}
}
return new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
}
/**
* Executes an, optionally parameterized, SQL query and returns the result,
* applying a given projection/transformation function on each row of the result.
......
......@@ -81,9 +81,13 @@ class OCI8Connection implements \Doctrine\DBAL\Driver\Connection
* @param int $type PDO::PARAM*
* @return mixed
*/
public function quote($input, $type=\PDO::PARAM_STR)
public function quote($value, $type=\PDO::PARAM_STR)
{
return is_numeric($input) ? $input : "'" . str_replace("'", "''", $input) . "'";
if (is_int($value) || is_float($value)) {
return $value;
}
$value = str_replace("'", "''", $value);
return "'" . addcslashes($value, "\000\n\r\\\032") . "'";
}
/**
......
<?php
/*
* 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.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Driver;
use PDO;
/**
* Interface for the reading part of a prepare statement only.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
interface ResultStatement
{
/**
* Closes the cursor, enabling the statement to be executed again.
*
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function closeCursor();
/**
* columnCount
* Returns the number of columns in the result set
*
* @return integer Returns the number of columns in the result set represented
* by the PDOStatement object. If there is no result set,
* this method should return 0.
*/
function columnCount();
/**
* fetch
*
* @see Query::HYDRATE_* constants
* @param integer $fetchStyle Controls how the next row will be returned to the caller.
* This value must be one of the Query::HYDRATE_* constants,
* defaulting to Query::HYDRATE_BOTH
*
* @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor,
* this value determines which row will be returned to the caller.
* This value must be one of the Query::HYDRATE_ORI_* constants, defaulting to
* Query::HYDRATE_ORI_NEXT. To request a scrollable cursor for your
* PDOStatement object,
* you must set the PDO::ATTR_CURSOR attribute to Doctrine::CURSOR_SCROLL when you
* prepare the SQL statement with Doctrine_Adapter_Interface->prepare().
*
* @param integer $cursorOffset For a PDOStatement object representing a scrollable cursor for which the
* $cursorOrientation parameter is set to Query::HYDRATE_ORI_ABS, this value specifies
* the absolute number of the row in the result set that shall be fetched.
*
* For a PDOStatement object representing a scrollable cursor for
* which the $cursorOrientation parameter is set to Query::HYDRATE_ORI_REL, this value
* specifies the row to fetch relative to the cursor position before
* PDOStatement->fetch() was called.
*
* @return mixed
*/
function fetch($fetchStyle = PDO::FETCH_BOTH);
/**
* Returns an array containing all of the result set rows
*
* @param integer $fetchStyle Controls how the next row will be returned to the caller.
* This value must be one of the Query::HYDRATE_* constants,
* defaulting to Query::HYDRATE_BOTH
*
* @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is
* Query::HYDRATE_COLUMN. Defaults to 0.
*
* @return array
*/
function fetchAll($fetchStyle = PDO::FETCH_BOTH);
/**
* fetchColumn
* Returns a single column from the next row of a
* result set or FALSE if there are no more rows.
*
* @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no
* value is supplied, PDOStatement->fetchColumn()
* fetches the first column.
*
* @return string returns a single column in the next row of a result set.
*/
function fetchColumn($columnIndex = 0);
}
<?php
/*
* $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
......@@ -34,9 +32,8 @@ use \PDO;
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
*/
interface Statement
interface Statement extends ResultStatement
{
/**
* Binds a value to a corresponding named or positional
......@@ -77,23 +74,6 @@ interface Statement
*/
function bindParam($column, &$variable, $type = null);
/**
* Closes the cursor, enabling the statement to be executed again.
*
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function closeCursor();
/**
* columnCount
* Returns the number of columns in the result set
*
* @return integer Returns the number of columns in the result set represented
* by the PDOStatement object. If there is no result set,
* this method should return 0.
*/
function columnCount();
/**
* errorCode
* Fetch the SQLSTATE associated with the last operation on the statement handle
......@@ -128,70 +108,14 @@ interface Statement
*/
function execute($params = null);
/**
* fetch
*
* @see Query::HYDRATE_* constants
* @param integer $fetchStyle Controls how the next row will be returned to the caller.
* This value must be one of the Query::HYDRATE_* constants,
* defaulting to Query::HYDRATE_BOTH
*
* @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor,
* this value determines which row will be returned to the caller.
* This value must be one of the Query::HYDRATE_ORI_* constants, defaulting to
* Query::HYDRATE_ORI_NEXT. To request a scrollable cursor for your
* PDOStatement object,
* you must set the PDO::ATTR_CURSOR attribute to Doctrine::CURSOR_SCROLL when you
* prepare the SQL statement with Doctrine_Adapter_Interface->prepare().
*
* @param integer $cursorOffset For a PDOStatement object representing a scrollable cursor for which the
* $cursorOrientation parameter is set to Query::HYDRATE_ORI_ABS, this value specifies
* the absolute number of the row in the result set that shall be fetched.
*
* For a PDOStatement object representing a scrollable cursor for
* which the $cursorOrientation parameter is set to Query::HYDRATE_ORI_REL, this value
* specifies the row to fetch relative to the cursor position before
* PDOStatement->fetch() was called.
*
* @return mixed
*/
function fetch($fetchStyle = PDO::FETCH_BOTH);
/**
* Returns an array containing all of the result set rows
*
* @param integer $fetchStyle Controls how the next row will be returned to the caller.
* This value must be one of the Query::HYDRATE_* constants,
* defaulting to Query::HYDRATE_BOTH
*
* @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is
* Query::HYDRATE_COLUMN. Defaults to 0.
*
* @return array
*/
function fetchAll($fetchStyle = PDO::FETCH_BOTH);
/**
* fetchColumn
* Returns a single column from the next row of a
* result set or FALSE if there are no more rows.
*
* @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no
* value is supplied, PDOStatement->fetchColumn()
* fetches the first column.
*
* @return string returns a single column in the next row of a result set.
*/
function fetchColumn($columnIndex = 0);
/**
* rowCount
* rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement
* rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement
* executed by the corresponding object.
*
* If the last SQL statement executed by the associated Statement object was a SELECT statement,
* some databases may return the number of rows returned by that statement. However,
* this behaviour is not guaranteed for all databases and should not be
* If the last SQL statement executed by the associated Statement object was a SELECT statement,
* some databases may return the number of rows returned by that statement. However,
* this behaviour is not guaranteed for all databases and should not be
* relied on for portable applications.
*
* @return integer Returns the number of rows.
......
<?php
/*
* 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.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Event\Listeners;
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
use Doctrine\Common\EventSubscriber;
/**
* Session init listener for executing a single SQL statement right after a connection is opened.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.com
* @since 2.2
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class SQLSessionInit implements EventSubscriber
{
/**
* @var string
*/
protected $sql;
/**
* @param string $sql
*/
public function __construct($sql)
{
$this->sql = $sql;
}
/**
* @param ConnectionEventArgs $args
* @return void
*/
public function postConnect(ConnectionEventArgs $args)
{
$conn = $args->getConnection();
$conn->exec($this->sql);
}
public function getSubscribedEvents()
{
return array(Events::postConnect);
}
}
\ No newline at end of file
......@@ -830,7 +830,8 @@ abstract class AbstractPlatform
/**
* Drop a Table
*
*
* @throws \InvalidArgumentException
* @param Table|string $table
* @return string
*/
......@@ -838,11 +839,24 @@ abstract class AbstractPlatform
{
if ($table instanceof \Doctrine\DBAL\Schema\Table) {
$table = $table->getQuotedName($this);
} else if(!is_string($table)) {
throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
}
return 'DROP TABLE ' . $table;
}
/**
* Get SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
*
* @param Table|string $table
* @return string
*/
public function getDropTemporaryTableSQL($table)
{
return $this->getDropTableSQL($table);
}
/**
* Drop index from a table
*
......
......@@ -610,23 +610,6 @@ class MySqlPlatform extends AbstractPlatform
{
return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
}
/**
* Gets the SQL to drop a table.
*
* @param string $table The name of table to drop.
* @override
*/
public function getDropTableSQL($table)
{
if ($table instanceof \Doctrine\DBAL\Schema\Table) {
$table = $table->getQuotedName($this);
} else if(!is_string($table)) {
throw new \InvalidArgumentException('MysqlPlatform::getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
}
return 'DROP TABLE ' . $table;
}
public function getSetTransactionIsolationSQL($level)
{
......@@ -686,4 +669,25 @@ class MySqlPlatform extends AbstractPlatform
{
return 'Doctrine\DBAL\Platforms\Keywords\MySQLKeywords';
}
/**
* Get SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
*
* MySQL commits a transaction implicitly when DROP TABLE is executed, however not
* if DROP TEMPORARY TABLE is executed.
*
* @throws \InvalidArgumentException
* @param $table
* @return string
*/
public function getDropTemporaryTableSQL($table)
{
if ($table instanceof \Doctrine\DBAL\Schema\Table) {
$table = $table->getQuotedName($this);
} else if(!is_string($table)) {
throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
}
return 'DROP TEMPORARY TABLE ' . $table;
}
}
......@@ -86,9 +86,9 @@ class Connection extends \Doctrine\DBAL\Connection
return $this->case;
}
public function executeQuery($query, array $params = array(), $types = array())
public function executeQuery($query, array $params = array(), $types = array(), $useCacheLifetime = false, $cacheResultKey = null)
{
return new Statement(parent::executeQuery($query, $params, $types), $this);
return new Statement(parent::executeQuery($query, $params, $types, $useCacheLifetime, $cacheResultKey), $this);
}
/**
......
......@@ -99,7 +99,7 @@ class SQLParserUtils
}
}
if (!$arrayPositions || count($params) != count($types)) {
if ((!$arrayPositions && $isPositional) || (count($params) != count($types))) {
return array($query, $params, $types);
}
......@@ -134,8 +134,44 @@ class SQLParserUtils
$paramOffset += ($len - 1); // Grows larger by number of parameters minus the replaced needle.
$queryOffset += (strlen($expandStr) - 1);
}
} else {
throw new DBALException("Array parameters are not supported for named placeholders.");
$queryOffset= 0;
$typesOrd = array();
$paramsOrd = array();
foreach ($paramPos as $needle => $needlePos) {
$paramLen = strlen($needle);
$token = substr($needle,0,1);
$needle = substr($needle,1);
$value = $params[$needle];
if (!isset($arrayPositions[$needle])) {
foreach ($needlePos as $pos) {
$pos += $queryOffset;
$queryOffset -= ($paramLen - 1);
$paramsOrd[] = $value;
$typesOrd[] = $types[$needle];
$query = substr($query, 0, $pos) . '?' . substr($query, ($pos + $paramLen));
}
} else {
$len = count($value);
$expandStr = implode(", ", array_fill(0, $len, "?"));
foreach ($needlePos as $pos) {
foreach ($value as $val) {
$paramsOrd[] = $val;
$typesOrd[] = $types[$needle] - Connection::ARRAY_PARAM_OFFSET;
}
$pos += $queryOffset;
$queryOffset += (strlen($expandStr) - $paramLen);
$query = substr($query, 0, $pos) . $expandStr . substr($query, ($pos + $paramLen));
}
}
}
$types = $typesOrd;
$params = $paramsOrd;
}
return array($query, $params, $types);
......
......@@ -38,11 +38,10 @@ class ArrayType extends Type
public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform)
{
if (empty($value)) {
return array();
if ($value === null) {
return null;
}
$value = (is_resource($value)) ? stream_get_contents($value) : $value;
$val = unserialize($value);
if ($val === false && $value != 'b:0;') {
......
<?php
namespace Doctrine\Tests\DBAL\Events;
use Doctrine\Tests\DbalTestCase;
use Doctrine\DBAL\Event\Listeners\SQLSessionInit;
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
require_once __DIR__ . '/../../TestInit.php';
/**
* @group DBAL-169
*/
class SQLSessionInitTest extends DbalTestCase
{
public function testPostConnect()
{
$connectionMock = $this->getMock('Doctrine\DBAL\Connection', array(), array(), '', false);
$connectionMock->expects($this->once())
->method('exec')
->with($this->equalTo("SET SEARCH_PATH TO foo, public, TIMEZONE TO 'Europe/Berlin'"));
$eventArgs = new ConnectionEventArgs($connectionMock);
$listener = new SQLSessionInit("SET SEARCH_PATH TO foo, public, TIMEZONE TO 'Europe/Berlin'");
$listener->postConnect($eventArgs);
}
public function testGetSubscribedEvents()
{
$listener = new SQLSessionInit("SET SEARCH_PATH TO foo, public, TIMEZONE TO 'Europe/Berlin'");
$this->assertEquals(array(Events::postConnect), $listener->getSubscribedEvents());
}
}
\ No newline at end of file
......@@ -269,4 +269,12 @@ class DataAccessTest extends \Doctrine\Tests\DbalFunctionalTestCase
$this->assertEquals('2010-03-01', date('Y-m-d', strtotime($row['add_month'])), "Adding month should end up on 2010-03-01");
$this->assertEquals('2009-11-01', date('Y-m-d', strtotime($row['sub_month'])), "Adding month should end up on 2009-11-01");
}
public function testQuoteSQLInjection()
{
$sql = "SELECT * FROM fetch_table WHERE test_string = " . $this->_conn->quote("bar' OR '1'='1");
$rows = $this->_conn->fetchAll($sql);
$this->assertEquals(0, count($rows), "no result should be returned, otherwise SQL injection is possible");
}
}
\ No newline at end of file
<?php
namespace Doctrine\Tests\DBAL\Functional\Ticket;
use Doctrine\DBAL\Connection;
use\PDO;
require_once __DIR__ . '/../../TestInit.php';
/**
* @group DDC-1372
*/
class NamedParametersTest extends \Doctrine\Tests\DbalFunctionalTestCase
{
public function ticketProvider()
{
return array(
array(
'SELECT * FROM ddc1372_foobar f WHERE f.foo = :foo AND f.bar IN (:bar)',
array('foo'=>1,'bar'=> array(1, 2, 3)),
array('foo'=>PDO::PARAM_INT,'bar'=> Connection::PARAM_INT_ARRAY,),
array(
array('id'=>1,'foo'=>1,'bar'=>1),
array('id'=>2,'foo'=>1,'bar'=>2),
array('id'=>3,'foo'=>1,'bar'=>3),
)
),
array(
'SELECT * FROM ddc1372_foobar f WHERE f.foo = :foo AND f.bar IN (:bar)',
array('foo'=>1,'bar'=> array(1, 2, 3)),
array('bar'=> Connection::PARAM_INT_ARRAY,'foo'=>PDO::PARAM_INT),
array(
array('id'=>1,'foo'=>1,'bar'=>1),
array('id'=>2,'foo'=>1,'bar'=>2),
array('id'=>3,'foo'=>1,'bar'=>3),
)
),
array(
'SELECT * FROM ddc1372_foobar f WHERE f.bar IN (:bar) AND f.foo = :foo',
array('foo'=>1,'bar'=> array(1, 2, 3)),
array('bar'=> Connection::PARAM_INT_ARRAY,'foo'=>PDO::PARAM_INT),
array(
array('id'=>1,'foo'=>1,'bar'=>1),
array('id'=>2,'foo'=>1,'bar'=>2),
array('id'=>3,'foo'=>1,'bar'=>3),
)
),
array(
'SELECT * FROM ddc1372_foobar f WHERE f.bar IN (:bar) AND f.foo = :foo',
array('foo'=>1,'bar'=> array('1', '2', '3')),
array('bar'=> Connection::PARAM_STR_ARRAY,'foo'=>PDO::PARAM_INT),
array(
array('id'=>1,'foo'=>1,'bar'=>1),
array('id'=>2,'foo'=>1,'bar'=>2),
array('id'=>3,'foo'=>1,'bar'=>3),
)
),
array(
'SELECT * FROM ddc1372_foobar f WHERE f.bar IN (:bar) AND f.foo IN (:foo)',
array('foo'=>array('1'),'bar'=> array(1, 2, 3,4)),
array('bar'=> Connection::PARAM_STR_ARRAY,'foo'=>Connection::PARAM_INT_ARRAY),
array(
array('id'=>1,'foo'=>1,'bar'=>1),
array('id'=>2,'foo'=>1,'bar'=>2),
array('id'=>3,'foo'=>1,'bar'=>3),
array('id'=>4,'foo'=>1,'bar'=>4),
)
),
array(
'SELECT * FROM ddc1372_foobar f WHERE f.bar IN (:bar) AND f.foo IN (:foo)',
array('foo'=>1,'bar'=> 2),
array('bar'=>PDO::PARAM_INT,'foo'=>PDO::PARAM_INT),
array(
array('id'=>2,'foo'=>1,'bar'=>2),
)
),
array(
'SELECT * FROM ddc1372_foobar f WHERE f.bar = :arg AND f.foo <> :arg',
array('arg'=>'1'),
array('arg'=>PDO::PARAM_STR),
array(
array('id'=>5,'foo'=>2,'bar'=>1),
)
),
array(
'SELECT * FROM ddc1372_foobar f WHERE f.bar NOT IN (:arg) AND f.foo IN (:arg)',
array('arg'=>array(1, 2)),
array('arg'=>Connection::PARAM_INT_ARRAY),
array(
array('id'=>3,'foo'=>1,'bar'=>3),
array('id'=>4,'foo'=>1,'bar'=>4),
)
),
);
}
public function setUp()
{
parent::setUp();
if (!$this->_conn->getSchemaManager()->tablesExist("ddc1372_foobar")) {
try {
$table = new \Doctrine\DBAL\Schema\Table("ddc1372_foobar");
$table->addColumn('id', 'integer');
$table->addColumn('foo','string');
$table->addColumn('bar','string');
$sm = $this->_conn->getSchemaManager();
$sm->createTable($table);
$this->_conn->insert('ddc1372_foobar', array(
'id' => 1, 'foo' => 1, 'bar' => 1
));
$this->_conn->insert('ddc1372_foobar', array(
'id' => 2, 'foo' => 1, 'bar' => 2
));
$this->_conn->insert('ddc1372_foobar', array(
'id' => 3, 'foo' => 1, 'bar' => 3
));
$this->_conn->insert('ddc1372_foobar', array(
'id' => 4, 'foo' => 1, 'bar' => 4
));
$this->_conn->insert('ddc1372_foobar', array(
'id' => 5, 'foo' => 2, 'bar' => 1
));
$this->_conn->insert('ddc1372_foobar', array(
'id' => 6, 'foo' => 2, 'bar' => 2
));
} catch(\Exception $e) {
$this->fail($e->getMessage());
}
}
}
/**
* @dataProvider ticketProvider
* @param string $query
* @param array $params
* @param array $types
* @param array $expected
*/
public function testTicket($query,$params,$types,$expected)
{
$stmt = $this->_conn->executeQuery($query, $params, $types);
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$this->assertEquals($result, $expected);
}
}
\ No newline at end of file
<?php
namespace Doctrine\Tests\DBAL\Functional;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use PDO;
require_once __DIR__ . '/../../TestInit.php';
/**
* @group DDC-217
*/
class ResultCacheTest extends \Doctrine\Tests\DbalFunctionalTestCase
{
private $expectedResult = array(array('test_int' => 100, 'test_string' => 'foo'), array('test_int' => 200, 'test_string' => 'bar'), array('test_int' => 300, 'test_string' => 'baz'));
private $sqlLogger;
public function setUp()
{
parent::setUp();
try {
/* @var $sm \Doctrine\DBAL\Schema\AbstractSchemaManager */
$table = new \Doctrine\DBAL\Schema\Table("caching");
$table->addColumn('test_int', 'integer');
$table->addColumn('test_string', 'string', array('notnull' => false));
$sm = $this->_conn->getSchemaManager();
$sm->createTable($table);
} catch(\Exception $e) {
}
$this->_conn->executeUpdate('DELETE FROM caching');
foreach ($this->expectedResult AS $row) {
$this->_conn->insert('caching', $row);
}
$config = $this->_conn->getConfiguration();
$config->setSQLLogger($this->sqlLogger = new \Doctrine\DBAL\Logging\DebugStack);
$cache = new \Doctrine\Common\Cache\ArrayCache;
$config->setResultCacheImpl($cache);
}
public function testCacheFetchAssoc()
{
$this->assertCacheNonCacheSelectSameFetchModeAreEqual($this->expectedResult, \PDO::FETCH_ASSOC);
}
public function testFetchNum()
{
$expectedResult = array();
foreach ($this->expectedResult AS $v) {
$expectedResult[] = array_values($v);
}
$this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, \PDO::FETCH_NUM);
}
public function testFetchBoth()
{
$expectedResult = array();
foreach ($this->expectedResult AS $v) {
$expectedResult[] = array_merge($v, array_values($v));
}
$this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, \PDO::FETCH_BOTH);
}
public function testMixingFetch()
{
$numExpectedResult = array();
foreach ($this->expectedResult AS $v) {
$numExpectedResult[] = array_values($v);
}
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$data = $this->hydrateStmt($stmt, \PDO::FETCH_ASSOC);
$this->assertEquals($this->expectedResult, $data);
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$data = $this->hydrateStmt($stmt, \PDO::FETCH_NUM);
$this->assertEquals($numExpectedResult, $data);
}
public function testDontCloseNoCache()
{
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$data = array();
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$data[] = $row;
}
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$data = array();
while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
$data[] = $row;
}
$this->assertEquals(2, count($this->sqlLogger->queries));
}
public function testDontFinishNoCache()
{
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$data = $this->hydrateStmt($stmt, \PDO::FETCH_NUM);
$this->assertEquals(2, count($this->sqlLogger->queries));
}
public function assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, $fetchStyle)
{
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$this->assertEquals(2, $stmt->columnCount());
$data = $this->hydrateStmt($stmt, $fetchStyle);
$this->assertEquals($expectedResult, $data);
$stmt = $this->_conn->executeQuery("SELECT * FROM caching", array(), array(), new QueryCacheProfile(10, "testcachekey"));
$this->assertEquals(2, $stmt->columnCount());
$data = $this->hydrateStmt($stmt, $fetchStyle);
$this->assertEquals($expectedResult, $data);
$this->assertEquals(1, count($this->sqlLogger->queries), "just one dbal hit");
}
public function testEmptyResultCache()
{
$stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey"));
$data = $this->hydrateStmt($stmt);
$stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey"));
$data = $this->hydrateStmt($stmt);
$this->assertEquals(1, count($this->sqlLogger->queries), "just one dbal hit");
}
public function testChangeCacheImpl()
{
$stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey"));
$data = $this->hydrateStmt($stmt);
$secondCache = new \Doctrine\Common\Cache\ArrayCache;
$stmt = $this->_conn->executeQuery("SELECT * FROM caching WHERE test_int > 500", array(), array(), new QueryCacheProfile(10, "emptycachekey", $secondCache));
$data = $this->hydrateStmt($stmt);
$this->assertEquals(2, count($this->sqlLogger->queries), "two hits");
$this->assertEquals(1, count($secondCache->fetch("emptycachekey")));
}
private function hydrateStmt($stmt, $fetchStyle = \PDO::FETCH_ASSOC)
{
$data = array();
while ($row = $stmt->fetch($fetchStyle)) {
$data[] = $row;
}
$stmt->closeCursor();
return $data;
}
}
\ No newline at end of file
<?php
namespace Doctrine\Tests\DBAL\Functional;
use \Doctrine\DBAL\Schema\Table;
use \Doctrine\DBAL\Schema\Column;
use \Doctrine\DBAL\Types\Type;
class TemporaryTableTest extends \Doctrine\Tests\DbalFunctionalTestCase
{
public function setUp()
{
parent::setUp();
try {
$this->_conn->exec($this->_conn->getDatabasePlatform()->getDropTableSQL("non_temporary"));
} catch(\Exception $e) {
}
}
/**
* @group DDC-1337
* @return void
*/
public function testDropTemporaryTableNotAbortsTransaction()
{
$platform = $this->_conn->getDatabasePlatform();
$columnDefinitions = array("id" => array("type" => Type::getType("integer"), "notnull" => true));
$tempTable = $platform->getTemporaryTableName("temporary");
$tempTableSQL = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' ('
. $platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
$table = new Table("non_temporary");
$table->addColumn("id", "integer");
$this->_conn->getSchemaManager()->createTable($table);
$this->_conn->beginTransaction();
$this->_conn->insert("non_temporary", array("id" => 1));
$this->_conn->exec($tempTableSQL);
$this->_conn->exec($platform->getDropTemporaryTableSQL($tempTable));
$this->_conn->insert("non_temporary", array("id" => 2));
$this->_conn->rollback();
$rows = $this->_conn->fetchAll('SELECT * FROM non_temporary');
$this->assertEquals(array(), $rows);
}
/**
* @group DDC-1337
* @return void
*/
public function testCreateTemporaryTableNotAbortsTransaction()
{
$platform = $this->_conn->getDatabasePlatform();
$columnDefinitions = array("id" => array("type" => Type::getType("integer"), "notnull" => true));
$tempTable = $platform->getTemporaryTableName("temporary");
$tempTableSQL = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' ('
. $platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
$table = new Table("non_temporary");
$table->addColumn("id", "integer");
$this->_conn->getSchemaManager()->createTable($table);
$this->_conn->beginTransaction();
$this->_conn->insert("non_temporary", array("id" => 1));
$this->_conn->exec($tempTableSQL);
$this->_conn->insert("non_temporary", array("id" => 2));
$this->_conn->rollback();
try {
$this->_conn->exec($platform->getDropTemporaryTableSQL($tempTable));
} catch(\Exception $e) {
}
$rows = $this->_conn->fetchAll('SELECT * FROM non_temporary');
$this->assertEquals(array(), $rows);
}
}
\ No newline at end of file
......@@ -9,6 +9,7 @@ require_once __DIR__ . '/../TestInit.php';
/**
* @group DBAL-78
* @group DDC-1372
*/
class SQLParserUtilsTest extends \Doctrine\Tests\DbalTestCase
{
......@@ -96,6 +97,89 @@ class SQLParserUtilsTest extends \Doctrine\Tests\DbalTestCase
array(1, 2, 3, 4, 5),
array(\PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT)
),
// Named parameters : Very simple with param int
array(
"SELECT * FROM Foo WHERE foo = :foo",
array('foo'=>1),
array('foo'=>\PDO::PARAM_INT),
'SELECT * FROM Foo WHERE foo = ?',
array(1),
array(\PDO::PARAM_INT)
),
// Named parameters : Very simple with param int and string
array(
"SELECT * FROM Foo WHERE foo = :foo AND bar = :bar",
array('bar'=>'Some String','foo'=>1),
array('foo'=>\PDO::PARAM_INT,'bar'=>\PDO::PARAM_STR),
'SELECT * FROM Foo WHERE foo = ? AND bar = ?',
array(1,'Some String'),
array(\PDO::PARAM_INT, \PDO::PARAM_STR)
),
// Named parameters : Very simple with one needle
array(
"SELECT * FROM Foo WHERE foo IN (:foo)",
array('foo'=>array(1, 2, 3)),
array('foo'=>Connection::PARAM_INT_ARRAY),
'SELECT * FROM Foo WHERE foo IN (?, ?, ?)',
array(1, 2, 3),
array(\PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT)
),
// Named parameters: One non-list before d one after list-needle
array(
"SELECT * FROM Foo WHERE foo = :foo AND bar IN (:bar)",
array('foo'=>"string", 'bar'=>array(1, 2, 3)),
array('foo'=>\PDO::PARAM_STR, 'bar'=>Connection::PARAM_INT_ARRAY),
'SELECT * FROM Foo WHERE foo = ? AND bar IN (?, ?, ?)',
array("string", 1, 2, 3),
array(\PDO::PARAM_STR, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT)
),
// Named parameters: One non-list after list-needle
array(
"SELECT * FROM Foo WHERE bar IN (:bar) AND baz = :baz",
array('bar'=>array(1, 2, 3), 'baz'=>"foo"),
array('bar'=>Connection::PARAM_INT_ARRAY, 'baz'=>\PDO::PARAM_STR),
'SELECT * FROM Foo WHERE bar IN (?, ?, ?) AND baz = ?',
array(1, 2, 3, "foo"),
array(\PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_STR)
),
// Named parameters: One non-list before and one after list-needle
array(
"SELECT * FROM Foo WHERE foo = :foo AND bar IN (:bar) AND baz = :baz",
array('bar'=>array(1, 2, 3),'foo'=>1, 'baz'=>4),
array('bar'=>Connection::PARAM_INT_ARRAY, 'foo'=>\PDO::PARAM_INT, 'baz'=>\PDO::PARAM_INT),
'SELECT * FROM Foo WHERE foo = ? AND bar IN (?, ?, ?) AND baz = ?',
array(1, 1, 2, 3, 4),
array(\PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT)
),
// Named parameters: Two lists
array(
"SELECT * FROM Foo WHERE foo IN (:a, :b)",
array('b'=>array(4, 5),'a'=>array(1, 2, 3)),
array('a'=>Connection::PARAM_INT_ARRAY, 'b'=>Connection::PARAM_INT_ARRAY),
'SELECT * FROM Foo WHERE foo IN (?, ?, ?, ?, ?)',
array(1, 2, 3, 4, 5),
array(\PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT, \PDO::PARAM_INT)
),
// Named parameters : With the same name arg type string
array(
"SELECT * FROM Foo WHERE foo <> :arg AND bar = :arg",
array('arg'=>"Some String"),
array('arg'=>\PDO::PARAM_STR),
'SELECT * FROM Foo WHERE foo <> ? AND bar = ?',
array("Some String","Some String"),
array(\PDO::PARAM_STR,\PDO::PARAM_STR,)
),
// Named parameters : With the same name arg
array(
"SELECT * FROM Foo WHERE foo IN (:arg) AND NOT bar IN (:arg)",
array('arg'=>array(1, 2, 3)),
array('arg'=>Connection::PARAM_INT_ARRAY),
'SELECT * FROM Foo WHERE foo IN (?, ?, ?) AND NOT bar IN (?, ?, ?)',
array(1, 2, 3, 1, 2, 3),
array(\PDO::PARAM_INT,\PDO::PARAM_INT, \PDO::PARAM_INT,\PDO::PARAM_INT,\PDO::PARAM_INT, \PDO::PARAM_INT)
),
);
}
......
......@@ -7,12 +7,12 @@ class DbalFunctionalTestCase extends DbalTestCase
/**
* Shared connection when a TestCase is run alone (outside of it's functional suite)
*
* @var Doctrine\DBAL\Connection
* @var \Doctrine\DBAL\Connection
*/
private static $_sharedConn;
/**
* @var Doctrine\DBAL\Connection
* @var \Doctrine\DBAL\Connection
*/
protected $_conn;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment