Add command to create database
This commit is contained in:
parent
2fd43ed717
commit
2e8469b11a
43
src/Console/CreateDatabaseCommand.php
Normal file
43
src/Console/CreateDatabaseCommand.php
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user