Add command to create database

This commit is contained in:
Tim 2021-09-19 20:39:10 +02:00
parent 2fd43ed717
commit 2e8469b11a
2 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,43 @@
<?php
namespace App\Console;
use App\Service\DatabaseManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
class CreateDatabaseCommand extends Command
{
// the name of the command (the part after "bin/console")
protected static $defaultName = 'app:db:create';
public function __construct(
private DatabaseManager $db,
)
{
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('name', InputArgument::OPTIONAL, 'Database name');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$question = $this->getHelper('question');
if (!$name = $input->getArgument('name')) {
$name = $question->ask($input, $output, new Question('Database name: '));
}
$this->db->createDatabase($name);
$output->writeln(sprintf('Database "%s" successfully created', $name));
return Command::SUCCESS;
}
}

View File

@ -25,4 +25,17 @@ class DatabaseManager
return $dbs; return $dbs;
} }
public function createDatabase(string $name)
{
$dbs = $this->listDatabases();
if(in_array($name, $dbs)) {
throw new \Exception(sprintf('Database "%s" already exists', $name));
}
$result = $this->conn->query(sprintf('CREATE DATABASE `%s`', $name));
if (!$result) {
throw new \Exception(sprintf('Database create error: %s', $this->conn->error));
}
}
} }