DbImportCommand.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Drupal\Core\Command;
  3. use Drupal\Core\Database\Connection;
  4. use Drupal\Core\Database\Database;
  5. use Drupal\Core\Database\SchemaObjectExistsException;
  6. use Symfony\Component\Console\Input\InputInterface;
  7. use Symfony\Component\Console\Input\InputOption;
  8. use Symfony\Component\Console\Output\OutputInterface;
  9. /**
  10. * Provides a command to import the current database from a script.
  11. *
  12. * This script runs on databases exported using using one of the database dump
  13. * commands and imports it into the current database connection.
  14. *
  15. * @see \Drupal\Core\Command\DbImportApplication
  16. */
  17. class DbImportCommand extends DbCommandBase {
  18. /**
  19. * {@inheritdoc}
  20. */
  21. protected function configure() {
  22. parent::configure();
  23. $this->setName('import')
  24. ->setDescription('Import database from a generation script.')
  25. ->addArgument('script', InputOption::VALUE_REQUIRED, 'Import script');
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. protected function execute(InputInterface $input, OutputInterface $output) {
  31. $script = $input->getArgument('script');
  32. if (!is_file($script)) {
  33. $output->writeln('File must exist.');
  34. return;
  35. }
  36. $connection = $this->getDatabaseConnection($input);
  37. $this->runScript($connection, $script);
  38. $output->writeln('Import completed successfully.');
  39. }
  40. /**
  41. * Run the database script.
  42. *
  43. * @param \Drupal\Core\Database\Connection $connection
  44. * Connection used by the script when included.
  45. * @param string $script
  46. * Path to dump script.
  47. */
  48. protected function runScript(Connection $connection, $script) {
  49. $old_key = Database::setActiveConnection($connection->getKey());
  50. if (substr($script, -3) == '.gz') {
  51. $script = "compress.zlib://$script";
  52. }
  53. try {
  54. require $script;
  55. }
  56. catch (SchemaObjectExistsException $e) {
  57. throw new \RuntimeException('An existing Drupal installation exists at this location. Try removing all tables or changing the database prefix in your settings.php file.');
  58. }
  59. Database::setActiveConnection($old_key);
  60. }
  61. }