3 namespace Drupal\Core\Command;
5 use Drupal\Core\Database\Connection;
6 use Drupal\Core\Database\Database;
7 use Drupal\Core\Database\SchemaObjectExistsException;
8 use Symfony\Component\Console\Input\InputInterface;
9 use Symfony\Component\Console\Input\InputOption;
10 use Symfony\Component\Console\Output\OutputInterface;
13 * Provides a command to import the current database from a script.
15 * This script runs on databases exported using using one of the database dump
16 * commands and imports it into the current database connection.
18 * @see \Drupal\Core\Command\DbImportApplication
20 class DbImportCommand extends DbCommandBase {
25 protected function configure() {
27 $this->setName('import')
28 ->setDescription('Import database from a generation script.')
29 ->addArgument('script', InputOption::VALUE_REQUIRED, 'Import script');
35 protected function execute(InputInterface $input, OutputInterface $output) {
36 $script = $input->getArgument('script');
37 if (!is_file($script)) {
38 $output->writeln('File must exist.');
42 $connection = $this->getDatabaseConnection($input);
43 $this->runScript($connection, $script);
44 $output->writeln('Import completed successfully.');
48 * Run the database script.
50 * @param \Drupal\Core\Database\Connection $connection
51 * Connection used by the script when included.
52 * @param string $script
53 * Path to dump script.
55 protected function runScript(Connection $connection, $script) {
56 $old_key = Database::setActiveConnection($connection->getKey());
58 if (substr($script, -3) == '.gz') {
59 $script = "compress.zlib://$script";
64 catch (SchemaObjectExistsException $e) {
65 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.');
67 Database::setActiveConnection($old_key);