-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathDbHealth.php
More file actions
99 lines (89 loc) · 2.5 KB
/
DbHealth.php
File metadata and controls
99 lines (89 loc) · 2.5 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\ServerInfo;
use OCP\IConfig;
use OCP\IDBConnection;
class DbHealth {
public function __construct(
private IDBConnection $db,
private IConfig $config,
) {
}
/**
* @return array{
* driver: string,
* largestTables: list<array{name: string, rows: int, sizeBytes: int}>,
* available: bool
* }
*/
public function getDbHealth(): array {
$driver = (string)$this->config->getSystemValue('dbtype', 'sqlite');
try {
$tables = match ($driver) {
'mysql', 'mariadb' => $this->mysqlTables(),
'pgsql' => $this->pgTables(),
default => [],
};
} catch (\Throwable) {
$tables = [];
}
return [
'driver' => $driver,
'largestTables' => $tables,
'available' => $tables !== [] || $driver === 'sqlite',
];
}
/**
* @return list<array{name: string, rows: int, sizeBytes: int}>
*/
private function mysqlTables(int $limit = 8): array {
$dbName = (string)$this->config->getSystemValue('dbname', '');
if ($dbName === '') {
return [];
}
$sql = 'SELECT table_name AS name, table_rows AS rows, '
. '(data_length + index_length) AS size_bytes '
. 'FROM information_schema.TABLES WHERE table_schema = ? '
. 'ORDER BY size_bytes DESC LIMIT ' . (int)$limit;
$conn = $this->db;
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $dbName);
$result = $stmt->executeQuery();
$out = [];
while (($row = $result->fetch()) !== false) {
$out[] = [
'name' => (string)($row['name'] ?? ''),
'rows' => (int)($row['rows'] ?? 0),
'sizeBytes' => (int)($row['size_bytes'] ?? 0),
];
}
$result->closeCursor();
return $out;
}
/**
* @return list<array{name: string, rows: int, sizeBytes: int}>
*/
private function pgTables(int $limit = 8): array {
$sql = 'SELECT relname AS name, n_live_tup AS rows, '
. 'pg_total_relation_size(C.oid) AS size_bytes '
. 'FROM pg_class C '
. 'LEFT JOIN pg_namespace N ON N.oid = C.relnamespace '
. "WHERE relkind = 'r' AND nspname NOT IN ('pg_catalog', 'information_schema') "
. 'ORDER BY size_bytes DESC LIMIT ' . (int)$limit;
$result = $this->db->prepare($sql)->executeQuery();
$out = [];
while (($row = $result->fetch()) !== false) {
$out[] = [
'name' => (string)($row['name'] ?? ''),
'rows' => (int)($row['rows'] ?? 0),
'sizeBytes' => (int)($row['size_bytes'] ?? 0),
];
}
$result->closeCursor();
return $out;
}
}