AddMissingColumns.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Command\Db;
  8. use OC\DB\Connection;
  9. use OC\DB\SchemaWrapper;
  10. use OCP\DB\Events\AddMissingColumnsEvent;
  11. use OCP\EventDispatcher\IEventDispatcher;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Input\InputOption;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. /**
  17. * Class AddMissingColumns
  18. *
  19. * if you added a new lazy column to the database, this is the right place to add
  20. * your update routine for existing instances
  21. *
  22. * @package OC\Core\Command\Db
  23. */
  24. class AddMissingColumns extends Command {
  25. public function __construct(
  26. private Connection $connection,
  27. private IEventDispatcher $dispatcher,
  28. ) {
  29. parent::__construct();
  30. }
  31. protected function configure() {
  32. $this
  33. ->setName('db:add-missing-columns')
  34. ->setDescription('Add missing optional columns to the database tables')
  35. ->addOption('dry-run', null, InputOption::VALUE_NONE, "Output the SQL queries instead of running them.");
  36. }
  37. protected function execute(InputInterface $input, OutputInterface $output): int {
  38. $dryRun = $input->getOption('dry-run');
  39. // Dispatch event so apps can also update columns if needed
  40. $event = new AddMissingColumnsEvent();
  41. $this->dispatcher->dispatchTyped($event);
  42. $missingColumns = $event->getMissingColumns();
  43. $updated = false;
  44. if (!empty($missingColumns)) {
  45. $schema = new SchemaWrapper($this->connection);
  46. foreach ($missingColumns as $missingColumn) {
  47. if ($schema->hasTable($missingColumn['tableName'])) {
  48. $table = $schema->getTable($missingColumn['tableName']);
  49. if (!$table->hasColumn($missingColumn['columnName'])) {
  50. $output->writeln('<info>Adding additional ' . $missingColumn['columnName'] . ' column to the ' . $missingColumn['tableName'] . ' table, this can take some time...</info>');
  51. $table->addColumn($missingColumn['columnName'], $missingColumn['typeName'], $missingColumn['options']);
  52. $sqlQueries = $this->connection->migrateToSchema($schema->getWrappedSchema(), $dryRun);
  53. if ($dryRun && $sqlQueries !== null) {
  54. $output->writeln($sqlQueries);
  55. }
  56. $updated = true;
  57. $output->writeln('<info>' . $missingColumn['tableName'] . ' table updated successfully.</info>');
  58. }
  59. }
  60. }
  61. }
  62. if (!$updated) {
  63. $output->writeln('<info>Done.</info>');
  64. }
  65. return 0;
  66. }
  67. }