Unverified Commit 62201f99 authored by Sergei Morozov's avatar Sergei Morozov Committed by GitHub

Merge pull request #3956 from dmaicher/cli_multi_connection

allow using multiple connections for CLI commands
parents a8544cac b10d4db8
<?php <?php
use Doctrine\DBAL\Tools\Console\ConnectionProvider;
use Doctrine\DBAL\Tools\Console\ConsoleRunner; use Doctrine\DBAL\Tools\Console\ConsoleRunner;
use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\HelperSet;
...@@ -42,16 +43,16 @@ if (! is_readable($configFile)) { ...@@ -42,16 +43,16 @@ if (! is_readable($configFile)) {
} }
$commands = []; $commands = [];
$helperSet = require $configFile; $helperSetOrConnectionProvider = require $configFile;
if (! $helperSet instanceof HelperSet) { if (! $helperSetOrConnectionProvider instanceof HelperSet && ! $helperSetOrConnectionProvider instanceof ConnectionProvider) {
foreach ($GLOBALS as $helperSetCandidate) { foreach ($GLOBALS as $candidate) {
if ($helperSetCandidate instanceof HelperSet) { if ($candidate instanceof HelperSet) {
$helperSet = $helperSetCandidate; $helperSetOrConnectionProvider = $candidate;
break; break;
} }
} }
} }
ConsoleRunner::run($helperSet, $commands); ConsoleRunner::run($helperSetOrConnectionProvider, $commands);
...@@ -21,6 +21,8 @@ use Doctrine\DBAL\Platforms\Keywords\SQLServer2005Keywords; ...@@ -21,6 +21,8 @@ use Doctrine\DBAL\Platforms\Keywords\SQLServer2005Keywords;
use Doctrine\DBAL\Platforms\Keywords\SQLServer2008Keywords; use Doctrine\DBAL\Platforms\Keywords\SQLServer2008Keywords;
use Doctrine\DBAL\Platforms\Keywords\SQLServer2012Keywords; use Doctrine\DBAL\Platforms\Keywords\SQLServer2012Keywords;
use Doctrine\DBAL\Platforms\Keywords\SQLServerKeywords; use Doctrine\DBAL\Platforms\Keywords\SQLServerKeywords;
use Doctrine\DBAL\Tools\Console\ConnectionProvider;
use Exception;
use InvalidArgumentException; use InvalidArgumentException;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
...@@ -30,6 +32,9 @@ use function array_keys; ...@@ -30,6 +32,9 @@ use function array_keys;
use function assert; use function assert;
use function count; use function count;
use function implode; use function implode;
use function is_string;
use function trigger_error;
use const E_USER_DEPRECATED;
class ReservedWordsCommand extends Command class ReservedWordsCommand extends Command
{ {
...@@ -54,6 +59,20 @@ class ReservedWordsCommand extends Command ...@@ -54,6 +59,20 @@ class ReservedWordsCommand extends Command
'sqlanywhere16' => SQLAnywhere16Keywords::class, 'sqlanywhere16' => SQLAnywhere16Keywords::class,
]; ];
/** @var ConnectionProvider|null */
private $connectionProvider;
public function __construct(?ConnectionProvider $connectionProvider = null)
{
parent::__construct();
$this->connectionProvider = $connectionProvider;
if ($connectionProvider !== null) {
return;
}
@trigger_error('Not passing a connection provider as the first constructor argument is deprecated', E_USER_DEPRECATED);
}
/** /**
* If you want to add or replace a keywords list use this command. * If you want to add or replace a keywords list use this command.
* *
...@@ -73,7 +92,9 @@ class ReservedWordsCommand extends Command ...@@ -73,7 +92,9 @@ class ReservedWordsCommand extends Command
$this $this
->setName('dbal:reserved-words') ->setName('dbal:reserved-words')
->setDescription('Checks if the current database contains identifiers that are reserved.') ->setDescription('Checks if the current database contains identifiers that are reserved.')
->setDefinition([new InputOption( ->setDefinition([
new InputOption('connection', null, InputOption::VALUE_REQUIRED, 'The named database connection'),
new InputOption(
'list', 'list',
'l', 'l',
InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
...@@ -121,8 +142,7 @@ EOT ...@@ -121,8 +142,7 @@ EOT
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
$conn = $this->getHelper('db')->getConnection(); $conn = $this->getConnection($input);
assert($conn instanceof Connection);
$keywordLists = (array) $input->getOption('list'); $keywordLists = (array) $input->getOption('list');
if (! $keywordLists) { if (! $keywordLists) {
...@@ -178,4 +198,24 @@ EOT ...@@ -178,4 +198,24 @@ EOT
return 0; return 0;
} }
private function getConnection(InputInterface $input) : Connection
{
$connectionName = $input->getOption('connection');
assert(is_string($connectionName) || $connectionName === null);
if ($this->connectionProvider === null) {
if ($connectionName !== null) {
throw new Exception('Specifying a connection is only supported when a ConnectionProvider is used.');
}
return $this->getHelper('db')->getConnection();
}
if ($connectionName !== null) {
return $this->connectionProvider->getConnection($connectionName);
}
return $this->connectionProvider->getDefaultConnection();
}
} }
...@@ -2,7 +2,10 @@ ...@@ -2,7 +2,10 @@
namespace Doctrine\DBAL\Tools\Console\Command; namespace Doctrine\DBAL\Tools\Console\Command;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Tools\Console\ConnectionProvider;
use Doctrine\DBAL\Tools\Dumper; use Doctrine\DBAL\Tools\Dumper;
use Exception;
use LogicException; use LogicException;
use RuntimeException; use RuntimeException;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
...@@ -14,6 +17,8 @@ use function assert; ...@@ -14,6 +17,8 @@ use function assert;
use function is_numeric; use function is_numeric;
use function is_string; use function is_string;
use function stripos; use function stripos;
use function trigger_error;
use const E_USER_DEPRECATED;
/** /**
* Task for executing arbitrary SQL that can come from a file or directly from * Task for executing arbitrary SQL that can come from a file or directly from
...@@ -21,6 +26,20 @@ use function stripos; ...@@ -21,6 +26,20 @@ use function stripos;
*/ */
class RunSqlCommand extends Command class RunSqlCommand extends Command
{ {
/** @var ConnectionProvider|null */
private $connectionProvider;
public function __construct(?ConnectionProvider $connectionProvider = null)
{
parent::__construct();
$this->connectionProvider = $connectionProvider;
if ($connectionProvider !== null) {
return;
}
@trigger_error('Not passing a connection provider as the first constructor argument is deprecated', E_USER_DEPRECATED);
}
/** @return void */ /** @return void */
protected function configure() protected function configure()
{ {
...@@ -28,6 +47,7 @@ class RunSqlCommand extends Command ...@@ -28,6 +47,7 @@ class RunSqlCommand extends Command
->setName('dbal:run-sql') ->setName('dbal:run-sql')
->setDescription('Executes arbitrary SQL directly from the command line.') ->setDescription('Executes arbitrary SQL directly from the command line.')
->setDefinition([ ->setDefinition([
new InputOption('connection', null, InputOption::VALUE_REQUIRED, 'The named database connection'),
new InputArgument('sql', InputArgument::REQUIRED, 'The SQL statement to execute.'), new InputArgument('sql', InputArgument::REQUIRED, 'The SQL statement to execute.'),
new InputOption('depth', null, InputOption::VALUE_REQUIRED, 'Dumping depth of result set.', 7), new InputOption('depth', null, InputOption::VALUE_REQUIRED, 'Dumping depth of result set.', 7),
new InputOption('force-fetch', null, InputOption::VALUE_NONE, 'Forces fetching the result.'), new InputOption('force-fetch', null, InputOption::VALUE_NONE, 'Forces fetching the result.'),
...@@ -43,7 +63,7 @@ EOT ...@@ -43,7 +63,7 @@ EOT
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
$conn = $this->getHelper('db')->getConnection(); $conn = $this->getConnection($input);
$sql = $input->getArgument('sql'); $sql = $input->getArgument('sql');
...@@ -69,4 +89,24 @@ EOT ...@@ -69,4 +89,24 @@ EOT
return 0; return 0;
} }
private function getConnection(InputInterface $input) : Connection
{
$connectionName = $input->getOption('connection');
assert(is_string($connectionName) || $connectionName === null);
if ($this->connectionProvider === null) {
if ($connectionName !== null) {
throw new Exception('Specifying a connection is only supported when a ConnectionProvider is used.');
}
return $this->getHelper('db')->getConnection();
}
if ($connectionName !== null) {
return $this->connectionProvider->getConnection($connectionName);
}
return $this->connectionProvider->getDefaultConnection();
}
} }
<?php
namespace Doctrine\DBAL\Tools\Console;
use OutOfBoundsException;
final class ConnectionNotFound extends OutOfBoundsException
{
}
<?php
namespace Doctrine\DBAL\Tools\Console;
use Doctrine\DBAL\Connection;
interface ConnectionProvider
{
public function getDefaultConnection() : Connection;
/**
* @throws ConnectionNotFound in case a connection with the given name does not exist.
*/
public function getConnection(string $name) : Connection;
}
<?php
namespace Doctrine\DBAL\Tools\Console\ConnectionProvider;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Tools\Console\ConnectionNotFound;
use Doctrine\DBAL\Tools\Console\ConnectionProvider;
use function sprintf;
class SingleConnectionProvider implements ConnectionProvider
{
/** @var Connection */
private $connection;
/** @var string */
private $defaultConnectionName;
public function __construct(Connection $connection, string $defaultConnectionName = 'default')
{
$this->connection = $connection;
$this->defaultConnectionName = $defaultConnectionName;
}
public function getDefaultConnection() : Connection
{
return $this->connection;
}
public function getConnection(string $name) : Connection
{
if ($name !== $this->defaultConnectionName) {
throw new ConnectionNotFound(sprintf('Connection with name "%s" does not exist.', $name));
}
return $this->connection;
}
}
...@@ -11,6 +11,10 @@ use Doctrine\DBAL\Version; ...@@ -11,6 +11,10 @@ use Doctrine\DBAL\Version;
use Symfony\Component\Console\Application; use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\HelperSet;
use TypeError;
use function sprintf;
use function trigger_error;
use const E_USER_DEPRECATED;
/** /**
* Handles running the Console Tools inside Symfony Console context. * Handles running the Console Tools inside Symfony Console context.
...@@ -20,6 +24,8 @@ class ConsoleRunner ...@@ -20,6 +24,8 @@ class ConsoleRunner
/** /**
* Create a Symfony Console HelperSet * Create a Symfony Console HelperSet
* *
* @deprecated use a ConnectionProvider instead.
*
* @return HelperSet * @return HelperSet
*/ */
public static function createHelperSet(Connection $connection) public static function createHelperSet(Connection $connection)
...@@ -30,20 +36,31 @@ class ConsoleRunner ...@@ -30,20 +36,31 @@ class ConsoleRunner
} }
/** /**
* Runs console with the given helperset. * Runs console with the given connection provider or helperset (deprecated).
* *
* @param ConnectionProvider|HelperSet $helperSetOrConnectionProvider
* @param Command[] $commands * @param Command[] $commands
* *
* @return void * @return void
*/ */
public static function run(HelperSet $helperSet, $commands = []) public static function run($helperSetOrConnectionProvider, $commands = [])
{ {
$cli = new Application('Doctrine Command Line Interface', Version::VERSION); $cli = new Application('Doctrine Command Line Interface', Version::VERSION);
$cli->setCatchExceptions(true); $cli->setCatchExceptions(true);
$cli->setHelperSet($helperSet);
self::addCommands($cli); $connectionProvider = null;
if ($helperSetOrConnectionProvider instanceof HelperSet) {
@trigger_error(sprintf('Passing an instance of "%s" as the first argument is deprecated. Pass an instance of "%s" instead.', HelperSet::class, ConnectionProvider::class), E_USER_DEPRECATED);
$connectionProvider = null;
$cli->setHelperSet($helperSetOrConnectionProvider);
} elseif ($helperSetOrConnectionProvider instanceof ConnectionProvider) {
$connectionProvider = $helperSetOrConnectionProvider;
} else {
throw new TypeError(sprintf('First argument must be an instance of "%s" or "%s"', HelperSet::class, ConnectionProvider::class));
}
self::addCommands($cli, $connectionProvider);
$cli->addCommands($commands); $cli->addCommands($commands);
$cli->run(); $cli->run();
...@@ -52,12 +69,12 @@ class ConsoleRunner ...@@ -52,12 +69,12 @@ class ConsoleRunner
/** /**
* @return void * @return void
*/ */
public static function addCommands(Application $cli) public static function addCommands(Application $cli, ?ConnectionProvider $connectionProvider = null)
{ {
$cli->addCommands([ $cli->addCommands([
new RunSqlCommand(), new RunSqlCommand($connectionProvider),
new ImportCommand(), new ImportCommand(),
new ReservedWordsCommand(), new ReservedWordsCommand($connectionProvider),
]); ]);
} }
...@@ -74,14 +91,17 @@ project, which is required to get the Doctrine-DBAL Console working. You can use ...@@ -74,14 +91,17 @@ project, which is required to get the Doctrine-DBAL Console working. You can use
following sample as a template: following sample as a template:
<?php <?php
use Doctrine\DBAL\Tools\Console\ConsoleRunner; use Doctrine\DBAL\Tools\Console\ConnectionProvider\SingleConnectionProvider;
// replace with the mechanism to retrieve DBAL connection in your app
$connection = getDBALConnection();
// You can append new commands to $commands array, if needed // You can append new commands to $commands array, if needed
return ConsoleRunner::createHelperSet($connection); // replace with the mechanism to retrieve DBAL connection(s) in your app
// and return a Doctrine\DBAL\Tools\Console\ConnectionProvider instance.
$connection = getDBALConnection();
// in case you have a single connection you can use SingleConnectionProvider
// otherwise you need to implement the Doctrine\DBAL\Tools\Console\ConnectionProvider interface with your custom logic
return new SingleConnectionProvider($connection);
HELP; HELP;
} }
......
...@@ -7,6 +7,8 @@ use Symfony\Component\Console\Helper\Helper; ...@@ -7,6 +7,8 @@ use Symfony\Component\Console\Helper\Helper;
/** /**
* Doctrine CLI Connection Helper. * Doctrine CLI Connection Helper.
*
* @deprecated use a ConnectionProvider instead.
*/ */
class ConnectionHelper extends Helper class ConnectionHelper extends Helper
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment