Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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