Skip to content

Instantly share code, notes, and snippets.

@SenseException
Last active May 4, 2016 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SenseException/77c2d04ac00d5e1a2da8fb94ec28a472 to your computer and use it in GitHub Desktop.
Save SenseException/77c2d04ac00d5e1a2da8fb94ec28a472 to your computer and use it in GitHub Desktop.
MySQL Profiles in Symfony Console using Doctrine DBAL (needs some cleanup)
<?php
use Doctrine\DBAL\Connection;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
class Profiler
{
/**
* @var Connection
*/
private $connection;
/**
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
public function start()
{
$this->connection->executeUpdate('SET SESSION profiling = 1;');
}
public function evaluateProfile(InputInterface $input, OutputInterface $output)
{
// Profiling query is deprecated. Use performance_schema instead
$profiles = $this->connection->fetchAll('SHOW PROFILES;');
$table = new Table($output);
$this->showRows($profiles, $table);
$question = new QuestionHelper();
while (true) {
try {
$queryIds = array_column($profiles, 'Query_ID');
$selectors = array_combine($queryIds, $queryIds);
$selectors['exit'] = 'exit';
$selectors['profiles'] = 'profiles';
$answer = $question->ask($input, $output, new ChoiceQuestion('Which profile to check?', $selectors));
} catch (\Exception $e) {
$answer = 'profiles';
$output->writeln('<error>'.$e->getMessage().'</error>');
}
if ('exit' === $answer) {
break;
}
if ('profiles' === $answer) {
$this->showRows($profiles, $table);
}
if (is_numeric($answer)) {
// Profiling query is deprecated. Use performance_schema instead
$profile = $this->connection->fetchAll("SHOW PROFILE FOR QUERY $answer;");
$this->showRows($profile, $table);
}
}
}
private function showRows(array $rows, Table $table)
{
$table->setRows($rows);
$table->render();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment