. */ namespace App\Services\Misc; use Doctrine\DBAL\Exception; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Platforms\AbstractMySQLPlatform; use Doctrine\DBAL\Platforms\SqlitePlatform; use Doctrine\ORM\EntityManagerInterface; /** * This service provides db independent information about the database. */ class DBInfoHelper { protected Connection $connection; public function __construct(protected EntityManagerInterface $entityManager) { $this->connection = $entityManager->getConnection(); } /** * Returns the database type of the used database. * @return string|null Returns 'mysql' for MySQL/MariaDB and 'sqlite' for SQLite. Returns null if unknown type */ public function getDatabaseType(): ?string { if ($this->connection->getDatabasePlatform() instanceof AbstractMySQLPlatform) { return 'mysql'; } if ($this->connection->getDatabasePlatform() instanceof SqlitePlatform) { return 'sqlite'; } return null; } /** * Returns the database version of the used database. * @throws Exception */ public function getDatabaseVersion(): ?string { if ($this->connection->getDatabasePlatform() instanceof AbstractMySQLPlatform) { return $this->connection->fetchOne('SELECT VERSION()'); } if ($this->connection->getDatabasePlatform() instanceof SqlitePlatform) { return $this->connection->fetchOne('SELECT sqlite_version()'); } return null; } /** * Returns the database size in bytes. * @return int|null The database size in bytes or null if unknown * @throws Exception */ public function getDatabaseSize(): ?int { if ($this->connection->getDatabasePlatform() instanceof AbstractMySQLPlatform) { try { return (int) $this->connection->fetchOne('SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema = DATABASE()'); } catch (Exception) { return null; } } if ($this->connection->getDatabasePlatform() instanceof SqlitePlatform) { try { return (int) $this->connection->fetchOne('SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size();'); } catch (Exception) { return null; } } return null; } /** * Returns the name of the database. */ public function getDatabaseName(): ?string { return $this->connection->getDatabase(); } /** * Returns the name of the database user. */ public function getDatabaseUsername(): ?string { if ($this->connection->getDatabasePlatform() instanceof AbstractMySQLPlatform) { try { return $this->connection->fetchOne('SELECT USER()'); } catch (Exception) { return null; } } if ($this->connection->getDatabasePlatform() instanceof SqlitePlatform) { return 'sqlite'; } return null; } }