Add user creation and deletion

This commit is contained in:
Tim
2024-09-23 23:32:33 +02:00
parent 4af4717785
commit 6aae797f16
4 changed files with 150 additions and 9 deletions

View File

@ -10,9 +10,7 @@ class BackupService
{
public function __construct(
private readonly DatabaseCredentials $credentials
)
{
}
) {}
public function backup(string $db, ?string $fileName = null): string
{

View File

@ -40,6 +40,20 @@ class DatabaseService
}
}
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);
}
public function listUsers(): array
{
$results = $this->conn->query('select * from mysql.user');
@ -56,17 +70,44 @@ class DatabaseService
return $users;
}
public function deleteDatabase(string $name): void
public function createUser(
string $name,
string $password,
?string $host = null,
): void
{
$result = $this->conn->query(sprintf('DROP DATABASE `%s`', $name));
$host ??= 'localhost';
$users = $this->listUsers();
foreach ($users as $user) {
if ($user['name'] === $name) {
throw new Exception(sprintf('User "%s" already exists', $name));
}
}
$result = $this->conn->query(sprintf("CREATE USER '%s'@'%s' IDENTIFIED BY '%s'", $name, $host, $password));
if (!$result) {
throw new Exception(sprintf('Database delete error: %s', $this->conn->error));
throw new Exception(sprintf('User create error: %s', $this->conn->error));
}
}
public function purgeDatabase(string $name): void
public function deleteUser(string $name, ?string $host = null): void
{
$this->deleteDatabase($name);
$this->createDatabase($name);
$host ??= 'localhost';
$users = $this->listUsers();
$found = false;
foreach ($users as $user) {
if ($user['name'] === $name) {
$found = true;
break;
}
}
if (!$found) {
throw new Exception(sprintf('User "%s" not found', $name));
}
$result = $this->conn->query(sprintf("DROP USER '%s'@'%s'", $name, $host));
if (!$result) {
throw new Exception(sprintf('User delete error: %s', $this->conn->error));
}
}
}