forked from tortoise/tortoise-orm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlmigrate.py
More file actions
65 lines (49 loc) · 2.23 KB
/
sqlmigrate.py
File metadata and controls
65 lines (49 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from __future__ import annotations
from typing import Any
from tortoise import Tortoise
from tortoise.config import TortoiseConfig
from tortoise.connection import get_connection
from tortoise.migrations.executor import MigrationExecutor
from tortoise.migrations.graph import MigrationKey
from tortoise.migrations.recorder import MigrationRecorder
class _NoopRecorder(MigrationRecorder):
"""A recorder that returns no applied migrations and never touches the DB."""
def __init__(self) -> None:
super().__init__(connection=None)
async def applied_migrations(self) -> list[MigrationKey]:
return []
async def ensure_schema(self, _schema_editor: Any) -> None:
return None
async def sqlmigrate(
*,
config: dict[str, Any] | TortoiseConfig | None = None,
config_file: str | None = None,
app_label: str,
migration_name: str,
backward: bool = False,
) -> list[str]:
"""Collect the SQL statements for a single migration without executing them.
Args:
config: Tortoise ORM config dict or TortoiseConfig object.
config_file: Path to a JSON/YAML config file for Tortoise ORM.
app_label: The application label.
migration_name: The migration name (exact or prefix match).
backward: If True, collect SQL for unapplying the migration.
Returns:
A list of SQL strings (including descriptive comment annotations).
"""
config = TortoiseConfig.resolve_args(config, config_file).to_dict()
if not config:
raise ValueError("sqlmigrate requires a config or config_file")
await Tortoise.init(config=config, init_connections=False)
configured_apps = config.get("apps", {})
if app_label not in configured_apps:
raise ValueError(f"Unknown app label {app_label!r}")
app_config = configured_apps[app_label]
connection_name = app_config.get("default_connection", "default")
connection = get_connection(connection_name)
apps_config = {app_label: app_config}
executor = MigrationExecutor(connection, apps_config)
# Replace the recorder with a noop so build_graph() does not query the DB.
executor.loader.recorder = _NoopRecorder()
return await executor.collect_sql(app_label, migration_name, backward=backward)