3 namespace Drupal\Core\Command;
5 use Drupal\Core\Database\Database;
6 use Symfony\Component\Console\Command\Command;
7 use Symfony\Component\Console\Input\InputInterface;
8 use Symfony\Component\Console\Input\InputOption;
11 * Base command that abstracts handling of database connection arguments.
13 class DbCommandBase extends Command {
18 protected function configure() {
19 $this->addOption('database', NULL, InputOption::VALUE_OPTIONAL, 'The database connection name to use.', 'default')
20 ->addOption('database-url', 'db-url', InputOption::VALUE_OPTIONAL, 'A database url to parse and use as the database connection.')
21 ->addOption('prefix', NULL, InputOption::VALUE_OPTIONAL, 'Override or set the table prefix used in the database connection.');
25 * Parse input options decide on a database.
27 * @param \Symfony\Component\Console\Input\InputInterface $input
29 * @return \Drupal\Core\Database\Connection
31 protected function getDatabaseConnection(InputInterface $input) {
32 // Load connection from a url.
33 if ($input->getOption('database-url')) {
34 // @todo this could probably be refactored to not use a global connection.
35 // Ensure database connection isn't set.
36 if (Database::getConnectionInfo('db-tools')) {
37 throw new \RuntimeException('Database "db-tools" is already defined. Cannot define database provided.');
39 $info = Database::convertDbUrlToConnectionInfo($input->getOption('database-url'), \Drupal::root());
40 Database::addConnectionInfo('db-tools', 'default', $info);
44 $key = $input->getOption('database');
47 // If they supplied a prefix, replace it in the connection information.
48 $prefix = $input->getOption('prefix');
50 $info = Database::getConnectionInfo($key)['default'];
51 $info['prefix']['default'] = $prefix;
53 Database::removeConnection($key);
54 Database::addConnectionInfo($key, 'default', $info);
57 return Database::getConnection('default', $key);