setName('doctrine:database:create')
->setDescription('Creates the configured database')
->addOption('connection', 'c', InputOption::VALUE_OPTIONAL, 'The connection to use for this command')
->addOption('if-not-exists', null, InputOption::VALUE_NONE, 'Don\'t trigger an error, when the database already exists')
->setHelp(<<<'EOT'
The %command.name% command creates the default connections database:
php %command.full_name%
You can also optionally specify the name of a connection to create the database for:
php %command.full_name% --connection=default
EOT);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$connectionName = $input->getOption('connection');
if (empty($connectionName)) {
$connectionName = $this->getDoctrine()->getDefaultConnectionName();
}
$connection = $this->getDoctrineConnection($connectionName);
$ifNotExists = $input->getOption('if-not-exists');
$params = $connection->getParams();
if (isset($params['primary'])) {
$params = $params['primary'];
}
$hasPath = isset($params['path']);
$name = $hasPath ? $params['path'] : ($params['dbname'] ?? false);
if (! $name) {
throw new InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be created.");
}
// Need to get rid of _every_ occurrence of dbname from connection configuration and we have already extracted all relevant info from url
unset($params['dbname'], $params['path'], $params['url']);
$tmpConnection = DriverManager::getConnection($params, $connection->getConfiguration());
$schemaManager = method_exists($tmpConnection, 'createSchemaManager')
? $tmpConnection->createSchemaManager()
: $tmpConnection->getSchemaManager();
$shouldNotCreateDatabase = $ifNotExists && in_array($name, $schemaManager->listDatabases());
// Only quote if we don't have a path
if (! $hasPath) {
$name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
}
$error = false;
try {
if ($shouldNotCreateDatabase) {
$output->writeln(sprintf('Database %s for connection named %s already exists. Skipped.', $name, $connectionName));
} else {
$schemaManager->createDatabase($name);
$output->writeln(sprintf('Created database %s for connection named %s', $name, $connectionName));
}
} catch (Throwable $e) {
$output->writeln(sprintf('Could not create database %s for connection named %s', $name, $connectionName));
$output->writeln(sprintf('%s', $e->getMessage()));
$error = true;
}
$tmpConnection->close();
return $error ? 1 : 0;
}
}