SelectCommand.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Commands;
  3. use App\AppService;
  4. use Symfony\Component\Console\Helper\Table;
  5. use Symfony\Component\Console\Command\Command;
  6. use Symfony\Component\Console\Input\InputArgument;
  7. use Symfony\Component\Console\Input\InputInterface;
  8. use Symfony\Component\Console\Output\OutputInterface;
  9. use YdbPlatform\Ydb\Session;
  10. use YdbPlatform\Ydb\Ydb;
  11. class SelectCommand extends Command
  12. {
  13. /**
  14. * @var string
  15. */
  16. protected static $defaultName = 'select';
  17. /**
  18. * @var AppService
  19. */
  20. protected $appService;
  21. public function __construct()
  22. {
  23. $this->appService = new AppService;
  24. parent::__construct();
  25. }
  26. protected function configure()
  27. {
  28. $this->setDescription('Select rows form a table.');
  29. $this->addArgument('table', InputArgument::REQUIRED, 'The table name.');
  30. }
  31. /**
  32. * @param InputInterface $input
  33. * @param OutputInterface $output
  34. * @return int
  35. * @throws \YandexCloud\Ydb\Exception
  36. */
  37. protected function execute(InputInterface $input, OutputInterface $output)
  38. {
  39. $table_name = $input->getArgument('table') ?: '';
  40. $ydb = $this->appService->initYdb();
  41. $result = $ydb->table()->retrySession(function (Session $session) use ($table_name, $output) {
  42. return $session->query('select * from `' . $table_name . '` limit 10;');
  43. }, true);
  44. $output->writeln('Column count: ' . $result->columnCount());
  45. $output->writeln('Row count: ' . $result->rowCount());
  46. $t = new Table($output);
  47. $t
  48. ->setHeaders(array_map(function($column) {
  49. return $column['name'];
  50. }, $result->columns()))
  51. ->setRows($result->rows())
  52. ;
  53. $t->render();
  54. return Command::SUCCESS;
  55. }
  56. }