Skip to content

Instantly share code, notes, and snippets.

@ludofleury
Last active November 8, 2021 14:41
Show Gist options
  • Select an option

  • Save ludofleury/5074595 to your computer and use it in GitHub Desktop.

Select an option

Save ludofleury/5074595 to your computer and use it in GitHub Desktop.
A Behat Context with a hook to kill the Mysql connections
<?php
use Behat\Symfony2Extension\Context\KernelAwareInterface;
use Behat\Symfony2Extension\Context\KernelDictionary;
use Behat\MinkExtension\Context\MinkContext;
class MysqlContext extends MinkContext implements KernelAwareInterface
{
use KernelDictionary;
/**
* @AfterScenario
*/
public function killMysqlConnections()
{
$connections = $this->kernel->getContainer()->get('doctrine')->getConnections();
foreach ($connections as $connection) {
$threads = $connection->query('SHOW FULL PROCESSLIST');
while ($thread = $threads->fetch()) {
if ($thread['db'] == $connection->getDatabase() && $thread['Command'] == 'Sleep') {
$connection->query(sprintf('KILL %d', $thread['Id']));
}
}
}
}
}
@ludofleury
Copy link
Copy Markdown
Author

In a very large Behat suite, you could have this problem with Doctrine: too many connections.
If you're using Mysql, this hook will kill all sleeping connections related to your test database.

Remember to check SymfonyDoctrineContext which also try to close connection after a scenario. (Yet some connections still up and the stack could grow over your hardware limit).

@beberlei
Copy link
Copy Markdown

beberlei commented Mar 3, 2013

You should use a shared connection instead and use a "BeforeScenario" hook to set the shared connection on the container, i suppose that would be much faster than reconnecting every time.

@ludofleury
Copy link
Copy Markdown
Author

Thanks @beberlei for the tips, I'll try.

@nmariani
Copy link
Copy Markdown

Thanks soooooo much @ludofleury. You saved my day after a Symfony 2.5 / PHP 5.5 upgrade! ;)

@itsjavi
Copy link
Copy Markdown

itsjavi commented Feb 25, 2020

that was a life saver! I thought that unsetting the PDO connection was enough but it was not.
thanks for this

@ludofleury
Copy link
Copy Markdown
Author

ludofleury commented Mar 20, 2020 via email

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