generated from spatie/package-skeleton-laravel
-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
DbConnectionInfo.php
69 lines (59 loc) · 2.78 KB
/
DbConnectionInfo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
namespace Spatie\Health\Support;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\MySqlConnection;
use Illuminate\Database\PostgresConnection;
use Spatie\Health\Exceptions\DatabaseNotSupported;
class DbConnectionInfo
{
public function connectionCount(ConnectionInterface $connection): int
{
return match (true) {
$connection instanceof MySqlConnection => (int) $connection->selectOne('show status where variable_name = "threads_connected"')->Value,
$connection instanceof PostgresConnection => (int) $connection->selectOne('select count(*) as connections from pg_stat_activity')->connections,
default => throw DatabaseNotSupported::make($connection),
};
}
public function tableSizeInMb(ConnectionInterface $connection, string $table): float
{
$sizeInBytes = match (true) {
$connection instanceof MySqlConnection => $this->getMySQLTableSize($connection, $table),
$connection instanceof PostgresConnection => $this->getPostgresTableSize($connection, $table),
default => throw DatabaseNotSupported::make($connection),
};
return $sizeInBytes / 1024 / 1024;
}
public function databaseSizeInMb(ConnectionInterface $connection): float
{
return match (true) {
$connection instanceof MySqlConnection => $this->getMySQlDatabaseSize($connection),
$connection instanceof PostgresConnection => $this->getPostgresDatabaseSize($connection),
default => throw DatabaseNotSupported::make($connection),
};
}
protected function getMySQLTableSize(ConnectionInterface $connection, string $table): int
{
return $connection->selectOne('SELECT (data_length + index_length) AS size FROM information_schema.TABLES WHERE table_schema = ? AND table_name = ?', [
$connection->getDatabaseName(),
$table,
])->size;
}
protected function getPostgresTableSize(ConnectionInterface $connection, string $table): int
{
return $connection->selectOne('SELECT pg_total_relation_size(?) AS size;', [
$table,
])->size;
}
protected function getMySQLDatabaseSize(ConnectionInterface $connection): int
{
return $connection->selectOne('SELECT size from (SELECT table_schema "name", ROUND(SUM(data_length + index_length) / 1024 / 1024) as size FROM information_schema.tables GROUP BY table_schema) alias_one where name = ?', [
$connection->getDatabaseName(),
])->size;
}
protected function getPostgresDatabaseSize(ConnectionInterface $connection): int
{
return $connection->selectOne('SELECT pg_database_size(?) / 1024 / 1024 AS size;', [
$connection->getDatabaseName(),
])->size;
}
}