DbCommandBase.php 2.1 KB

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