Skip to content

Instantly share code, notes, and snippets.

@makasim
Last active October 11, 2018 13:48
Show Gist options
  • Save makasim/f1e28c9bc9458f20f38f to your computer and use it in GitHub Desktop.
Save makasim/f1e28c9bc9458f20f38f to your computer and use it in GitHub Desktop.
Persisted connection.
<?php
namespace Base\Testing;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Bundle\FrameworkBundle\Client;
trait DbIsolationExtension
{
/**
* @var Connection[]
*/
protected static $dbIsolationConnections = [];
protected function startTransaction()
{
if (false == $this->getClient() instanceof Client) {
throw new \LogicException('The client must be instance of Client');
}
if (false == $this->getClient()->getContainer()) {
throw new \LogicException('The client missing a container. Make sure the kernel was booted');
}
/** @var RegistryInterface $registry */
$registry = $this->getClient()->getContainer()->get('doctrine');
foreach ($registry->getManagers() as $name => $em) {
if ($em instanceof EntityManagerInterface) {
$em->clear();
$em->getConnection()->beginTransaction();
self::$dbIsolationConnections[$name.'_'.uniqid()] = $em->getConnection();
}
}
}
protected static function rollbackTransaction()
{
foreach (self::$dbIsolationConnections as $name => $connection) {
while ($connection->isConnected() && $connection->isTransactionActive()) {
$connection->rollBack();
}
}
self::$dbIsolationConnections = [];
}
/**
* @return \Symfony\Bundle\FrameworkBundle\Client
*/
abstract protected function getClient();
}
<?php
/**
Copyright (C) 2016 Maksim Kotlyar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/
namespace Base\Doctrine\DBAL;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Connection as DriverConnection;
use Doctrine\DBAL\Platforms\MySqlPlatform;
/**
* @see https://gist.github.com/makasim/f1e28c9bc9458f20f38f
*
* Connection wrapper sharing the same db handle across multiple requests
*
* Allows multiple Connection instances to run in the same transaction
*/
class PersistedConnection extends Connection
{
/**
* @var DriverConnection[]
*/
protected static $persistedConnections;
/**
* @var int[]
*/
protected static $persistedTransactionNestingLevels;
/**
* {@inheritDoc}
*/
public function connect()
{
if ($this->isConnected()) {
return false;
}
if ($this->hasPersistedConnection()) {
$this->_conn = $this->getPersistedConnection();
$this->setConnected(true);
} else {
parent::connect();
$this->setPersistedConnection($this->_conn);
// TODO we may need something like this for PosgreSQL
if ($this->getDatabasePlatform() instanceof MySqlPlatform) {
$this->_conn->exec('SET SESSION wait_timeout=2147483');
}
}
return true;
}
/**
* {@inheritDoc}
*/
public function close($force = false)
{
if ($force) {
parent::close();
$this->unsetPersistedConnection();
}
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
$this->wrapTransactionNestingLevel('beginTransaction');
}
/**
* {@inheritDoc}
*/
public function commit()
{
$this->wrapTransactionNestingLevel('commit');
}
/**
* {@inheritDoc}
*/
public function rollBack()
{
$this->wrapTransactionNestingLevel('rollBack');
}
/**
* {@inheritDoc}
*/
public function isTransactionActive()
{
$this->setTransactionNestingLevel($this->getPersistedTransactionNestingLevel());
return parent::isTransactionActive();
}
/**
* @param int $level
*/
private function setTransactionNestingLevel($level)
{
$rp = new \ReflectionProperty('Doctrine\DBAL\Connection', '_transactionNestingLevel');
$rp->setAccessible(true);
$rp->setValue($this, $level);
$rp->setAccessible(false);
}
/**
* @param string $method
*
* @throws \Exception
*/
private function wrapTransactionNestingLevel($method)
{
$exception = null;
$this->setTransactionNestingLevel($this->getPersistedTransactionNestingLevel());
try {
call_user_func(array('parent', $method));
$this->setPersistedTransactionNestingLevel($this->getTransactionNestingLevel());
} catch (\Exception $e) {
$this->setPersistedTransactionNestingLevel($this->getTransactionNestingLevel());
throw $e;
}
}
/**
* @param bool $connected
*/
protected function setConnected($connected)
{
$rp = new \ReflectionProperty('Doctrine\DBAL\Connection', '_isConnected');
$rp->setAccessible(true);
$rp->setValue($this, $connected);
$rp->setAccessible(false);
}
/**
* @return int
*/
protected function getPersistedTransactionNestingLevel()
{
if (isset(static::$persistedTransactionNestingLevels[$this->getConnectionId()])) {
return static::$persistedTransactionNestingLevels[$this->getConnectionId()];
}
return 0;
}
/**
* @param int $level
*/
protected function setPersistedTransactionNestingLevel($level)
{
static::$persistedTransactionNestingLevels[$this->getConnectionId()] = $level;
}
/**
* @param DriverConnection $connection
*/
protected function setPersistedConnection(DriverConnection $connection)
{
static::$persistedConnections[$this->getConnectionId()] = $connection;
}
/**
* @return bool
*/
protected function hasPersistedConnection()
{
return isset(static::$persistedConnections[$this->getConnectionId()]);
}
/**
* @return DriverConnection
*/
protected function getPersistedConnection()
{
return static::$persistedConnections[$this->getConnectionId()];
}
/**
* @return DriverConnection
*/
protected function unsetPersistedConnection()
{
unset(static::$persistedConnections[$this->getConnectionId()]);
unset(static::$persistedTransactionNestingLevels[$this->getConnectionId()]);
}
/**
* @return string
*/
protected function getConnectionId()
{
return md5(serialize($this->getParams()));
}
}
<?php
/**
Copyright (C) 2016 Maksim Kotlyar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/
namespace Base\Doctrine\DBAL;
use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
class PersistedConnectionFactory extends ConnectionFactory
{
/**
* {@inheritdoc}
*/
public function createConnection(
array $params,
Configuration $config = null,
EventManager $eventManager = null,
array $mappingTypes = array()
) {
if (isset($params['wrapperClass'])) {
throw new \LogicException('The wrapper class has already been defined. We cannot overwrite it.');
}
$params['wrapperClass'] = 'Base\Doctrine\DBAL\PersistedConnection';
return parent::createConnection($params, $config, $eventManager, $mappingTypes);
}
}
@makasim
Copy link
Author

makasim commented Mar 14, 2016

# config_test.yml

parameters:
    doctrine.dbal.connection_factory.class: 'Base\Doctrine\DBAL\PersistedConnectionFactory'

@nenadalm
Copy link

hi. I see that you added the connection into oro https://github.com/laboro/dev/blob/304a84c7df3c2ac270c58605e99148ddfeb9d9ef/package/platform/src/Oro/Component/Testing/Doctrine/PersistentConnection.php.

What if I wanted to use it from your gist? What's the license? Maybe you could include it into the file?

@makasim
Copy link
Author

makasim commented Nov 24, 2016

@nenadalm MIT license, I've just added it as a comment.

@nenadalm
Copy link

thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment