From 2e8469b11a5042389dfa6e5002fb11fc13eb0002 Mon Sep 17 00:00:00 2001 From: Tim Date: Sun, 19 Sep 2021 20:39:10 +0200 Subject: [PATCH] Add command to create database --- src/Console/CreateDatabaseCommand.php | 43 +++++++++++++++++++++++++++ src/Service/DatabaseManager.php | 13 ++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/Console/CreateDatabaseCommand.php diff --git a/src/Console/CreateDatabaseCommand.php b/src/Console/CreateDatabaseCommand.php new file mode 100644 index 0000000..d6545f7 --- /dev/null +++ b/src/Console/CreateDatabaseCommand.php @@ -0,0 +1,43 @@ +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; + } +} \ No newline at end of file diff --git a/src/Service/DatabaseManager.php b/src/Service/DatabaseManager.php index 13ff537..c102186 100644 --- a/src/Service/DatabaseManager.php +++ b/src/Service/DatabaseManager.php @@ -25,4 +25,17 @@ class DatabaseManager 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)); + } + } } \ No newline at end of file