qodalis-cli-server-plugin-databases 1.0.0b30__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- qodalis_cli_databases/__init__.py +94 -0
- qodalis_cli_databases/builder.py +179 -0
- qodalis_cli_databases/commands.py +297 -0
- qodalis_cli_databases/connection.py +307 -0
- qodalis_cli_databases/controller.py +149 -0
- qodalis_cli_databases/dashboard/extension.css +1 -0
- qodalis_cli_databases/dashboard/extension.js +42 -0
- qodalis_cli_databases/dashboard_page.py +38 -0
- qodalis_cli_databases/databases.py +112 -0
- qodalis_cli_databases/dialects.py +228 -0
- qodalis_cli_databases/mcp_tools.py +174 -0
- qodalis_cli_databases/runner.py +514 -0
- qodalis_cli_databases/sources.py +127 -0
- qodalis_cli_databases/stats.py +449 -0
- qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/METADATA +28 -0
- qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/RECORD +18 -0
- qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/WHEEL +4 -0
- qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""Database stats: server, size, connections, load counters, cache hit ratio and the largest tables, per dialect.
|
|
2
|
+
|
|
3
|
+
Each metric group is read on its own: one that fails (a missing permission, e.g. SQL Server without
|
|
4
|
+
``VIEW SERVER STATE``) is left out and listed in ``unavailable``, so the rest still shows. Counters are
|
|
5
|
+
cumulative since the server started; the dashboard turns two samples into rates.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from datetime import date, datetime, timezone
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
from typing import Any, Awaitable, Callable
|
|
14
|
+
|
|
15
|
+
from .connection import CliSqlConnection, CliSqlSession
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
#: How many tables the stats list (the largest).
|
|
20
|
+
TOP_TABLES = 10
|
|
21
|
+
|
|
22
|
+
#: SQLite counts rows of at most this many tables (``count(*)`` reads the whole table).
|
|
23
|
+
SQLITE_COUNTED_TABLES = 20
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _num(value: Any) -> float | int | None:
|
|
27
|
+
if value is None or isinstance(value, bool):
|
|
28
|
+
return None
|
|
29
|
+
if isinstance(value, Decimal):
|
|
30
|
+
return int(value) if value == value.to_integral_value() else float(value)
|
|
31
|
+
if isinstance(value, (int, float)):
|
|
32
|
+
return value
|
|
33
|
+
try:
|
|
34
|
+
text = str(value).strip()
|
|
35
|
+
return int(text) if text.lstrip("-").isdigit() else float(text)
|
|
36
|
+
except (TypeError, ValueError):
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _iso(value: Any) -> str | None:
|
|
41
|
+
if isinstance(value, datetime):
|
|
42
|
+
if value.tzinfo is None:
|
|
43
|
+
value = value.replace(tzinfo=timezone.utc)
|
|
44
|
+
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
45
|
+
if isinstance(value, date):
|
|
46
|
+
return value.isoformat()
|
|
47
|
+
return str(value) if value is not None else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _now() -> datetime:
|
|
51
|
+
return datetime.now(timezone.utc)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _first(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
|
55
|
+
return rows[0] if rows else {}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _clean(values: dict[str, Any]) -> dict[str, Any]:
|
|
59
|
+
"""Without the keys whose value is unknown."""
|
|
60
|
+
return {k: v for k, v in values.items() if v is not None}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _top(tables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
64
|
+
"""The largest tables: by bytes when known, else by rows."""
|
|
65
|
+
key = "bytes" if any(t.get("bytes") is not None for t in tables) else "rows"
|
|
66
|
+
tables.sort(key=lambda t: t.get(key) or 0, reverse=True)
|
|
67
|
+
return [_clean(t) for t in tables[:TOP_TABLES]]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _uptime(started: Any) -> int | None:
|
|
71
|
+
if not isinstance(started, datetime):
|
|
72
|
+
return None
|
|
73
|
+
if started.tzinfo is None:
|
|
74
|
+
started = started.replace(tzinfo=timezone.utc)
|
|
75
|
+
return max(0, int((_now() - started).total_seconds()))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
Group = Callable[[CliSqlSession], Awaitable[Any]]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# ---------------------------------------------------------------- PostgreSQL
|
|
82
|
+
|
|
83
|
+
async def _pg_server(db: CliSqlSession) -> dict[str, Any]:
|
|
84
|
+
row = _first(await db.query("SELECT version() AS version, pg_postmaster_start_time() AS started"))
|
|
85
|
+
version = str(row.get("version") or "")
|
|
86
|
+
# "PostgreSQL 17.2 on x86_64-pc-linux-gnu, ..." -> "PostgreSQL 17.2"
|
|
87
|
+
short = " ".join(version.split(" ")[:2]) if version.startswith("PostgreSQL") else version
|
|
88
|
+
started = row.get("started")
|
|
89
|
+
return _clean({"version": short or None, "startedAt": _iso(started), "uptimeSeconds": _uptime(started)})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def _pg_size(db: CliSqlSession) -> dict[str, Any]:
|
|
93
|
+
row = _first(await db.query(
|
|
94
|
+
"SELECT pg_database_size(current_database()) AS bytes, "
|
|
95
|
+
"(SELECT COALESCE(SUM(pg_indexes_size(relid)), 0) FROM pg_stat_user_tables) AS index_bytes"
|
|
96
|
+
))
|
|
97
|
+
total, index = _num(row.get("bytes")), _num(row.get("index_bytes"))
|
|
98
|
+
return _clean({"bytes": total, "indexBytes": index, "dataBytes": total - index if total is not None and index is not None else None})
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
async def _pg_database_row(db: CliSqlSession) -> dict[str, Any]:
|
|
102
|
+
return _first(await db.query(
|
|
103
|
+
"SELECT numbackends, xact_commit, xact_rollback, blks_hit, blks_read, tup_returned, tup_fetched, "
|
|
104
|
+
"tup_inserted, tup_updated, tup_deleted FROM pg_stat_database WHERE datname = current_database()"
|
|
105
|
+
))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def _pg_connections(db: CliSqlSession) -> dict[str, Any]:
|
|
109
|
+
row = _first(await db.query(
|
|
110
|
+
"SELECT (SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database()) AS open, "
|
|
111
|
+
"(SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() AND state = 'active') AS active, "
|
|
112
|
+
"current_setting('max_connections') AS max"
|
|
113
|
+
))
|
|
114
|
+
return _clean({"active": _num(row.get("active")), "open": _num(row.get("open")), "max": _num(row.get("max"))})
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
async def _pg_counters(db: CliSqlSession) -> dict[str, Any]:
|
|
118
|
+
row = await _pg_database_row(db)
|
|
119
|
+
commits, rollbacks = _num(row.get("xact_commit")), _num(row.get("xact_rollback"))
|
|
120
|
+
read = [_num(row.get(k)) for k in ("tup_returned", "tup_fetched")]
|
|
121
|
+
written = [_num(row.get(k)) for k in ("tup_inserted", "tup_updated", "tup_deleted")]
|
|
122
|
+
return _clean({
|
|
123
|
+
"transactions": (commits or 0) + (rollbacks or 0) if commits is not None else None,
|
|
124
|
+
"commits": commits,
|
|
125
|
+
"rollbacks": rollbacks,
|
|
126
|
+
"rowsRead": sum(v or 0 for v in read) if any(v is not None for v in read) else None,
|
|
127
|
+
"rowsWritten": sum(v or 0 for v in written) if any(v is not None for v in written) else None,
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def _pg_cache(db: CliSqlSession) -> float | None:
|
|
132
|
+
row = await _pg_database_row(db)
|
|
133
|
+
hit, read = _num(row.get("blks_hit")) or 0, _num(row.get("blks_read")) or 0
|
|
134
|
+
return hit / (hit + read) if hit + read else None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
async def _pg_tables(db: CliSqlSession) -> list[dict[str, Any]]:
|
|
138
|
+
rows = await db.query(
|
|
139
|
+
"SELECT schemaname AS schema_name, relname AS table_name, n_live_tup AS row_count, "
|
|
140
|
+
"pg_total_relation_size(relid) AS bytes FROM pg_stat_user_tables "
|
|
141
|
+
f"ORDER BY pg_total_relation_size(relid) DESC LIMIT {TOP_TABLES}"
|
|
142
|
+
)
|
|
143
|
+
return _top([
|
|
144
|
+
{"schema": r.get("schema_name"), "name": r.get("table_name"), "rows": _num(r.get("row_count")), "bytes": _num(r.get("bytes"))}
|
|
145
|
+
for r in rows
|
|
146
|
+
])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ---------------------------------------------------------------- MySQL / MariaDB
|
|
150
|
+
|
|
151
|
+
_MYSQL_STATUS = (
|
|
152
|
+
"Uptime", "Threads_connected", "Threads_running", "Questions", "Com_commit", "Com_rollback", "Innodb_rows_read",
|
|
153
|
+
"Innodb_rows_inserted", "Innodb_rows_updated", "Innodb_rows_deleted", "Innodb_buffer_pool_read_requests",
|
|
154
|
+
"Innodb_buffer_pool_reads",
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
async def _mysql_status(db: CliSqlSession) -> dict[str, Any]:
|
|
159
|
+
names = ", ".join(f"'{n}'" for n in _MYSQL_STATUS)
|
|
160
|
+
rows = await db.query(f"SHOW GLOBAL STATUS WHERE Variable_name IN ({names})")
|
|
161
|
+
out: dict[str, Any] = {}
|
|
162
|
+
for r in rows:
|
|
163
|
+
values = list(r.values())
|
|
164
|
+
name = r.get("Variable_name", values[0] if values else None)
|
|
165
|
+
value = r.get("Value", values[1] if len(values) > 1 else None)
|
|
166
|
+
if name is not None:
|
|
167
|
+
out[str(name)] = _num(value)
|
|
168
|
+
return out
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
async def _mysql_server(db: CliSqlSession) -> dict[str, Any]:
|
|
172
|
+
version = _first(await db.query("SELECT VERSION() AS version")).get("version")
|
|
173
|
+
uptime = (await _mysql_status(db)).get("Uptime")
|
|
174
|
+
started = None
|
|
175
|
+
if uptime is not None:
|
|
176
|
+
started = datetime.fromtimestamp(_now().timestamp() - uptime, timezone.utc).replace(microsecond=0)
|
|
177
|
+
prefix = "MariaDB " if version and "mariadb" in str(version).lower() else "MySQL "
|
|
178
|
+
return _clean({
|
|
179
|
+
"version": f"{prefix}{str(version).split('-')[0]}" if version else None,
|
|
180
|
+
"startedAt": _iso(started),
|
|
181
|
+
"uptimeSeconds": int(uptime) if uptime is not None else None,
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
async def _mysql_fresh_table_stats(db: CliSqlSession) -> None:
|
|
186
|
+
"""information_schema.tables caches InnoDB sizes for a day (MySQL 8); read them fresh. MariaDB has no such
|
|
187
|
+
cache (nor the variable)."""
|
|
188
|
+
try:
|
|
189
|
+
await db.query("SET SESSION information_schema_stats_expiry = 0")
|
|
190
|
+
except Exception: # noqa: BLE001 - MariaDB, older MySQL
|
|
191
|
+
pass
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
async def _mysql_size(db: CliSqlSession) -> dict[str, Any]:
|
|
195
|
+
await _mysql_fresh_table_stats(db)
|
|
196
|
+
row = _first(await db.query(
|
|
197
|
+
"SELECT COALESCE(SUM(data_length), 0) AS data_bytes, COALESCE(SUM(index_length), 0) AS index_bytes "
|
|
198
|
+
"FROM information_schema.tables WHERE table_schema = DATABASE()"
|
|
199
|
+
))
|
|
200
|
+
data, index = _num(row.get("data_bytes")), _num(row.get("index_bytes"))
|
|
201
|
+
return _clean({"bytes": (data or 0) + (index or 0), "dataBytes": data, "indexBytes": index})
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
async def _mysql_connections(db: CliSqlSession) -> dict[str, Any]:
|
|
205
|
+
# This database's connections (all of them with the PROCESS privilege, else the user's own)
|
|
206
|
+
row = _first(await db.query(
|
|
207
|
+
"SELECT COUNT(*) AS open_count, COALESCE(SUM(command NOT IN ('Sleep', 'Daemon')), 0) AS active_count "
|
|
208
|
+
"FROM information_schema.processlist WHERE db = DATABASE()"
|
|
209
|
+
))
|
|
210
|
+
max_connections = _num(_first(await db.query("SELECT @@max_connections AS max")).get("max"))
|
|
211
|
+
return _clean({"active": _num(row.get("active_count")), "open": _num(row.get("open_count")), "max": max_connections})
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
async def _mysql_counters(db: CliSqlSession) -> dict[str, Any]:
|
|
215
|
+
s = await _mysql_status(db)
|
|
216
|
+
commits, rollbacks = s.get("Com_commit"), s.get("Com_rollback")
|
|
217
|
+
written = [s.get(k) for k in ("Innodb_rows_inserted", "Innodb_rows_updated", "Innodb_rows_deleted")]
|
|
218
|
+
return _clean({
|
|
219
|
+
"queries": s.get("Questions"),
|
|
220
|
+
"transactions": (commits or 0) + (rollbacks or 0) if commits is not None else None,
|
|
221
|
+
"commits": commits,
|
|
222
|
+
"rollbacks": rollbacks,
|
|
223
|
+
"rowsRead": s.get("Innodb_rows_read"),
|
|
224
|
+
"rowsWritten": sum(v or 0 for v in written) if any(v is not None for v in written) else None,
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
async def _mysql_cache(db: CliSqlSession) -> float | None:
|
|
229
|
+
s = await _mysql_status(db)
|
|
230
|
+
requests, reads = s.get("Innodb_buffer_pool_read_requests"), s.get("Innodb_buffer_pool_reads")
|
|
231
|
+
return max(0.0, 1 - (reads or 0) / requests) if requests else None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
async def _mysql_tables(db: CliSqlSession) -> list[dict[str, Any]]:
|
|
235
|
+
await _mysql_fresh_table_stats(db)
|
|
236
|
+
rows = await db.query(
|
|
237
|
+
"SELECT table_name AS table_name, table_rows AS row_count, data_length + index_length AS bytes "
|
|
238
|
+
"FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' "
|
|
239
|
+
f"ORDER BY data_length + index_length DESC LIMIT {TOP_TABLES}"
|
|
240
|
+
)
|
|
241
|
+
return _top([
|
|
242
|
+
{"name": r.get("table_name") or r.get("TABLE_NAME"), "rows": _num(r.get("row_count")), "bytes": _num(r.get("bytes"))}
|
|
243
|
+
for r in rows
|
|
244
|
+
])
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ---------------------------------------------------------------- SQL Server
|
|
248
|
+
|
|
249
|
+
async def _mssql_server(db: CliSqlSession) -> dict[str, Any]:
|
|
250
|
+
row = _first(await db.query(
|
|
251
|
+
"SELECT CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(128)) AS version, "
|
|
252
|
+
"CAST(SERVERPROPERTY('Edition') AS nvarchar(128)) AS edition"
|
|
253
|
+
))
|
|
254
|
+
out: dict[str, Any] = {}
|
|
255
|
+
if row.get("version"):
|
|
256
|
+
out["version"] = f"SQL Server {row['version']}" + (f" ({row['edition']})" if row.get("edition") else "")
|
|
257
|
+
# Needs VIEW SERVER STATE: without it the version alone is shown
|
|
258
|
+
try:
|
|
259
|
+
started = _first(await db.query("SELECT sqlserver_start_time AS started FROM sys.dm_os_sys_info")).get("started")
|
|
260
|
+
out.update(_clean({"startedAt": _iso(started), "uptimeSeconds": _uptime(started)}))
|
|
261
|
+
except Exception: # noqa: BLE001 - optional
|
|
262
|
+
pass
|
|
263
|
+
return out
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
async def _mssql_size(db: CliSqlSession) -> dict[str, Any]:
|
|
267
|
+
row = _first(await db.query(
|
|
268
|
+
"SELECT CAST(SUM(CASE WHEN type = 0 THEN CAST(size AS bigint) ELSE 0 END) * 8192 AS bigint) AS data_bytes, "
|
|
269
|
+
"CAST(SUM(CASE WHEN type = 1 THEN CAST(size AS bigint) ELSE 0 END) * 8192 AS bigint) AS log_bytes, "
|
|
270
|
+
"CAST(SUM(CAST(size AS bigint)) * 8192 AS bigint) AS total_bytes FROM sys.database_files"
|
|
271
|
+
))
|
|
272
|
+
out = _clean({"bytes": _num(row.get("total_bytes")), "dataBytes": _num(row.get("data_bytes")), "logBytes": _num(row.get("log_bytes"))})
|
|
273
|
+
try:
|
|
274
|
+
index = _first(await db.query(
|
|
275
|
+
"SELECT CAST(COALESCE(SUM(used_page_count), 0) * 8192 AS bigint) AS index_bytes "
|
|
276
|
+
"FROM sys.dm_db_partition_stats WHERE index_id > 1"
|
|
277
|
+
)).get("index_bytes")
|
|
278
|
+
if index is not None:
|
|
279
|
+
out["indexBytes"] = _num(index)
|
|
280
|
+
except Exception: # noqa: BLE001 - optional
|
|
281
|
+
pass
|
|
282
|
+
return out
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
async def _mssql_connections(db: CliSqlSession) -> dict[str, Any]:
|
|
286
|
+
row = _first(await db.query(
|
|
287
|
+
"SELECT (SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE database_id = DB_ID() AND is_user_process = 1) AS open_count, "
|
|
288
|
+
"(SELECT COUNT(*) FROM sys.dm_exec_requests WHERE database_id = DB_ID() AND session_id <> @@SPID) AS active_count, "
|
|
289
|
+
"@@MAX_CONNECTIONS AS max_count"
|
|
290
|
+
))
|
|
291
|
+
return _clean({"active": _num(row.get("active_count")), "open": _num(row.get("open_count")), "max": _num(row.get("max_count"))})
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
async def _mssql_counters(db: CliSqlSession) -> dict[str, Any]:
|
|
295
|
+
rows = await db.query(
|
|
296
|
+
"SELECT RTRIM(counter_name) AS counter_name, RTRIM(instance_name) AS instance_name, cntr_value AS value "
|
|
297
|
+
"FROM sys.dm_os_performance_counters WHERE (counter_name = 'Batch Requests/sec' AND object_name LIKE '%SQL Statistics%') "
|
|
298
|
+
"OR (counter_name = 'Transactions/sec' AND object_name LIKE '%:Databases%' AND instance_name = DB_NAME())"
|
|
299
|
+
)
|
|
300
|
+
if not rows:
|
|
301
|
+
# The view is empty without VIEW SERVER STATE
|
|
302
|
+
raise PermissionError("performance counters are not visible (VIEW SERVER STATE)")
|
|
303
|
+
out: dict[str, Any] = {}
|
|
304
|
+
for r in rows:
|
|
305
|
+
if r.get("counter_name") == "Batch Requests/sec":
|
|
306
|
+
out["queries"] = _num(r.get("value"))
|
|
307
|
+
elif r.get("counter_name") == "Transactions/sec":
|
|
308
|
+
out["transactions"] = _num(r.get("value"))
|
|
309
|
+
return out
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
async def _mssql_cache(db: CliSqlSession) -> float | None:
|
|
313
|
+
rows = await db.query(
|
|
314
|
+
"SELECT RTRIM(counter_name) AS counter_name, cntr_value AS value FROM sys.dm_os_performance_counters "
|
|
315
|
+
"WHERE object_name LIKE '%Buffer Manager%' AND counter_name IN ('Buffer cache hit ratio', 'Buffer cache hit ratio base')"
|
|
316
|
+
)
|
|
317
|
+
if not rows:
|
|
318
|
+
raise PermissionError("performance counters are not visible (VIEW SERVER STATE)")
|
|
319
|
+
values = {r.get("counter_name"): _num(r.get("value")) for r in rows}
|
|
320
|
+
ratio, base = values.get("Buffer cache hit ratio"), values.get("Buffer cache hit ratio base")
|
|
321
|
+
return min(1.0, ratio / base) if ratio is not None and base else None
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
async def _mssql_tables(db: CliSqlSession) -> list[dict[str, Any]]:
|
|
325
|
+
rows = await db.query(
|
|
326
|
+
f"SELECT TOP {TOP_TABLES} s.name AS schema_name, t.name AS table_name, "
|
|
327
|
+
"SUM(CASE WHEN p.index_id IN (0, 1) THEN p.row_count ELSE 0 END) AS row_count, "
|
|
328
|
+
"CAST(SUM(p.reserved_page_count) * 8192 AS bigint) AS bytes "
|
|
329
|
+
"FROM sys.tables t JOIN sys.schemas s ON s.schema_id = t.schema_id "
|
|
330
|
+
"JOIN sys.dm_db_partition_stats p ON p.object_id = t.object_id "
|
|
331
|
+
"GROUP BY s.name, t.name ORDER BY SUM(p.reserved_page_count) DESC"
|
|
332
|
+
)
|
|
333
|
+
return _top([
|
|
334
|
+
{"schema": r.get("schema_name"), "name": r.get("table_name"), "rows": _num(r.get("row_count")), "bytes": _num(r.get("bytes"))}
|
|
335
|
+
for r in rows
|
|
336
|
+
])
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
# ---------------------------------------------------------------- SQLite
|
|
340
|
+
|
|
341
|
+
async def _sqlite_server(db: CliSqlSession) -> dict[str, Any]:
|
|
342
|
+
version = _first(await db.query("SELECT sqlite_version() AS version")).get("version")
|
|
343
|
+
return {"version": f"SQLite {version}"} if version else {}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
async def _sqlite_size(db: CliSqlSession) -> dict[str, Any]:
|
|
347
|
+
pages = _num(_first(await db.query("PRAGMA page_count")).get("page_count"))
|
|
348
|
+
page_size = _num(_first(await db.query("PRAGMA page_size")).get("page_size"))
|
|
349
|
+
return {"bytes": pages * page_size} if pages is not None and page_size is not None else {}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
async def _sqlite_tables(db: CliSqlSession) -> list[dict[str, Any]]:
|
|
353
|
+
names = [
|
|
354
|
+
r["name"] for r in await db.query(
|
|
355
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
356
|
+
)
|
|
357
|
+
]
|
|
358
|
+
sizes: dict[str, int] = {}
|
|
359
|
+
try:
|
|
360
|
+
# dbstat is compiled in most builds; indexes count to their table
|
|
361
|
+
for r in await db.query(
|
|
362
|
+
"SELECT COALESCE(m.tbl_name, s.name) AS table_name, SUM(s.pgsize) AS bytes FROM dbstat s "
|
|
363
|
+
"LEFT JOIN sqlite_master m ON m.name = s.name GROUP BY COALESCE(m.tbl_name, s.name)"
|
|
364
|
+
):
|
|
365
|
+
sizes[str(r["table_name"])] = int(r["bytes"] or 0)
|
|
366
|
+
except Exception: # noqa: BLE001 - no dbstat: rows only
|
|
367
|
+
pass
|
|
368
|
+
def quote(name: str) -> str:
|
|
369
|
+
return '"' + name.replace('"', '""') + '"' # any table name, not only identifiers
|
|
370
|
+
|
|
371
|
+
if sizes:
|
|
372
|
+
ordered = sorted(names, key=lambda n: sizes.get(n, 0), reverse=True)
|
|
373
|
+
else:
|
|
374
|
+
# Without sizes, every table is ranked by its highest rowid (an index lookup, not a scan) before the counts
|
|
375
|
+
estimate: dict[str, int] = {}
|
|
376
|
+
for name in names:
|
|
377
|
+
try:
|
|
378
|
+
estimate[name] = _num(_first(await db.query(f"SELECT MAX(rowid) AS n FROM {quote(name)}")).get("n")) or 0
|
|
379
|
+
except Exception: # noqa: BLE001 - a WITHOUT ROWID table
|
|
380
|
+
estimate[name] = 0
|
|
381
|
+
ordered = sorted(names, key=lambda n: estimate[n], reverse=True)
|
|
382
|
+
tables: list[dict[str, Any]] = []
|
|
383
|
+
for i, name in enumerate(ordered):
|
|
384
|
+
rows = None
|
|
385
|
+
if i < SQLITE_COUNTED_TABLES:
|
|
386
|
+
rows = _num(_first(await db.query(f"SELECT COUNT(*) AS n FROM {quote(name)}")).get("n"))
|
|
387
|
+
tables.append({"name": name, "rows": rows, "bytes": sizes.get(name) if sizes else None})
|
|
388
|
+
return _top(tables)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
# ---------------------------------------------------------------- collection
|
|
392
|
+
|
|
393
|
+
_GROUPS: dict[str, dict[str, Group]] = {
|
|
394
|
+
"postgres": {
|
|
395
|
+
"server": _pg_server, "size": _pg_size, "connections": _pg_connections, "counters": _pg_counters,
|
|
396
|
+
"cacheHitRatio": _pg_cache, "tables": _pg_tables,
|
|
397
|
+
},
|
|
398
|
+
"mysql": {
|
|
399
|
+
"server": _mysql_server, "size": _mysql_size, "connections": _mysql_connections, "counters": _mysql_counters,
|
|
400
|
+
"cacheHitRatio": _mysql_cache, "tables": _mysql_tables,
|
|
401
|
+
},
|
|
402
|
+
"mssql": {
|
|
403
|
+
"server": _mssql_server, "size": _mssql_size, "connections": _mssql_connections, "counters": _mssql_counters,
|
|
404
|
+
"cacheHitRatio": _mssql_cache, "tables": _mssql_tables,
|
|
405
|
+
},
|
|
406
|
+
"sqlite": {"server": _sqlite_server, "size": _sqlite_size, "tables": _sqlite_tables},
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
_COUNTERS_SCOPE = {"postgres": "database", "mysql": "server", "mssql": "server"}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
async def collect_stats(name: str, connection: CliSqlConnection) -> dict[str, Any]:
|
|
413
|
+
"""The stats of a database (``GET /api/v1/qcli/databases/{db}/stats``); never raises for a metric."""
|
|
414
|
+
dialect = connection.dialect
|
|
415
|
+
stats: dict[str, Any] = {"name": name, "dialect": dialect, "collectedAt": _iso(_now())}
|
|
416
|
+
unavailable: list[dict[str, str]] = []
|
|
417
|
+
groups = _GROUPS.get(dialect, {})
|
|
418
|
+
try:
|
|
419
|
+
async with connection.session() as db:
|
|
420
|
+
for metric, read in groups.items():
|
|
421
|
+
try:
|
|
422
|
+
value = await read(db)
|
|
423
|
+
except Exception as exc: # noqa: BLE001 - listed as unavailable
|
|
424
|
+
unavailable.append({"metric": metric, "error": str(exc) or type(exc).__name__})
|
|
425
|
+
continue
|
|
426
|
+
if value is None or value == {}:
|
|
427
|
+
continue
|
|
428
|
+
stats[metric] = value
|
|
429
|
+
except Exception as exc: # noqa: BLE001 - the database is down
|
|
430
|
+
unavailable.append({"metric": "connection", "error": str(exc) or type(exc).__name__})
|
|
431
|
+
if "counters" in stats and dialect in _COUNTERS_SCOPE:
|
|
432
|
+
stats["countersScope"] = _COUNTERS_SCOPE[dialect]
|
|
433
|
+
stats["unavailable"] = unavailable
|
|
434
|
+
return stats
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
async def collect_size(connection: CliSqlConnection) -> int | None:
|
|
438
|
+
"""The database's size in bytes, best effort (the summary's ``sizeBytes``)."""
|
|
439
|
+
read = _GROUPS.get(connection.dialect, {}).get("size")
|
|
440
|
+
if read is None:
|
|
441
|
+
return None
|
|
442
|
+
try:
|
|
443
|
+
async with connection.session() as db:
|
|
444
|
+
size = await read(db)
|
|
445
|
+
except Exception as exc: # noqa: BLE001 - omitted from the summary
|
|
446
|
+
logger.debug("could not read the size of a %s database: %s", connection.dialect, exc)
|
|
447
|
+
return None
|
|
448
|
+
value = size.get("bytes") if isinstance(size, dict) else None
|
|
449
|
+
return int(value) if value is not None else None
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: qodalis-cli-server-plugin-databases
|
|
3
|
+
Version: 1.0.0b30
|
|
4
|
+
Summary: Databases for Qodalis CLI servers — stats (size, connections, load, largest tables) and versioned schema migrations of PostgreSQL, MySQL, SQL Server and SQLite, with history, API, terminal and MCP
|
|
5
|
+
Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
|
|
6
|
+
Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
|
|
7
|
+
Project-URL: Issues, https://github.com/qodalis-solutions/cli-server-python/issues
|
|
8
|
+
Author-email: Nicolae Lupei <nicolae.lupei@qodalis.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: cli,database,databases,migrations,plugin,qodalis,schema,stats
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: fastapi>=0.100.0
|
|
22
|
+
Requires-Dist: qodalis-cli-server-abstractions>=1.0.0b17
|
|
23
|
+
Provides-Extra: mssql
|
|
24
|
+
Requires-Dist: pymssql>=2.3.0; extra == 'mssql'
|
|
25
|
+
Provides-Extra: mysql
|
|
26
|
+
Requires-Dist: aiomysql>=0.2.0; extra == 'mysql'
|
|
27
|
+
Provides-Extra: postgres
|
|
28
|
+
Requires-Dist: asyncpg>=0.29.0; extra == 'postgres'
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
qodalis_cli_databases/__init__.py,sha256=QcwB6gsHaXhiAzEH_746gQeqPs8FgWwWsmJtLuCnGxo,2598
|
|
2
|
+
qodalis_cli_databases/builder.py,sha256=aqdUJRPqpjwxEbeNPVTg0IIQI8xrXzK1lTJEKFLLPUc,8114
|
|
3
|
+
qodalis_cli_databases/commands.py,sha256=SnEj4LbnU6EADH7XK-dJYOpqciBgQqmlKai2pd4fopM,11646
|
|
4
|
+
qodalis_cli_databases/connection.py,sha256=gZsIjg9B0siMsXHk9tZGA-dIqqpDnN2Z9wLZCpnp5S0,10787
|
|
5
|
+
qodalis_cli_databases/controller.py,sha256=7EWb7Oo4pwfsc_FRxc_sTDzBvpf91MZ1mgLMuvZv_JU,5411
|
|
6
|
+
qodalis_cli_databases/dashboard_page.py,sha256=bkM_0NWIVQWbgs0YM4_GifFz09Q1EkE5G0CNimTEQhU,1468
|
|
7
|
+
qodalis_cli_databases/databases.py,sha256=lqSqztkjETjzyU-H_nEXf9-_zvm2tbtBi3kdy-me5Ck,5180
|
|
8
|
+
qodalis_cli_databases/dialects.py,sha256=9SL-b7O_1DThS-2LAwBPWlgU-MRurXSjmyJbvWyV3go,9468
|
|
9
|
+
qodalis_cli_databases/mcp_tools.py,sha256=SEQgxux2IiDVAN1mk7SUR70DbO7uo0QxkPoCRVIGvnM,8944
|
|
10
|
+
qodalis_cli_databases/runner.py,sha256=OKD13RukwtKRJ6w2YVoJr87bTwsDOS29SiNi0KNGxcQ,21862
|
|
11
|
+
qodalis_cli_databases/sources.py,sha256=Agv9TZOs9lKc4vYCw-ogXtRRkfLhoDK0wDt6dwvtdXM,4951
|
|
12
|
+
qodalis_cli_databases/stats.py,sha256=YRaRv3blmvE4V-i-bVPiH-ps_VvvXAVzPq6GP1cUCDg,20395
|
|
13
|
+
qodalis_cli_databases/dashboard/extension.css,sha256=0IzPA7i9o_ARv_y1Xkhz0USuBs5lxpjNMhvNJvZhosw,19472
|
|
14
|
+
qodalis_cli_databases/dashboard/extension.js,sha256=TEEmC1f1H-Tvp8QkSWTg8X8q8CBBGPHrpaLi2mjG-QU,242806
|
|
15
|
+
qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/METADATA,sha256=W-xU4AD777NViTh_9StS6-xiFI4UccR_LgCoUVxF0t0,1426
|
|
16
|
+
qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
17
|
+
qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/licenses/LICENSE,sha256=uagko_O2JboeVOW3cldvxKW4QIDjTHCCk5T32qqg_As,1079
|
|
18
|
+
qodalis_cli_server_plugin_databases-1.0.0b30.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-2026 Qodalis Solutions
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|