QueryExecuteCommand.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Michel\PaperORM\Command;
  3. use Michel\Console\Argument\CommandArgument;
  4. use Michel\Console\Command\CommandInterface;
  5. use Michel\Console\InputInterface;
  6. use Michel\Console\Output\ConsoleOutput;
  7. use Michel\Console\OutputInterface;
  8. use Michel\PaperORM\EntityManager;
  9. use Michel\PaperORM\EntityManagerInterface;
  10. class QueryExecuteCommand implements CommandInterface
  11. {
  12. private EntityManagerInterface $entityManager;
  13. public function __construct(EntityManagerInterface $entityManager)
  14. {
  15. $this->entityManager = $entityManager;
  16. }
  17. public function getName(): string
  18. {
  19. return 'paper:query:execute';
  20. }
  21. public function getDescription(): string
  22. {
  23. return 'Execute a SQL query';
  24. }
  25. public function getOptions(): array
  26. {
  27. return [];
  28. }
  29. public function getArguments(): array
  30. {
  31. return [
  32. new CommandArgument('query', true, null, 'The SQL query : select * from users')
  33. ];
  34. }
  35. public function execute(InputInterface $input, OutputInterface $output): void
  36. {
  37. $io = ConsoleOutput::create($output);
  38. $query = $input->hasArgument("query") ? $input->getArgumentValue("query") : null;
  39. if ($query === null) {
  40. throw new \LogicException("SQL query is required");
  41. }
  42. $io->title('Starting query on ' . $this->entityManager->getPlatform()->getDatabaseName());
  43. $data = $this->entityManager->getConnection()->fetchAll($query);
  44. $io->listKeyValues([
  45. 'query' => $query,
  46. 'rows' => count($data),
  47. ]);
  48. if ($data === []) {
  49. $io->info('The query yielded an empty result set.');
  50. return;
  51. }
  52. $io->table(array_keys($data[0]), $data);
  53. }
  54. }