CreateTableCommand.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Commands;
  3. use App\AppService;
  4. use Symfony\Component\Console\Command\Command;
  5. use Symfony\Component\Console\Input\InputArgument;
  6. use Symfony\Component\Console\Input\InputInterface;
  7. use Symfony\Component\Console\Output\OutputInterface;
  8. use YdbPlatform\Ydb\Session;
  9. class CreateTableCommand extends Command
  10. {
  11. /**
  12. * @var string
  13. */
  14. protected static $defaultName = 'create';
  15. /**
  16. * @var AppService
  17. */
  18. protected $appService;
  19. public function __construct()
  20. {
  21. $this->appService = new AppService;
  22. parent::__construct();
  23. }
  24. protected function configure()
  25. {
  26. $this->setDescription('Create a table.');
  27. $this->addArgument('table', InputArgument::REQUIRED, 'The table name.');
  28. }
  29. /**
  30. * @param InputInterface $input
  31. * @param OutputInterface $output
  32. * @return int
  33. * @throws \Exception
  34. */
  35. protected function execute(InputInterface $input, OutputInterface $output)
  36. {
  37. $table_name = $input->getArgument('table') ?: '';
  38. $columns = $this->getColumns();
  39. $ydb = $this->appService->initYdb();
  40. $ydb->table()->retrySession(function (Session $session) use ($columns, $table_name) {
  41. $session->createTable($table_name, $columns, 'id');
  42. },true);
  43. $output->writeln('Table ' . $table_name . ' has been created.');
  44. $ydb->table()->retryTransaction(function (Session $session) use ($columns, $table_name) {
  45. $session->query('upsert into `' . $table_name . '` (`' . implode('`, `', array_keys($columns)) . '`) values (' . implode('), (', $this->getData()) . ');');
  46. },true);
  47. $output->writeln('Table ' . $table_name . ' has been populated with some data.');
  48. return Command::SUCCESS;
  49. }
  50. /**
  51. * @return array
  52. */
  53. protected function getColumns()
  54. {
  55. return [
  56. 'id' => 'UINT64',
  57. 'name' => 'UTF8',
  58. 'type' => 'STRING',
  59. 'status' => 'UINT32',
  60. 'created_at' => 'DATETIME',
  61. ];
  62. }
  63. /**
  64. * @return array
  65. */
  66. protected function getData()
  67. {
  68. return [
  69. '1, "Item 1", "basic", 1, Datetime("' . date('Y-m-d\TH:i:s\Z') . '")',
  70. '2, "Item 2", "medium", 1, Datetime("' . date('Y-m-d\TH:i:s\Z') . '")',
  71. '3, "Item 3", "basic", 2, Datetime("' . date('Y-m-d\TH:i:s\Z') . '")',
  72. '4, "Item 4", "medium", 2, Datetime("' . date('Y-m-d\TH:i:s\Z') . '")',
  73. ];
  74. }
  75. }