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,514 @@
|
|
|
1
|
+
"""Runs one database's migrations: status, up, down, and the run history."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Any, Awaitable, Callable, Literal
|
|
12
|
+
|
|
13
|
+
from qodalis_cli_server_abstractions import CliTableNameOptions, qcli_table_name
|
|
14
|
+
|
|
15
|
+
from .connection import CliSqlConnection, CliSqlSession
|
|
16
|
+
from .dialects import (
|
|
17
|
+
TRANSACTION,
|
|
18
|
+
HistoryTables,
|
|
19
|
+
acquire_lock,
|
|
20
|
+
ensure_history_tables,
|
|
21
|
+
quote_ident,
|
|
22
|
+
quote_table,
|
|
23
|
+
release_lock,
|
|
24
|
+
table_exists,
|
|
25
|
+
)
|
|
26
|
+
from .sources import CliMigration, CliMigrationSource, checksum_of, id_sort_key, step_sql
|
|
27
|
+
|
|
28
|
+
#: Where a migration stands in a database.
|
|
29
|
+
CliMigrationStatus = Literal["applied", "pending", "changed", "missing", "failed"]
|
|
30
|
+
#: What started a run.
|
|
31
|
+
CliMigrationTrigger = Literal["startup", "api", "terminal", "mcp"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def iso(value: Any) -> str | None:
|
|
35
|
+
"""A time as ``2026-11-23T10:00:00.000Z`` (naive values are UTC)."""
|
|
36
|
+
if value is None:
|
|
37
|
+
return None
|
|
38
|
+
if isinstance(value, str):
|
|
39
|
+
try:
|
|
40
|
+
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
41
|
+
except ValueError:
|
|
42
|
+
return value
|
|
43
|
+
if isinstance(value, datetime):
|
|
44
|
+
if value.tzinfo is None:
|
|
45
|
+
value = value.replace(tzinfo=timezone.utc)
|
|
46
|
+
value = value.astimezone(timezone.utc)
|
|
47
|
+
return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}Z"
|
|
48
|
+
return str(value)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _now() -> datetime:
|
|
52
|
+
return datetime.now(timezone.utc)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class CliMigrationState:
|
|
57
|
+
"""A migration with its status (``GET /api/v1/qcli/databases/{db}/migrations``)."""
|
|
58
|
+
|
|
59
|
+
source: str
|
|
60
|
+
id: str
|
|
61
|
+
name: str
|
|
62
|
+
status: CliMigrationStatus
|
|
63
|
+
has_down: bool
|
|
64
|
+
applied_at: str | None = None
|
|
65
|
+
duration_ms: int | None = None
|
|
66
|
+
applied_by: str | None = None
|
|
67
|
+
|
|
68
|
+
def to_dict(self) -> dict[str, Any]:
|
|
69
|
+
out: dict[str, Any] = {"source": self.source, "id": self.id, "name": self.name, "status": self.status}
|
|
70
|
+
if self.applied_at is not None:
|
|
71
|
+
out["appliedAt"] = self.applied_at
|
|
72
|
+
if self.duration_ms is not None:
|
|
73
|
+
out["durationMs"] = self.duration_ms
|
|
74
|
+
if self.applied_by:
|
|
75
|
+
out["appliedBy"] = self.applied_by
|
|
76
|
+
out["hasDown"] = self.has_down
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class CliMigrationRun:
|
|
82
|
+
"""One invocation of up or down, kept in ``QcliMigrationRuns``."""
|
|
83
|
+
|
|
84
|
+
id: str
|
|
85
|
+
direction: Literal["up", "down"]
|
|
86
|
+
trigger: CliMigrationTrigger
|
|
87
|
+
started_at: str
|
|
88
|
+
status: Literal["running", "succeeded", "failed"]
|
|
89
|
+
target: str | None = None
|
|
90
|
+
actor: str | None = None
|
|
91
|
+
finished_at: str | None = None
|
|
92
|
+
error: str | None = None
|
|
93
|
+
#: The migrations it applied (up) or rolled back (down), in order, with their durations
|
|
94
|
+
#: (``{"source", "id", "name", "durationMs"}``).
|
|
95
|
+
applied: list[dict[str, Any]] = field(default_factory=list)
|
|
96
|
+
#: The migration it stopped at (``{"source", "id"}``).
|
|
97
|
+
failed: dict[str, str] | None = None
|
|
98
|
+
|
|
99
|
+
def to_dict(self) -> dict[str, Any]:
|
|
100
|
+
out: dict[str, Any] = {"id": self.id, "direction": self.direction}
|
|
101
|
+
if self.target is not None:
|
|
102
|
+
out["target"] = self.target
|
|
103
|
+
out["trigger"] = self.trigger
|
|
104
|
+
if self.actor:
|
|
105
|
+
out["actor"] = self.actor
|
|
106
|
+
out["startedAt"] = self.started_at
|
|
107
|
+
if self.finished_at:
|
|
108
|
+
out["finishedAt"] = self.finished_at
|
|
109
|
+
out["status"] = self.status
|
|
110
|
+
if self.error:
|
|
111
|
+
out["error"] = self.error
|
|
112
|
+
out["applied"] = list(self.applied)
|
|
113
|
+
if self.failed:
|
|
114
|
+
out["failed"] = dict(self.failed)
|
|
115
|
+
return out
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass
|
|
119
|
+
class CliMigrationRunOptions:
|
|
120
|
+
#: Up: stop after this migration (``id`` or ``source:id``). Down: roll back to it, keeping it
|
|
121
|
+
#: (``base`` = everything).
|
|
122
|
+
to: str | None = None
|
|
123
|
+
#: Run although a migration is ``changed`` or ``missing``.
|
|
124
|
+
force: bool = False
|
|
125
|
+
#: Return the SQL instead of running it.
|
|
126
|
+
dry_run: bool = False
|
|
127
|
+
actor: str | None = None
|
|
128
|
+
trigger: CliMigrationTrigger = "api"
|
|
129
|
+
#: Wait for another process's run instead of answering busy (startup does).
|
|
130
|
+
wait: bool = False
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class CliMigrationError(Exception):
|
|
134
|
+
"""A refused request: ``status`` is the HTTP status the API answers (400, 404, 409)."""
|
|
135
|
+
|
|
136
|
+
def __init__(self, message: str, status: int) -> None:
|
|
137
|
+
super().__init__(message)
|
|
138
|
+
self.message = message
|
|
139
|
+
self.status = status
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass
|
|
143
|
+
class CliMigrationDatabaseOptions:
|
|
144
|
+
"""A database to migrate."""
|
|
145
|
+
|
|
146
|
+
connection: CliSqlConnection
|
|
147
|
+
#: Apply pending migrations when the server starts (it waits for them; a failure stops startup).
|
|
148
|
+
apply_on_startup: bool = False
|
|
149
|
+
#: Names of the history tables (``QcliMigrations``, ``QcliMigrationRuns``): prefix, schema, overrides.
|
|
150
|
+
table_prefix: str | None = None
|
|
151
|
+
schema: str | None = None
|
|
152
|
+
tables: dict[str, str] = field(default_factory=dict)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@dataclass
|
|
156
|
+
class _Loaded:
|
|
157
|
+
source: str
|
|
158
|
+
migration: CliMigration
|
|
159
|
+
checksum: str | None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _key(source: str, mid: str) -> str:
|
|
163
|
+
return f"{source}\u0000{mid}"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class CliMigrationRunner:
|
|
167
|
+
"""Runs one database's migrations: status, up, down, and the run history."""
|
|
168
|
+
|
|
169
|
+
def __init__(self, name: str, options: CliMigrationDatabaseOptions) -> None:
|
|
170
|
+
self.name = name
|
|
171
|
+
self.options = options
|
|
172
|
+
names = CliTableNameOptions(table_prefix=options.table_prefix, tables=dict(options.tables or {}), schema=options.schema)
|
|
173
|
+
self.tables = HistoryTables(
|
|
174
|
+
migrations=qcli_table_name("Migrations", names),
|
|
175
|
+
runs=qcli_table_name("MigrationRuns", names),
|
|
176
|
+
)
|
|
177
|
+
self._sources: list[CliMigrationSource] = []
|
|
178
|
+
self._running: asyncio.Future[Any] | None = None
|
|
179
|
+
self._current_run: str | None = None
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def dialect(self) -> str:
|
|
183
|
+
return self.options.connection.dialect
|
|
184
|
+
|
|
185
|
+
def add_source(self, source: CliMigrationSource) -> "CliMigrationRunner":
|
|
186
|
+
"""Adds a source; sources apply in the order they were added."""
|
|
187
|
+
if any(s.name == source.name for s in self._sources):
|
|
188
|
+
raise ValueError(f"migration source already added to {self.name}: {source.name}")
|
|
189
|
+
self._sources.append(source)
|
|
190
|
+
return self
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def source_names(self) -> list[str]:
|
|
194
|
+
return [s.name for s in self._sources]
|
|
195
|
+
|
|
196
|
+
async def _load(self) -> list[_Loaded]:
|
|
197
|
+
out: list[_Loaded] = []
|
|
198
|
+
for source in self._sources:
|
|
199
|
+
migrations = sorted(await source.load(), key=lambda m: id_sort_key(m.id))
|
|
200
|
+
for a, b in zip(migrations, migrations[1:]):
|
|
201
|
+
if a.id == b.id:
|
|
202
|
+
raise ValueError(f"duplicate migration {source.name}:{b.id}")
|
|
203
|
+
for m in migrations:
|
|
204
|
+
out.append(_Loaded(source.name, m, checksum_of(m, self.dialect)))
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
def _table(self, name: str) -> str:
|
|
208
|
+
return quote_table(self.dialect, name, self.options.schema)
|
|
209
|
+
|
|
210
|
+
def _cols(self, *names: str) -> str:
|
|
211
|
+
return ", ".join(quote_ident(self.dialect, n) for n in names)
|
|
212
|
+
|
|
213
|
+
def _c(self, name: str) -> str:
|
|
214
|
+
return quote_ident(self.dialect, name)
|
|
215
|
+
|
|
216
|
+
async def _history(self, db: CliSqlSession) -> list[dict[str, Any]]:
|
|
217
|
+
if not await table_exists(db, self.tables.migrations, self.options.schema):
|
|
218
|
+
return []
|
|
219
|
+
return await db.query(
|
|
220
|
+
f"SELECT {self._cols('Source', 'Id', 'Name', 'Checksum', 'AppliedAt', 'DurationMs', 'AppliedBy')} "
|
|
221
|
+
f"FROM {self._table(self.tables.migrations)}"
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
async def _last_failure(self, db: CliSqlSession) -> dict[str, str] | None:
|
|
225
|
+
items, _ = await self._runs_on(db, 1, 0)
|
|
226
|
+
return items[0].failed if items and items[0].status == "failed" else None
|
|
227
|
+
|
|
228
|
+
def _states_of(
|
|
229
|
+
self, loaded: list[_Loaded], rows: list[dict[str, Any]], failed: dict[str, str] | None = None,
|
|
230
|
+
) -> list[CliMigrationState]:
|
|
231
|
+
applied = {_key(r["Source"], str(r["Id"])): r for r in rows}
|
|
232
|
+
known = {_key(l.source, l.migration.id) for l in loaded}
|
|
233
|
+
states: list[CliMigrationState] = []
|
|
234
|
+
for l in loaded:
|
|
235
|
+
row = applied.get(_key(l.source, l.migration.id))
|
|
236
|
+
has_down = l.migration.down is not None
|
|
237
|
+
if row is None:
|
|
238
|
+
is_failed = failed is not None and failed.get("source") == l.source and failed.get("id") == l.migration.id
|
|
239
|
+
states.append(CliMigrationState(l.source, l.migration.id, l.migration.name, "failed" if is_failed else "pending", has_down))
|
|
240
|
+
continue
|
|
241
|
+
changed = bool(row["Checksum"]) and bool(l.checksum) and row["Checksum"] != l.checksum
|
|
242
|
+
states.append(CliMigrationState(
|
|
243
|
+
l.source, l.migration.id, l.migration.name, "changed" if changed else "applied", has_down,
|
|
244
|
+
applied_at=iso(row["AppliedAt"]), duration_ms=int(row["DurationMs"]), applied_by=row["AppliedBy"] or None,
|
|
245
|
+
))
|
|
246
|
+
# Applied, but gone from its source (a source this runner still has)
|
|
247
|
+
sources = set(self.source_names)
|
|
248
|
+
for row in rows:
|
|
249
|
+
if row["Source"] in sources and _key(row["Source"], str(row["Id"])) not in known:
|
|
250
|
+
states.append(CliMigrationState(
|
|
251
|
+
row["Source"], str(row["Id"]), row["Name"], "missing", False,
|
|
252
|
+
applied_at=iso(row["AppliedAt"]), duration_ms=int(row["DurationMs"]), applied_by=row["AppliedBy"] or None,
|
|
253
|
+
))
|
|
254
|
+
return states
|
|
255
|
+
|
|
256
|
+
async def status(self) -> list[CliMigrationState]:
|
|
257
|
+
"""Every migration with its status."""
|
|
258
|
+
loaded = await self._load()
|
|
259
|
+
async with self.options.connection.session() as db:
|
|
260
|
+
return self._states_of(loaded, await self._history(db), await self._last_failure(db))
|
|
261
|
+
|
|
262
|
+
async def runs(self, limit: int = 20, offset: int = 0) -> tuple[list[CliMigrationRun], int]:
|
|
263
|
+
"""The latest runs, newest first, and their total."""
|
|
264
|
+
async with self.options.connection.session() as db:
|
|
265
|
+
return await self._runs_on(db, limit, offset)
|
|
266
|
+
|
|
267
|
+
async def _runs_on(self, db: CliSqlSession, limit: int, offset: int) -> tuple[list[CliMigrationRun], int]:
|
|
268
|
+
if not await table_exists(db, self.tables.runs, self.options.schema):
|
|
269
|
+
return [], 0
|
|
270
|
+
table = self._table(self.tables.runs)
|
|
271
|
+
total_rows = await db.query(f"SELECT COUNT(*) AS n FROM {table}")
|
|
272
|
+
total = int(total_rows[0]["n"]) if total_rows else 0
|
|
273
|
+
limit = max(1, int(limit))
|
|
274
|
+
offset = max(0, int(offset))
|
|
275
|
+
page = (
|
|
276
|
+
f"OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY" if self.dialect == "mssql"
|
|
277
|
+
else f"LIMIT {limit} OFFSET {offset}"
|
|
278
|
+
)
|
|
279
|
+
rows = await db.query(
|
|
280
|
+
f"SELECT {self._cols('Id', 'Direction', 'Target', 'Trigger', 'Actor', 'StartedAt', 'FinishedAt', 'Status', 'Error', 'Applied')} "
|
|
281
|
+
f"FROM {table} ORDER BY {self._c('StartedAt')} DESC, {self._c('Id')} DESC {page}"
|
|
282
|
+
)
|
|
283
|
+
return [self._run_of(r) for r in rows], total
|
|
284
|
+
|
|
285
|
+
@staticmethod
|
|
286
|
+
def _run_of(r: dict[str, Any]) -> CliMigrationRun:
|
|
287
|
+
detail = json.loads(r["Applied"]) if r.get("Applied") else {"applied": []}
|
|
288
|
+
return CliMigrationRun(
|
|
289
|
+
id=str(r["Id"]),
|
|
290
|
+
direction=r["Direction"],
|
|
291
|
+
trigger=r["Trigger"],
|
|
292
|
+
started_at=iso(r["StartedAt"]) or "",
|
|
293
|
+
status=r["Status"],
|
|
294
|
+
target=str(r["Target"]) if r.get("Target") else None,
|
|
295
|
+
actor=str(r["Actor"]) if r.get("Actor") else None,
|
|
296
|
+
finished_at=iso(r.get("FinishedAt")),
|
|
297
|
+
error=str(r["Error"]) if r.get("Error") else None,
|
|
298
|
+
applied=detail.get("applied") or [],
|
|
299
|
+
failed=detail.get("failed") or None,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
def _find(self, loaded: list[_Loaded], target: str) -> int:
|
|
303
|
+
"""A migration's index by ``id`` or ``source:id``."""
|
|
304
|
+
qualified = target.find(":") > 0
|
|
305
|
+
matches = [
|
|
306
|
+
i for i, l in enumerate(loaded)
|
|
307
|
+
if (f"{l.source}:{l.migration.id}" if qualified else l.migration.id) == target
|
|
308
|
+
]
|
|
309
|
+
if not matches:
|
|
310
|
+
raise CliMigrationError(f"unknown migration: {target}", 404)
|
|
311
|
+
if len(matches) > 1:
|
|
312
|
+
raise CliMigrationError(f"migration {target} is in several sources: name it as source:id", 400)
|
|
313
|
+
return matches[0]
|
|
314
|
+
|
|
315
|
+
async def up(self, options: CliMigrationRunOptions | None = None) -> CliMigrationRun | dict[str, str]:
|
|
316
|
+
"""Applies pending migrations (up to ``to``). Dry run: ``{"sql": ...}``, what it would run."""
|
|
317
|
+
opts = options or CliMigrationRunOptions()
|
|
318
|
+
return await self._exclusive(opts, lambda db, loaded: self._run_up(db, loaded, opts))
|
|
319
|
+
|
|
320
|
+
async def down(self, options: CliMigrationRunOptions) -> CliMigrationRun | dict[str, str]:
|
|
321
|
+
"""Rolls back applied migrations, newest first, down to ``to`` (kept; ``base`` = everything)."""
|
|
322
|
+
if not options.to:
|
|
323
|
+
raise CliMigrationError("to is required to roll back (an id, or base for everything)", 400)
|
|
324
|
+
return await self._exclusive(options, lambda db, loaded: self._run_down(db, loaded, options))
|
|
325
|
+
|
|
326
|
+
async def _exclusive(
|
|
327
|
+
self,
|
|
328
|
+
options: CliMigrationRunOptions,
|
|
329
|
+
fn: Callable[[CliSqlSession, list[_Loaded]], Awaitable[Any]],
|
|
330
|
+
) -> Any:
|
|
331
|
+
"""Runs ``fn`` alone: one run per process at a time, and the database lock across processes."""
|
|
332
|
+
if options.dry_run:
|
|
333
|
+
loaded = await self._load()
|
|
334
|
+
async with self.options.connection.session() as db:
|
|
335
|
+
return await fn(db, loaded)
|
|
336
|
+
while self._running is not None:
|
|
337
|
+
if not options.wait:
|
|
338
|
+
raise CliMigrationError(f"a migration run is in progress on {self.name}", 409)
|
|
339
|
+
try:
|
|
340
|
+
await asyncio.shield(self._running)
|
|
341
|
+
except Exception:
|
|
342
|
+
pass
|
|
343
|
+
|
|
344
|
+
async def run() -> Any:
|
|
345
|
+
loaded = await self._load()
|
|
346
|
+
async with self.options.connection.session() as db:
|
|
347
|
+
key = f"qcli-migrations:{self.options.schema or ''}.{self.tables.migrations}"
|
|
348
|
+
if not await acquire_lock(db, key, options.wait):
|
|
349
|
+
raise CliMigrationError(f"a migration run is in progress on {self.name}", 409)
|
|
350
|
+
try:
|
|
351
|
+
await ensure_history_tables(db, self.tables, self.options.schema)
|
|
352
|
+
return await fn(db, loaded)
|
|
353
|
+
finally:
|
|
354
|
+
try:
|
|
355
|
+
await release_lock(db, key)
|
|
356
|
+
except Exception:
|
|
357
|
+
pass
|
|
358
|
+
|
|
359
|
+
task = asyncio.ensure_future(run())
|
|
360
|
+
self._running = task
|
|
361
|
+
try:
|
|
362
|
+
return await task
|
|
363
|
+
finally:
|
|
364
|
+
self._running = None
|
|
365
|
+
|
|
366
|
+
@staticmethod
|
|
367
|
+
def _blocked(states: list[CliMigrationState], force: bool) -> None:
|
|
368
|
+
problems = [s for s in states if s.status in ("changed", "missing")]
|
|
369
|
+
if problems and not force:
|
|
370
|
+
listed = ", ".join(f"{p.source}:{p.id} ({p.status})" for p in problems)
|
|
371
|
+
raise CliMigrationError(
|
|
372
|
+
f"migrations changed or missing since they were applied: {listed}; fix them or run with force", 409,
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
async def _run_up(self, db: CliSqlSession, loaded: list[_Loaded], options: CliMigrationRunOptions) -> Any:
|
|
376
|
+
states = self._states_of(loaded, await self._history(db))
|
|
377
|
+
self._blocked(states, options.force)
|
|
378
|
+
last = self._find(loaded, options.to) if options.to is not None else len(loaded) - 1
|
|
379
|
+
pending = [l for i, l in enumerate(loaded) if i <= last and states[i].status not in ("applied", "changed")]
|
|
380
|
+
if options.dry_run:
|
|
381
|
+
return {"sql": self._script(pending, "up")}
|
|
382
|
+
|
|
383
|
+
async def step(l: _Loaded) -> int:
|
|
384
|
+
started = time.monotonic()
|
|
385
|
+
|
|
386
|
+
async def bookkeeping(duration_ms: int) -> None:
|
|
387
|
+
await db.query(
|
|
388
|
+
f"INSERT INTO {self._table(self.tables.migrations)} "
|
|
389
|
+
f"({self._cols('Source', 'Id', 'Name', 'Checksum', 'AppliedAt', 'DurationMs', 'AppliedBy', 'RunId')}) "
|
|
390
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
391
|
+
[l.source, l.migration.id, l.migration.name, l.checksum, _now(), duration_ms, options.actor, self._current_run],
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
await self._apply(db, l, "up", bookkeeping)
|
|
395
|
+
return int((time.monotonic() - started) * 1000)
|
|
396
|
+
|
|
397
|
+
return await self._record(db, "up", options, pending, step)
|
|
398
|
+
|
|
399
|
+
async def _run_down(self, db: CliSqlSession, loaded: list[_Loaded], options: CliMigrationRunOptions) -> Any:
|
|
400
|
+
states = self._states_of(loaded, await self._history(db))
|
|
401
|
+
keep = -1 if options.to == "base" else self._find(loaded, options.to or "")
|
|
402
|
+
undo = [l for i, l in enumerate(loaded) if i > keep and states[i].status in ("applied", "changed")]
|
|
403
|
+
undo.reverse()
|
|
404
|
+
no_down = [l for l in undo if l.migration.down is None]
|
|
405
|
+
if no_down:
|
|
406
|
+
listed = ", ".join(f"{l.source}:{l.migration.id}" for l in no_down)
|
|
407
|
+
raise CliMigrationError(f"cannot roll back: no down step for {listed}", 409)
|
|
408
|
+
if options.dry_run:
|
|
409
|
+
return {"sql": self._script(undo, "down")}
|
|
410
|
+
|
|
411
|
+
async def step(l: _Loaded) -> int:
|
|
412
|
+
started = time.monotonic()
|
|
413
|
+
|
|
414
|
+
async def bookkeeping(_: int) -> None:
|
|
415
|
+
await db.query(
|
|
416
|
+
f"DELETE FROM {self._table(self.tables.migrations)} WHERE {self._c('Source')} = ? AND {self._c('Id')} = ?",
|
|
417
|
+
[l.source, l.migration.id],
|
|
418
|
+
)
|
|
419
|
+
|
|
420
|
+
await self._apply(db, l, "down", bookkeeping)
|
|
421
|
+
return int((time.monotonic() - started) * 1000)
|
|
422
|
+
|
|
423
|
+
return await self._record(db, "down", options, undo, step)
|
|
424
|
+
|
|
425
|
+
def _script(self, items: list[_Loaded], direction: str) -> str:
|
|
426
|
+
"""The SQL of the steps, for a dry run (code steps show as a comment)."""
|
|
427
|
+
parts = []
|
|
428
|
+
for l in items:
|
|
429
|
+
step = l.migration.up if direction == "up" else l.migration.down
|
|
430
|
+
sql = step_sql(step, self.dialect, l.migration.id) # type: ignore[arg-type]
|
|
431
|
+
parts.append(
|
|
432
|
+
f"-- {l.source}:{l.migration.id} {l.migration.name} ({direction})\n"
|
|
433
|
+
+ (sql if sql is not None else "-- (code: runs a function, no SQL to show)")
|
|
434
|
+
)
|
|
435
|
+
return "\n\n".join(parts)
|
|
436
|
+
|
|
437
|
+
async def _apply(
|
|
438
|
+
self, db: CliSqlSession, l: _Loaded, direction: str, bookkeeping: Callable[[int], Awaitable[None]],
|
|
439
|
+
) -> None:
|
|
440
|
+
"""Runs the step and its history change, in one transaction unless the migration opts out."""
|
|
441
|
+
step = l.migration.up if direction == "up" else l.migration.down
|
|
442
|
+
tx = TRANSACTION[self.dialect]
|
|
443
|
+
in_transaction = l.migration.transaction is not False
|
|
444
|
+
started = time.monotonic()
|
|
445
|
+
if in_transaction:
|
|
446
|
+
await db.exec(tx["begin"])
|
|
447
|
+
try:
|
|
448
|
+
sql = step_sql(step, self.dialect, l.migration.id) # type: ignore[arg-type]
|
|
449
|
+
if sql is None:
|
|
450
|
+
await step(db) # type: ignore[misc,operator]
|
|
451
|
+
elif sql.strip():
|
|
452
|
+
await db.exec(sql)
|
|
453
|
+
await bookkeeping(int((time.monotonic() - started) * 1000))
|
|
454
|
+
if in_transaction:
|
|
455
|
+
await db.exec(tx["commit"])
|
|
456
|
+
except BaseException:
|
|
457
|
+
if in_transaction:
|
|
458
|
+
try:
|
|
459
|
+
await db.exec(tx["rollback"])
|
|
460
|
+
except Exception:
|
|
461
|
+
pass
|
|
462
|
+
raise
|
|
463
|
+
|
|
464
|
+
async def _record(
|
|
465
|
+
self,
|
|
466
|
+
db: CliSqlSession,
|
|
467
|
+
direction: Literal["up", "down"],
|
|
468
|
+
options: CliMigrationRunOptions,
|
|
469
|
+
items: list[_Loaded],
|
|
470
|
+
step: Callable[[_Loaded], Awaitable[int]],
|
|
471
|
+
) -> CliMigrationRun:
|
|
472
|
+
"""Runs the steps, recording the run before and at the end."""
|
|
473
|
+
started = _now()
|
|
474
|
+
run = CliMigrationRun(
|
|
475
|
+
id=str(uuid.uuid4()),
|
|
476
|
+
direction=direction,
|
|
477
|
+
trigger=options.trigger,
|
|
478
|
+
started_at=iso(started) or "",
|
|
479
|
+
status="running",
|
|
480
|
+
target=options.to,
|
|
481
|
+
actor=options.actor or None,
|
|
482
|
+
)
|
|
483
|
+
await db.query(
|
|
484
|
+
f"INSERT INTO {self._table(self.tables.runs)} "
|
|
485
|
+
f"({self._cols('Id', 'Direction', 'Target', 'Trigger', 'Actor', 'StartedAt', 'Status', 'Applied')}) "
|
|
486
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
487
|
+
[run.id, direction, run.target, run.trigger, run.actor, started, "running", json.dumps({"applied": []})],
|
|
488
|
+
)
|
|
489
|
+
self._current_run = run.id
|
|
490
|
+
try:
|
|
491
|
+
for l in items:
|
|
492
|
+
try:
|
|
493
|
+
duration_ms = await step(l)
|
|
494
|
+
run.applied.append({"source": l.source, "id": l.migration.id, "name": l.migration.name, "durationMs": duration_ms})
|
|
495
|
+
except Exception as exc: # noqa: BLE001 - recorded on the run
|
|
496
|
+
run.status = "failed"
|
|
497
|
+
run.error = f"{l.source}:{l.migration.id} {l.migration.name}: {exc}"
|
|
498
|
+
run.failed = {"source": l.source, "id": l.migration.id}
|
|
499
|
+
break
|
|
500
|
+
finally:
|
|
501
|
+
self._current_run = None
|
|
502
|
+
if run.status == "running":
|
|
503
|
+
run.status = "succeeded"
|
|
504
|
+
finished = _now()
|
|
505
|
+
run.finished_at = iso(finished)
|
|
506
|
+
detail: dict[str, Any] = {"applied": run.applied}
|
|
507
|
+
if run.failed:
|
|
508
|
+
detail["failed"] = run.failed
|
|
509
|
+
await db.query(
|
|
510
|
+
f"UPDATE {self._table(self.tables.runs)} SET {self._c('FinishedAt')} = ?, {self._c('Status')} = ?, "
|
|
511
|
+
f"{self._c('Error')} = ?, {self._c('Applied')} = ? WHERE {self._c('Id')} = ?",
|
|
512
|
+
[finished, run.status, run.error, json.dumps(detail), run.id],
|
|
513
|
+
)
|
|
514
|
+
return run
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Where a database's migrations come from: a folder of SQL files, or code (how plugins ship their schema)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from dataclasses import dataclass, replace
|
|
9
|
+
from typing import Any, Awaitable, Callable, Mapping, Protocol, Sequence, Union
|
|
10
|
+
|
|
11
|
+
from .connection import CliSqlSession
|
|
12
|
+
|
|
13
|
+
#: A migration step: SQL, SQL per dialect (``{"postgres": ..., "sqlite": ...}``), or a coroutine function
|
|
14
|
+
#: given the session.
|
|
15
|
+
CliMigrationStep = Union[str, Mapping[str, str], Callable[[CliSqlSession], Awaitable[None]]]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class CliMigration:
|
|
20
|
+
"""One schema change. Released migrations are never edited or reordered: add a new one instead."""
|
|
21
|
+
|
|
22
|
+
#: Unique within its source, sortable: ``0001``, ``2``, ``20261120111649``.
|
|
23
|
+
id: str
|
|
24
|
+
#: Shown in the dashboard: ``create users``.
|
|
25
|
+
name: str
|
|
26
|
+
up: CliMigrationStep
|
|
27
|
+
#: Undoes ``up``; without it the migration cannot be rolled back.
|
|
28
|
+
down: CliMigrationStep | None = None
|
|
29
|
+
#: Run inside a transaction with its history row (False for ``CREATE INDEX CONCURRENTLY``).
|
|
30
|
+
transaction: bool = True
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CliMigrationSource(Protocol):
|
|
34
|
+
"""A source of migrations: ``name`` is unique per database (``app``, ``qcli-users``) and stored with every
|
|
35
|
+
applied migration; ``load`` returns the migrations in any order (the runner sorts them by id)."""
|
|
36
|
+
|
|
37
|
+
name: str
|
|
38
|
+
|
|
39
|
+
async def load(self) -> list[CliMigration]: ...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_NUMBER = re.compile(r"(\d+)")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def id_sort_key(value: str) -> list[Any]:
|
|
46
|
+
"""Ids compared as numbers where they are numbers (``2`` before ``10``), else as text."""
|
|
47
|
+
return [(0, int(part), "") if part.isdigit() else (1, 0, part.lower()) for part in _NUMBER.split(value) if part]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def step_sql(step: CliMigrationStep, dialect: str, migration: str) -> str | None:
|
|
51
|
+
"""The SQL a step runs on ``dialect``, or None for a code step; raises when the step has none for the
|
|
52
|
+
dialect."""
|
|
53
|
+
if callable(step):
|
|
54
|
+
return None
|
|
55
|
+
if isinstance(step, str):
|
|
56
|
+
return step
|
|
57
|
+
sql = step.get(dialect)
|
|
58
|
+
if sql is None:
|
|
59
|
+
raise ValueError(f"migration {migration} has no SQL for {dialect}")
|
|
60
|
+
return sql
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def checksum_of(migration: CliMigration, dialect: str) -> str | None:
|
|
64
|
+
"""SHA-256 of the up step's SQL for the dialect; None for code (it cannot be compared reliably)."""
|
|
65
|
+
sql = step_sql(migration.up, dialect, migration.id)
|
|
66
|
+
return None if sql is None else hashlib.sha256(sql.replace("\r\n", "\n").encode("utf-8")).hexdigest()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_NO_TRANSACTION = re.compile(r"^\s*--\s*qcli:no-transaction\b", re.IGNORECASE)
|
|
70
|
+
_FILE = re.compile(r"^([0-9A-Za-z]+)_(.+?)\.(up|down)\.sql$")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class SqlFolderSource:
|
|
74
|
+
"""Migrations from a folder: ``NNNN_name.up.sql``, with an optional ``NNNN_name.down.sql``. A file
|
|
75
|
+
starting with ``-- qcli:no-transaction`` runs outside a transaction. Read again on every load, so a new
|
|
76
|
+
file shows as pending."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, directory: str, name: str = "app") -> None:
|
|
79
|
+
self.directory = directory
|
|
80
|
+
self.name = name
|
|
81
|
+
|
|
82
|
+
async def load(self) -> list[CliMigration]:
|
|
83
|
+
by_id: dict[str, dict[str, str]] = {}
|
|
84
|
+
for file in sorted(os.listdir(self.directory)):
|
|
85
|
+
match = _FILE.match(file)
|
|
86
|
+
if not match:
|
|
87
|
+
continue
|
|
88
|
+
mid, title, direction = match.groups()
|
|
89
|
+
title = re.sub(r"[_-]+", " ", title)
|
|
90
|
+
entry = by_id.setdefault(mid, {"name": title})
|
|
91
|
+
if entry["name"] != title:
|
|
92
|
+
raise ValueError(f"migration {mid} has files with different names in {self.directory}")
|
|
93
|
+
with open(os.path.join(self.directory, file), encoding="utf-8") as f:
|
|
94
|
+
entry[direction] = f.read()
|
|
95
|
+
out: list[CliMigration] = []
|
|
96
|
+
for mid, entry in by_id.items():
|
|
97
|
+
if "up" not in entry:
|
|
98
|
+
raise ValueError(f"migration {mid} has a down file but no up file in {self.directory}")
|
|
99
|
+
out.append(CliMigration(
|
|
100
|
+
id=mid,
|
|
101
|
+
name=entry["name"],
|
|
102
|
+
up=entry["up"],
|
|
103
|
+
down=entry.get("down"),
|
|
104
|
+
transaction=not _NO_TRANSACTION.match(entry["up"]),
|
|
105
|
+
))
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class CodeSource:
|
|
110
|
+
"""Migrations given in code (how plugins ship their schema)."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, name: str, migrations: Sequence[CliMigration]) -> None:
|
|
113
|
+
self.name = name
|
|
114
|
+
self._migrations = list(migrations)
|
|
115
|
+
|
|
116
|
+
async def load(self) -> list[CliMigration]:
|
|
117
|
+
return [replace(m, id=str(m.id)) for m in self._migrations]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def sql_folder_source(directory: str, name: str = "app") -> SqlFolderSource:
|
|
121
|
+
"""Migrations from ``NNNN_name.up.sql`` / ``.down.sql`` files in ``directory``."""
|
|
122
|
+
return SqlFolderSource(directory, name)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def code_source(name: str, migrations: Sequence[CliMigration]) -> CodeSource:
|
|
126
|
+
"""Migrations given in code, as source ``name``."""
|
|
127
|
+
return CodeSource(name, migrations)
|