Implement mysqldump/backup service/command

This commit is contained in:
Tim
2021-12-16 00:58:17 +01:00
parent 0ff9021d6e
commit 11089d82bc
9 changed files with 122 additions and 29 deletions

View File

@ -0,0 +1,57 @@
<?php
namespace App\Service;
use mysqli;
class DatabaseService
{
private mysqli $conn;
public function __construct(
private MysqliConnection $service
)
{
$this->conn = $this->service->getConnection();
}
public function listDatabases(): array
{
$dbs = [];
$results = $this->conn->query('SHOW DATABASES');
while ($result = $results->fetch_object()) {
$dbs[] = $result->Database;
}
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));
}
}
public function listUsers(): array
{
$results = $this->conn->query('select * from mysql.user');
$users = [];
while ($result = $results->fetch_object()) {
$users[] = [
'name' => $result->User,
'host' => $result->Host,
'plugin' => $result->plugin,
];
}
return $users;
}
}