First Commit
This commit is contained in:
Executable
+60
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
|
||||
class DbQueryCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'db:query';
|
||||
protected static $defaultDescription = 'Executa uma query SQL diretamente no banco de dados';
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->addArgument('query', InputArgument::REQUIRED, 'A query SQL a ser executada');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$query = $input->getArgument('query');
|
||||
$connection = Capsule::connection();
|
||||
|
||||
$output->writeln("<info>Executando query:</info> <comment>{$query}</comment>");
|
||||
|
||||
try {
|
||||
if (stripos($query, 'select') === 0 || stripos($query, 'show') === 0 || stripos($query, 'describe') === 0) {
|
||||
$results = $connection->select($query);
|
||||
|
||||
if (empty($results)) {
|
||||
$output->writeln('<info>Nenhum resultado encontrado.</info>');
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$table = new Table($output);
|
||||
$headers = array_keys((array) $results[0]);
|
||||
$table->setHeaders($headers);
|
||||
|
||||
foreach ($results as $row) {
|
||||
$table->addRow((array) $row);
|
||||
}
|
||||
|
||||
$table->render();
|
||||
$output->writeln("<info>Total de registros: " . count($results) . "</info>");
|
||||
} else {
|
||||
$affected = $connection->affectingStatement($query);
|
||||
$output->writeln("<info>Query executada com sucesso. Linhas afetadas: {$affected}</info>");
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$output->writeln("<error>Erro ao executar query: " . $e->getMessage() . "</error>");
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user