72 lines
1.7 KiB
PHP
72 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use Exception;
|
|
use mysqli;
|
|
|
|
class DatabaseService
|
|
{
|
|
private mysqli $conn;
|
|
|
|
public function __construct(
|
|
private readonly 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): void
|
|
{
|
|
$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;
|
|
}
|
|
|
|
public function deleteDatabase(string $name): void
|
|
{
|
|
$result = $this->conn->query(sprintf('DROP DATABASE `%s`', $name));
|
|
if (!$result) {
|
|
throw new Exception(sprintf('Database delete error: %s', $this->conn->error));
|
|
}
|
|
}
|
|
|
|
public function purgeDatabase(string $name): void
|
|
{
|
|
$this->deleteDatabase($name);
|
|
$this->createDatabase($name);
|
|
}
|
|
} |