qodalis-cli-server-plugin-databases 1.0.0b30__tar.gz
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_server_plugin_databases-1.0.0b30/.gitignore +2 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/LICENSE +21 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/PKG-INFO +28 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/pyproject.toml +48 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/__init__.py +94 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/builder.py +179 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/commands.py +297 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/connection.py +307 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/controller.py +149 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/dashboard/extension.css +1 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/dashboard/extension.js +42 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/dashboard_page.py +38 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/databases.py +112 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/dialects.py +228 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/mcp_tools.py +174 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/runner.py +514 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/sources.py +127 -0
- qodalis_cli_server_plugin_databases-1.0.0b30/qodalis_cli_databases/stats.py +449 -0
|
@@ -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.
|
|
@@ -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,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "qodalis-cli-server-plugin-databases"
|
|
7
|
+
version = "1.0.0b30"
|
|
8
|
+
description = "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"
|
|
9
|
+
readme = { text = "", content-type = "text/plain" }
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Nicolae Lupei", email = "nicolae.lupei@qodalis.com" },
|
|
14
|
+
]
|
|
15
|
+
keywords = ["cli", "qodalis", "databases", "migrations", "database", "schema", "stats", "plugin"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"qodalis-cli-server-abstractions>=1.0.0b17",
|
|
28
|
+
"fastapi>=0.100.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
postgres = ["asyncpg>=0.29.0"]
|
|
33
|
+
mysql = ["aiomysql>=0.2.0"]
|
|
34
|
+
mssql = ["pymssql>=2.3.0"]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://github.com/qodalis-solutions/cli-server-python"
|
|
38
|
+
Repository = "https://github.com/qodalis-solutions/cli-server-python"
|
|
39
|
+
Issues = "https://github.com/qodalis-solutions/cli-server-python/issues"
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.wheel]
|
|
42
|
+
packages = ["qodalis_cli_databases"]
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.sdist]
|
|
45
|
+
include = ["qodalis_cli_databases/**"]
|
|
46
|
+
|
|
47
|
+
[tool.hatch.build]
|
|
48
|
+
artifacts = ["qodalis_cli_databases/dashboard/**"]
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Qodalis CLI databases plugin: the server's PostgreSQL, MySQL/MariaDB, SQL Server and SQLite databases, their
|
|
2
|
+
stats (size, connections, load, largest tables) and their migrations (versioned schema changes applied under a
|
|
3
|
+
lock, recorded, and shown, run and rolled back from the dashboard, the terminal, MCP and the API)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
#: The package's icon on the admin dashboard's plugins page (``CliInstalledPlugin.icon``).
|
|
8
|
+
__plugin_icon__ = "🗄️"
|
|
9
|
+
|
|
10
|
+
from .builder import (
|
|
11
|
+
DATABASES_PERMISSION_ENTRIES,
|
|
12
|
+
DATABASES_PREFIX,
|
|
13
|
+
CliDatabasesBuilder,
|
|
14
|
+
CliDatabasesPlugin,
|
|
15
|
+
)
|
|
16
|
+
from .connection import (
|
|
17
|
+
SQL_DIALECTS,
|
|
18
|
+
CliSqlConnection,
|
|
19
|
+
CliSqlDialect,
|
|
20
|
+
CliSqlSession,
|
|
21
|
+
mssql_connection,
|
|
22
|
+
mysql_connection,
|
|
23
|
+
postgres_connection,
|
|
24
|
+
sqlite_connection,
|
|
25
|
+
)
|
|
26
|
+
from .controller import create_databases_router
|
|
27
|
+
from .commands import CliDatabasesCommandProcessor
|
|
28
|
+
from .dialects import (
|
|
29
|
+
adopt_legacy_table,
|
|
30
|
+
column_exists,
|
|
31
|
+
quote_ident,
|
|
32
|
+
quote_table,
|
|
33
|
+
rename_column,
|
|
34
|
+
rename_table,
|
|
35
|
+
table_exists,
|
|
36
|
+
)
|
|
37
|
+
from .databases import MIGRATION_RUN_EVENT, DATABASES_READ, DATABASES_MIGRATE, CliDatabases
|
|
38
|
+
from .stats import collect_size, collect_stats
|
|
39
|
+
from .runner import (
|
|
40
|
+
CliMigrationDatabaseOptions,
|
|
41
|
+
CliMigrationError,
|
|
42
|
+
CliMigrationRun,
|
|
43
|
+
CliMigrationRunner,
|
|
44
|
+
CliMigrationRunOptions,
|
|
45
|
+
CliMigrationState,
|
|
46
|
+
CliMigrationStatus,
|
|
47
|
+
CliMigrationTrigger,
|
|
48
|
+
)
|
|
49
|
+
from .sources import CliMigration, CliMigrationSource, CliMigrationStep, CodeSource, SqlFolderSource, code_source, sql_folder_source
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"DATABASES_PERMISSION_ENTRIES",
|
|
53
|
+
"DATABASES_PREFIX",
|
|
54
|
+
"CliDatabasesBuilder",
|
|
55
|
+
"CliDatabasesPlugin",
|
|
56
|
+
"SQL_DIALECTS",
|
|
57
|
+
"CliSqlConnection",
|
|
58
|
+
"CliSqlDialect",
|
|
59
|
+
"CliSqlSession",
|
|
60
|
+
"mssql_connection",
|
|
61
|
+
"mysql_connection",
|
|
62
|
+
"postgres_connection",
|
|
63
|
+
"sqlite_connection",
|
|
64
|
+
"create_databases_router",
|
|
65
|
+
"CliDatabasesCommandProcessor",
|
|
66
|
+
"adopt_legacy_table",
|
|
67
|
+
"column_exists",
|
|
68
|
+
"quote_ident",
|
|
69
|
+
"quote_table",
|
|
70
|
+
"rename_column",
|
|
71
|
+
"rename_table",
|
|
72
|
+
"table_exists",
|
|
73
|
+
"MIGRATION_RUN_EVENT",
|
|
74
|
+
"DATABASES_READ",
|
|
75
|
+
"DATABASES_MIGRATE",
|
|
76
|
+
"CliDatabases",
|
|
77
|
+
"collect_size",
|
|
78
|
+
"collect_stats",
|
|
79
|
+
"CliMigrationDatabaseOptions",
|
|
80
|
+
"CliMigrationError",
|
|
81
|
+
"CliMigrationRun",
|
|
82
|
+
"CliMigrationRunner",
|
|
83
|
+
"CliMigrationRunOptions",
|
|
84
|
+
"CliMigrationState",
|
|
85
|
+
"CliMigrationStatus",
|
|
86
|
+
"CliMigrationTrigger",
|
|
87
|
+
"CliMigration",
|
|
88
|
+
"CliMigrationSource",
|
|
89
|
+
"CliMigrationStep",
|
|
90
|
+
"CodeSource",
|
|
91
|
+
"SqlFolderSource",
|
|
92
|
+
"code_source",
|
|
93
|
+
"sql_folder_source",
|
|
94
|
+
]
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Fluent builder of the databases plugin."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, Sequence
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter
|
|
10
|
+
|
|
11
|
+
from qodalis_cli_server_abstractions import CliModule, CliRoutePermission, IAuditStore, ICliCommandProcessor
|
|
12
|
+
|
|
13
|
+
from .commands import CliDatabasesCommandProcessor
|
|
14
|
+
from .dashboard_page import databases_page
|
|
15
|
+
from .controller import create_databases_router
|
|
16
|
+
from .databases import DATABASES_READ, DATABASES_MIGRATE, CliDatabases
|
|
17
|
+
from .runner import CliMigrationDatabaseOptions, CliMigrationRun, CliMigrationRunner, CliMigrationRunOptions
|
|
18
|
+
from .sources import CliMigration, CliMigrationSource, code_source, sql_folder_source
|
|
19
|
+
|
|
20
|
+
DATABASES_PREFIX = "/api/v1/qcli/databases"
|
|
21
|
+
|
|
22
|
+
#: The permissions the plugin adds to the server's catalog.
|
|
23
|
+
DATABASES_PERMISSION_ENTRIES: list[dict[str, str]] = [
|
|
24
|
+
{"name": DATABASES_READ, "description": "See databases, their stats and migrations", "group": "Databases"},
|
|
25
|
+
{"name": DATABASES_MIGRATE, "description": "Apply and roll back database migrations", "group": "Databases"},
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
_DATABASE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _DatabasesModule(CliModule):
|
|
32
|
+
def __init__(self, processor: ICliCommandProcessor) -> None:
|
|
33
|
+
self._processors = [processor]
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def name(self) -> str:
|
|
37
|
+
return "databases"
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def version(self) -> str:
|
|
41
|
+
return "1.0.0"
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def description(self) -> str:
|
|
45
|
+
return "Databases: stats, migrations (status, apply, roll back)"
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def icon(self) -> str:
|
|
49
|
+
return "🗄️"
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def processors(self) -> Sequence[ICliCommandProcessor]:
|
|
53
|
+
return self._processors
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class CliDatabasesPlugin:
|
|
58
|
+
"""The built plugin: mount it with ``result.mount_plugin(plugin)``."""
|
|
59
|
+
|
|
60
|
+
prefix: str
|
|
61
|
+
router: APIRouter
|
|
62
|
+
databases: CliDatabases
|
|
63
|
+
#: The ``databases`` terminal commands, registered when mounted.
|
|
64
|
+
module: CliModule
|
|
65
|
+
#: ``databases:read`` for GET, ``databases:migrate`` for migration runs (enforced on a protected server).
|
|
66
|
+
route_permissions: list[CliRoutePermission] = field(default_factory=list)
|
|
67
|
+
#: ``databases:read`` and ``databases:migrate``, added to the server's permission catalog when mounted.
|
|
68
|
+
permissions: list[dict[str, str]] = field(default_factory=list)
|
|
69
|
+
#: The dashboard's Databases page (``/qcli/databases``), when its build is there.
|
|
70
|
+
dashboard_pages: list[Any] = field(default_factory=list)
|
|
71
|
+
_startup: list[str] = field(default_factory=list, repr=False)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def mcp_providers(self) -> list[Any]:
|
|
75
|
+
"""The ``databases_*`` and ``migrations_*`` MCP tools, served when the server's MCP endpoint is on."""
|
|
76
|
+
try:
|
|
77
|
+
from .mcp_tools import DatabasesMcpToolProvider
|
|
78
|
+
except ImportError: # without the server package
|
|
79
|
+
return []
|
|
80
|
+
return [DatabasesMcpToolProvider(self.databases)]
|
|
81
|
+
|
|
82
|
+
def on_mount(self, server: Any) -> None:
|
|
83
|
+
"""Hook called by ``CliServerResult.mount_plugin``: migration runs publish ``databases:migration-run`` on the server's
|
|
84
|
+
event bus."""
|
|
85
|
+
bus = getattr(server, "event_bus", None)
|
|
86
|
+
if self.databases.event_bus is None and bus is not None:
|
|
87
|
+
self.databases.event_bus = bus
|
|
88
|
+
|
|
89
|
+
async def apply_on_startup(self) -> list[CliMigrationRun]:
|
|
90
|
+
"""Applies the pending migrations of the databases marked ``apply_on_startup``, one after another,
|
|
91
|
+
waiting for another process's run; raises ``RuntimeError`` with the first failure. Await it before
|
|
92
|
+
the server serves requests (e.g. in the app's lifespan)."""
|
|
93
|
+
runs: list[CliMigrationRun] = []
|
|
94
|
+
for name in self._startup:
|
|
95
|
+
run = await self.databases.run(name, "up", CliMigrationRunOptions(trigger="startup", wait=True))
|
|
96
|
+
runs.append(run)
|
|
97
|
+
if run.status == "failed":
|
|
98
|
+
raise RuntimeError(f"migrations of {name} failed: {run.error}")
|
|
99
|
+
return runs
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class CliDatabasesBuilder:
|
|
103
|
+
"""The databases plugin: the server's relational databases (PostgreSQL, MySQL, SQL Server, SQLite), their
|
|
104
|
+
stats (size, connections, load, largest tables) and their migrations: versioned schema changes applied under
|
|
105
|
+
a lock, recorded in ``QcliMigrations`` / ``QcliMigrationRuns``, and shown, run and rolled back from the
|
|
106
|
+
dashboard, the terminal (``databases``), MCP and the API at ``/api/v1/qcli/databases``.
|
|
107
|
+
|
|
108
|
+
Example::
|
|
109
|
+
|
|
110
|
+
databases = (
|
|
111
|
+
CliDatabasesBuilder()
|
|
112
|
+
.add_database("main", CliMigrationDatabaseOptions(postgres_connection(pool), apply_on_startup=True))
|
|
113
|
+
.add_sql_folder("main", "./migrations")
|
|
114
|
+
.build()
|
|
115
|
+
)
|
|
116
|
+
await databases.apply_on_startup()
|
|
117
|
+
result.mount_plugin(databases)
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
def __init__(self) -> None:
|
|
121
|
+
self._databases: list[tuple[str, CliMigrationDatabaseOptions, list[CliMigrationSource]]] = []
|
|
122
|
+
self._audit_store: IAuditStore | None = None
|
|
123
|
+
self._dashboard_dir: str | bool | None = None
|
|
124
|
+
|
|
125
|
+
def add_database(self, name: str, options: CliMigrationDatabaseOptions) -> "CliDatabasesBuilder":
|
|
126
|
+
"""Registers a database (its name is used in the API, the terminal and the dashboard)."""
|
|
127
|
+
if not _DATABASE_NAME.match(name or ""):
|
|
128
|
+
raise ValueError(f"invalid database name: {name}")
|
|
129
|
+
if any(n == name for n, _, _ in self._databases):
|
|
130
|
+
raise ValueError(f"migration database already added: {name}")
|
|
131
|
+
self._databases.append((name, options, []))
|
|
132
|
+
return self
|
|
133
|
+
|
|
134
|
+
def add_source(self, database: str, source: CliMigrationSource) -> "CliDatabasesBuilder":
|
|
135
|
+
"""Adds a source of migrations to a database; sources apply in the order they were added."""
|
|
136
|
+
for name, _, sources in self._databases:
|
|
137
|
+
if name == database:
|
|
138
|
+
sources.append(source)
|
|
139
|
+
return self
|
|
140
|
+
raise ValueError(f"unknown migration database: {database}")
|
|
141
|
+
|
|
142
|
+
def add_sql_folder(self, database: str, directory: str, source_name: str = "app") -> "CliDatabasesBuilder":
|
|
143
|
+
"""Migrations from ``NNNN_name.up.sql`` / ``.down.sql`` files in ``directory``."""
|
|
144
|
+
return self.add_source(database, sql_folder_source(directory, source_name))
|
|
145
|
+
|
|
146
|
+
def add_migrations(self, database: str, source_name: str, migrations: Sequence[CliMigration]) -> "CliDatabasesBuilder":
|
|
147
|
+
"""Migrations given in code, as source ``source_name`` (how plugins ship their schema)."""
|
|
148
|
+
return self.add_source(database, code_source(source_name, migrations))
|
|
149
|
+
|
|
150
|
+
def set_audit_store(self, store: IAuditStore) -> "CliDatabasesBuilder":
|
|
151
|
+
"""Writes every run to the audit log (``migrations.up`` / ``migrations.down``)."""
|
|
152
|
+
self._audit_store = store
|
|
153
|
+
return self
|
|
154
|
+
|
|
155
|
+
def set_dashboard_dir(self, directory: str | bool) -> "CliDatabasesBuilder":
|
|
156
|
+
"""Where the dashboard's Databases page is (``@qodalis/cli-dashboard-module-databases``'s build); by
|
|
157
|
+
default the copy inside the package. ``False`` leaves the page out."""
|
|
158
|
+
self._dashboard_dir = directory
|
|
159
|
+
return self
|
|
160
|
+
|
|
161
|
+
def build(self) -> CliDatabasesPlugin:
|
|
162
|
+
databases = CliDatabases()
|
|
163
|
+
for name, options, sources in self._databases:
|
|
164
|
+
runner = CliMigrationRunner(name, options)
|
|
165
|
+
for source in sources:
|
|
166
|
+
runner.add_source(source)
|
|
167
|
+
databases.add(runner)
|
|
168
|
+
databases.audit_store = self._audit_store
|
|
169
|
+
page = databases_page(self._dashboard_dir)
|
|
170
|
+
return CliDatabasesPlugin(
|
|
171
|
+
prefix=DATABASES_PREFIX,
|
|
172
|
+
router=create_databases_router(databases),
|
|
173
|
+
databases=databases,
|
|
174
|
+
module=_DatabasesModule(CliDatabasesCommandProcessor(databases)),
|
|
175
|
+
route_permissions=[CliRoutePermission(DATABASES_PREFIX, DATABASES_READ, DATABASES_MIGRATE)],
|
|
176
|
+
permissions=list(DATABASES_PERMISSION_ENTRIES),
|
|
177
|
+
dashboard_pages=[page] if page else [],
|
|
178
|
+
_startup=[name for name, options, _ in self._databases if options.apply_on_startup],
|
|
179
|
+
)
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""Terminal commands: ``databases`` (alias ``db``) — ``list``, ``stats <db>``, ``migrations <db>``,
|
|
2
|
+
``up <db>``, ``down <db> --to <id>``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from qodalis_cli_server_abstractions import (
|
|
10
|
+
CliCommandExample,
|
|
11
|
+
CliCommandParameterDescriptor,
|
|
12
|
+
CliCommandProcessor,
|
|
13
|
+
CliProcessCommand,
|
|
14
|
+
ICliCommandParameterDescriptor,
|
|
15
|
+
ICliCommandProcessor,
|
|
16
|
+
get_positional_text,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from .databases import DATABASES_MIGRATE, DATABASES_READ, CliDatabases
|
|
20
|
+
from .runner import CliMigrationError, CliMigrationRun, CliMigrationRunOptions
|
|
21
|
+
|
|
22
|
+
_TO = CliCommandParameterDescriptor(
|
|
23
|
+
"to", "Migration to stop at (id or source:id; down: base for everything)", False, "string",
|
|
24
|
+
)
|
|
25
|
+
_DRY_RUN = CliCommandParameterDescriptor("dry-run", "Show the SQL instead of running it", False, "boolean")
|
|
26
|
+
_FORCE = CliCommandParameterDescriptor("force", "Run although migrations changed or went missing", False, "boolean")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _database_of(databases: CliDatabases, command: CliProcessCommand) -> str:
|
|
30
|
+
name = get_positional_text(command) or (databases.databases[0].name if len(databases.databases) == 1 else "")
|
|
31
|
+
if not name:
|
|
32
|
+
raise CliMigrationError(f"name the database: {', '.join(d.name for d in databases.databases)}", 400)
|
|
33
|
+
return name
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def format_bytes(value: Any) -> str:
|
|
37
|
+
"""``1.5 MB``-style size."""
|
|
38
|
+
if not isinstance(value, (int, float)):
|
|
39
|
+
return "-"
|
|
40
|
+
size = float(value)
|
|
41
|
+
for unit in ("B", "KB", "MB", "GB", "TB"):
|
|
42
|
+
if size < 1024 or unit == "TB":
|
|
43
|
+
return f"{int(size)} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
|
44
|
+
size /= 1024
|
|
45
|
+
return f"{size:.1f} TB"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _describe_run(run: CliMigrationRun) -> str:
|
|
49
|
+
verb = "Applied" if run.direction == "up" else "Rolled back"
|
|
50
|
+
lines = [f"{verb} {len(run.applied)} migration(s) ({run.status})"]
|
|
51
|
+
lines += [f" {a['source']}:{a['id']} {a['name']} {a['durationMs']} ms" for a in run.applied]
|
|
52
|
+
if run.error:
|
|
53
|
+
lines.append(f"Failed: {run.error}")
|
|
54
|
+
return "\n".join(lines)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def describe_stats(stats: dict[str, Any]) -> str:
|
|
58
|
+
"""The stats as text (terminal and MCP)."""
|
|
59
|
+
lines = [f"{stats['name']} ({stats['dialect']})"]
|
|
60
|
+
server = stats.get("server") or {}
|
|
61
|
+
if server.get("version"):
|
|
62
|
+
uptime = server.get("uptimeSeconds")
|
|
63
|
+
lines.append(f" Server: {server['version']}" + (f", up {uptime // 3600}h {uptime % 3600 // 60}m" if isinstance(uptime, int) else ""))
|
|
64
|
+
size = stats.get("size") or {}
|
|
65
|
+
if size.get("bytes") is not None:
|
|
66
|
+
parts = [f"{label} {format_bytes(size[key])}" for key, label in (("dataBytes", "data"), ("indexBytes", "indexes"), ("logBytes", "log")) if size.get(key) is not None]
|
|
67
|
+
lines.append(f" Size: {format_bytes(size['bytes'])}" + (f" ({', '.join(parts)})" if parts else ""))
|
|
68
|
+
conns = stats.get("connections") or {}
|
|
69
|
+
if conns:
|
|
70
|
+
lines.append(" Connections: " + ", ".join(f"{conns[k]} {k}" for k in ("active", "open", "max") if conns.get(k) is not None))
|
|
71
|
+
counters = stats.get("counters") or {}
|
|
72
|
+
if counters:
|
|
73
|
+
scope = f" (since {'server' if stats.get('countersScope') == 'server' else 'database'} start)"
|
|
74
|
+
lines.append(" Counters: " + ", ".join(f"{k} {v}" for k, v in counters.items()) + scope)
|
|
75
|
+
if stats.get("cacheHitRatio") is not None:
|
|
76
|
+
lines.append(f" Cache hits: {stats['cacheHitRatio'] * 100:.1f}%")
|
|
77
|
+
tables = stats.get("tables") or []
|
|
78
|
+
if tables:
|
|
79
|
+
lines.append(" Largest tables:")
|
|
80
|
+
for t in tables:
|
|
81
|
+
name = f"{t['schema']}.{t['name']}" if t.get("schema") else t["name"]
|
|
82
|
+
rows = f"{t['rows']} rows" if t.get("rows") is not None else ""
|
|
83
|
+
lines.append(f" {name:<32} {format_bytes(t.get('bytes')) if t.get('bytes') is not None else '':>10} {rows}")
|
|
84
|
+
for u in stats.get("unavailable") or []:
|
|
85
|
+
lines.append(f" {u['metric']}: unavailable ({u['error']})")
|
|
86
|
+
return "\n".join(lines)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def describe_databases(databases: list[dict[str, Any]]) -> str:
|
|
90
|
+
"""The databases list as text (terminal and MCP)."""
|
|
91
|
+
if not databases:
|
|
92
|
+
return "No databases registered."
|
|
93
|
+
lines = []
|
|
94
|
+
for d in databases:
|
|
95
|
+
size = f", {format_bytes(d['sizeBytes'])}" if d.get("sizeBytes") is not None else ""
|
|
96
|
+
if d.get("error"):
|
|
97
|
+
lines.append(f"{d['name']} ({d['dialect']}{size}): {d['error']}")
|
|
98
|
+
else:
|
|
99
|
+
problems = f", {d['problems']} to look at" if d["problems"] else ""
|
|
100
|
+
lines.append(f"{d['name']} ({d['dialect']}{size}): {d['applied']} applied, {d['pending']} pending{problems}")
|
|
101
|
+
return "\n".join(lines)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _flag(command: CliProcessCommand, name: str) -> bool:
|
|
105
|
+
value = (command.args or {}).get(name)
|
|
106
|
+
return value is True or (isinstance(value, str) and value.lower() in ("true", "1", ""))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _caller() -> str | None:
|
|
110
|
+
"""The signed-in user running the command (``get_cli_caller``), when the server provides it."""
|
|
111
|
+
try:
|
|
112
|
+
from qodalis_cli import get_cli_caller # the server package, optional here
|
|
113
|
+
except ImportError:
|
|
114
|
+
return None
|
|
115
|
+
caller = get_cli_caller()
|
|
116
|
+
return getattr(caller, "user_name", None) if caller is not None else None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class _ListProcessor(CliCommandProcessor):
|
|
120
|
+
def __init__(self, databases: CliDatabases) -> None:
|
|
121
|
+
self._databases = databases
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def command(self) -> str:
|
|
125
|
+
return "list"
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def description(self) -> str:
|
|
129
|
+
return "Lists the databases: dialect, size and migrations"
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def required_permissions(self) -> list[str]:
|
|
133
|
+
return [DATABASES_READ]
|
|
134
|
+
|
|
135
|
+
async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
|
|
136
|
+
return describe_databases(await self._databases.overview())
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class _StatsProcessor(CliCommandProcessor):
|
|
140
|
+
def __init__(self, databases: CliDatabases) -> None:
|
|
141
|
+
self._databases = databases
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def command(self) -> str:
|
|
145
|
+
return "stats"
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def description(self) -> str:
|
|
149
|
+
return "Shows a database's size, connections, load counters and largest tables"
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def required_permissions(self) -> list[str]:
|
|
153
|
+
return [DATABASES_READ]
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def examples(self) -> list[CliCommandExample]:
|
|
157
|
+
return [CliCommandExample("databases stats main", "Stats of the database main")]
|
|
158
|
+
|
|
159
|
+
async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
|
|
160
|
+
try:
|
|
161
|
+
return describe_stats(await self._databases.stats(_database_of(self._databases, command)))
|
|
162
|
+
except Exception as exc: # noqa: BLE001 - shown to the user
|
|
163
|
+
return f"Error: {exc}"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class _MigrationsProcessor(CliCommandProcessor):
|
|
167
|
+
def __init__(self, databases: CliDatabases) -> None:
|
|
168
|
+
self._databases = databases
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def command(self) -> str:
|
|
172
|
+
return "migrations"
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def description(self) -> str:
|
|
176
|
+
return "Shows the migrations of a database and their status"
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def required_permissions(self) -> list[str]:
|
|
180
|
+
return [DATABASES_READ]
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def examples(self) -> list[CliCommandExample]:
|
|
184
|
+
return [CliCommandExample("databases migrations main", "Migrations of the database main")]
|
|
185
|
+
|
|
186
|
+
async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
|
|
187
|
+
try:
|
|
188
|
+
db = self._databases.require(_database_of(self._databases, command))
|
|
189
|
+
states = await db.status()
|
|
190
|
+
except Exception as exc: # noqa: BLE001 - shown to the user
|
|
191
|
+
return f"Error: {exc}"
|
|
192
|
+
if not states:
|
|
193
|
+
return f"{db.name}: no migrations"
|
|
194
|
+
lines = [f"{db.name} ({db.dialect})"]
|
|
195
|
+
lines += [
|
|
196
|
+
f" {s.status:<8} {s.source}:{s.id} {s.name}{' ' + s.applied_at if s.applied_at else ''}" for s in states
|
|
197
|
+
]
|
|
198
|
+
return "\n".join(lines)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class _RunProcessor(CliCommandProcessor):
|
|
202
|
+
def __init__(self, databases: CliDatabases, direction: str) -> None:
|
|
203
|
+
self._databases = databases
|
|
204
|
+
self._direction = direction
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def command(self) -> str:
|
|
208
|
+
return self._direction
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def description(self) -> str:
|
|
212
|
+
return (
|
|
213
|
+
"Applies the pending migrations of a database" if self._direction == "up"
|
|
214
|
+
else "Rolls back migrations of a database to --to"
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def required_permissions(self) -> list[str]:
|
|
219
|
+
return [DATABASES_MIGRATE]
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def parameters(self) -> list[ICliCommandParameterDescriptor]:
|
|
223
|
+
return [_TO, _DRY_RUN, _FORCE]
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def examples(self) -> list[CliCommandExample]:
|
|
227
|
+
if self._direction == "up":
|
|
228
|
+
return [
|
|
229
|
+
CliCommandExample("databases up main", "Apply every pending migration"),
|
|
230
|
+
CliCommandExample("databases up main --dry-run", "Show the SQL first"),
|
|
231
|
+
]
|
|
232
|
+
return [CliCommandExample("databases down main --to 0003", "Roll back what came after 0003")]
|
|
233
|
+
|
|
234
|
+
async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
|
|
235
|
+
try:
|
|
236
|
+
name = _database_of(self._databases, command)
|
|
237
|
+
raw_to: Any = (command.args or {}).get("to")
|
|
238
|
+
to = str(raw_to) if raw_to not in (None, True, "") else None
|
|
239
|
+
if self._direction == "down" and not to:
|
|
240
|
+
return "Error: --to is required to roll back (an id, or base for everything)"
|
|
241
|
+
if _flag(command, "dry-run"):
|
|
242
|
+
db = self._databases.require(name)
|
|
243
|
+
options = CliMigrationRunOptions(to=to, dry_run=True)
|
|
244
|
+
result = await (db.up(options) if self._direction == "up" else db.down(options))
|
|
245
|
+
return result["sql"] or "Nothing to run." # type: ignore[index]
|
|
246
|
+
run = await self._databases.run(name, self._direction, CliMigrationRunOptions( # type: ignore[arg-type]
|
|
247
|
+
to=to, force=_flag(command, "force"), actor=_caller(), trigger="terminal",
|
|
248
|
+
))
|
|
249
|
+
return _describe_run(run)
|
|
250
|
+
except Exception as exc: # noqa: BLE001 - shown to the user
|
|
251
|
+
return f"Error: {exc}"
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class CliDatabasesCommandProcessor(CliCommandProcessor):
|
|
255
|
+
"""``databases`` (alias ``db``): ``list``, ``stats <db>``, ``migrations <db>``, ``up <db>``,
|
|
256
|
+
``down <db> --to <id>``."""
|
|
257
|
+
|
|
258
|
+
def __init__(self, databases: CliDatabases) -> None:
|
|
259
|
+
self._databases = databases
|
|
260
|
+
self._processors: list[ICliCommandProcessor] = [
|
|
261
|
+
_ListProcessor(databases),
|
|
262
|
+
_StatsProcessor(databases),
|
|
263
|
+
_MigrationsProcessor(databases),
|
|
264
|
+
_RunProcessor(databases, "up"),
|
|
265
|
+
_RunProcessor(databases, "down"),
|
|
266
|
+
]
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def command(self) -> str:
|
|
270
|
+
return "databases"
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def aliases(self) -> list[str]:
|
|
274
|
+
return ["db"]
|
|
275
|
+
|
|
276
|
+
@property
|
|
277
|
+
def description(self) -> str:
|
|
278
|
+
return "Databases: stats and migrations (status, apply, roll back)"
|
|
279
|
+
|
|
280
|
+
@property
|
|
281
|
+
def module(self) -> str:
|
|
282
|
+
return "databases"
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def icon(self) -> str:
|
|
286
|
+
return "🗄️"
|
|
287
|
+
|
|
288
|
+
@property
|
|
289
|
+
def required_permissions(self) -> list[str]:
|
|
290
|
+
return [DATABASES_READ]
|
|
291
|
+
|
|
292
|
+
@property
|
|
293
|
+
def processors(self) -> list[ICliCommandProcessor]:
|
|
294
|
+
return self._processors
|
|
295
|
+
|
|
296
|
+
async def handle_async(self, command: CliProcessCommand, cancellation_event: asyncio.Event | None = None) -> str:
|
|
297
|
+
return describe_databases(await self._databases.overview())
|