DbCommandBase.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. *
  25. * @return \Drupal\Core\Database\Connection
  26. */
  27. protected function getDatabaseConnection(InputInterface $input) {
  28. // Load connection from a url.
  29. if ($input->getOption('database-url')) {
  30. // @todo this could probably be refactored to not use a global connection.
  31. // Ensure database connection isn't set.
  32. if (Database::getConnectionInfo('db-tools')) {
  33. throw new \RuntimeException('Database "db-tools" is already defined. Cannot define database provided.');
  34. }
  35. $info = Database::convertDbUrlToConnectionInfo($input->getOption('database-url'), \Drupal::root());
  36. Database::addConnectionInfo('db-tools', 'default', $info);
  37. $key = 'db-tools';
  38. }
  39. else {
  40. $key = $input->getOption('database');
  41. }
  42. // If they supplied a prefix, replace it in the connection information.
  43. $prefix = $input->getOption('prefix');
  44. if ($prefix) {
  45. $info = Database::getConnectionInfo($key)['default'];
  46. $info['prefix']['default'] = $prefix;
  47. Database::removeConnection($key);
  48. Database::addConnectionInfo($key, 'default', $info);
  49. }
  50. return Database::getConnection('default', $key);
  51. }
  52. }