ExpectedSchema.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Robin Appelman <robin@icewind.nl>
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Command\Db;
  8. use Doctrine\DBAL\Schema\Schema;
  9. use OC\Core\Command\Base;
  10. use OC\DB\Connection;
  11. use OC\DB\MigrationService;
  12. use OC\DB\SchemaWrapper;
  13. use OC\Migration\NullOutput;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Input\InputOption;
  16. use Symfony\Component\Console\Output\OutputInterface;
  17. class ExpectedSchema extends Base {
  18. public function __construct(
  19. protected Connection $connection,
  20. ) {
  21. parent::__construct();
  22. }
  23. protected function configure(): void {
  24. $this
  25. ->setName('db:schema:expected')
  26. ->setDescription('Export the expected database schema for a fresh installation')
  27. ->setHelp("Note that the expected schema might not exactly match the exported live schema as the expected schema doesn't take into account any database wide settings or defaults.")
  28. ->addOption('sql', null, InputOption::VALUE_NONE, 'Dump the SQL statements for creating the expected schema');
  29. parent::configure();
  30. }
  31. protected function execute(InputInterface $input, OutputInterface $output): int {
  32. $schema = new Schema();
  33. $this->applyMigrations('core', $schema);
  34. $apps = \OC_App::getEnabledApps();
  35. foreach ($apps as $app) {
  36. $this->applyMigrations($app, $schema);
  37. }
  38. $sql = $input->getOption('sql');
  39. if ($sql) {
  40. $output->writeln($schema->toSql($this->connection->getDatabasePlatform()));
  41. } else {
  42. $encoder = new SchemaEncoder();
  43. $this->writeArrayInOutputFormat($input, $output, $encoder->encodeSchema($schema, $this->connection->getDatabasePlatform()));
  44. }
  45. return 0;
  46. }
  47. private function applyMigrations(string $app, Schema $schema): void {
  48. $output = new NullOutput();
  49. $ms = new MigrationService($app, $this->connection, $output);
  50. foreach ($ms->getAvailableVersions() as $version) {
  51. $migration = $ms->createInstance($version);
  52. $migration->changeSchema($output, function () use (&$schema) {
  53. return new SchemaWrapper($this->connection, $schema);
  54. }, []);
  55. }
  56. }
  57. }