alembic-status 1.0.0__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.
@@ -0,0 +1,6 @@
1
+ """Show alembic branches status and upgrade outdated branches."""
2
+
3
+ from alembic_status.core import StatusReport, autoupgrade, get_status
4
+
5
+ __all__ = ["StatusReport", "autoupgrade", "get_status"]
6
+ __version__ = "0.1.0"
alembic_status/cli.py ADDED
@@ -0,0 +1,103 @@
1
+ """Standalone ``alembic-status`` command, usable without Flask."""
2
+
3
+ from collections.abc import Iterator
4
+ from contextlib import contextmanager
5
+
6
+ import click
7
+ from alembic.config import Config
8
+ from sqlalchemy import create_engine
9
+ from sqlalchemy.engine import Connection
10
+
11
+ from alembic_status.core import autoupgrade as run_autoupgrade
12
+ from alembic_status.core import get_status
13
+
14
+
15
+ @contextmanager
16
+ def _connect(config: Config) -> Iterator[Connection]:
17
+ url = config.get_main_option("sqlalchemy.url")
18
+ if not url:
19
+ raise click.UsageError("No database URL: set sqlalchemy.url in the config or pass --url.")
20
+ engine = create_engine(url)
21
+ try:
22
+ with engine.connect() as connection:
23
+ yield connection
24
+ finally:
25
+ engine.dispose()
26
+
27
+
28
+ @click.group(invoke_without_command=True)
29
+ @click.option(
30
+ "-c",
31
+ "--config",
32
+ "config_file",
33
+ default="alembic.ini",
34
+ show_default=True,
35
+ type=click.Path(dir_okay=False, exists=True),
36
+ help="Alembic configuration file.",
37
+ )
38
+ @click.option(
39
+ "-d",
40
+ "--directory",
41
+ default=None,
42
+ help="Migration script directory (default: script_location of the config file).",
43
+ )
44
+ @click.option(
45
+ "--url",
46
+ default=None,
47
+ help="Database URL (default: sqlalchemy.url of the config file).",
48
+ )
49
+ @click.pass_context
50
+ def main(ctx: click.Context, config_file: str, directory: str | None, url: str | None) -> None:
51
+ """Show and upgrade alembic branches. Without a sub-command, shows the status."""
52
+ config = Config(config_file)
53
+ if directory:
54
+ config.set_main_option("script_location", directory)
55
+ if url:
56
+ config.set_main_option("sqlalchemy.url", url)
57
+ ctx.obj = config
58
+ if ctx.invoked_subcommand is None:
59
+ ctx.invoke(status, show_dependencies=False, branches=())
60
+
61
+
62
+ @main.command()
63
+ @click.option(
64
+ "--deps", "--dependencies", "show_dependencies", is_flag=True, help="Show dependencies"
65
+ )
66
+ @click.argument("branches", nargs=-1)
67
+ @click.pass_obj
68
+ def status(config: Config, show_dependencies: bool, branches: tuple[str, ...]) -> None:
69
+ """Show all revisions sorted by branches."""
70
+ with _connect(config) as connection:
71
+ report = get_status(
72
+ config,
73
+ connection,
74
+ branches=branches,
75
+ show_dependencies=show_dependencies,
76
+ style=click.style,
77
+ )
78
+ click.echo(report.text)
79
+
80
+
81
+ @main.command()
82
+ @click.option(
83
+ "--sql",
84
+ is_flag=True,
85
+ help="Don't emit SQL to database - dump to standard output instead",
86
+ )
87
+ @click.option(
88
+ "--tag",
89
+ default=None,
90
+ help='Arbitrary "tag" name - can be used by custom env.py scripts',
91
+ )
92
+ @click.option(
93
+ "-x", "--x-arg", multiple=True, help="Additional arguments consumed by custom env.py scripts"
94
+ )
95
+ @click.pass_obj
96
+ def autoupgrade(config: Config, sql: bool, tag: str | None, x_arg: tuple[str, ...]) -> None:
97
+ """Upgrade all branches to head."""
98
+ with _connect(config) as connection:
99
+ run_autoupgrade(config, connection, sql=sql, tag=tag, x_args=x_arg)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
alembic_status/core.py ADDED
@@ -0,0 +1,327 @@
1
+ """Alembic branch status and autoupgrade, without any Flask dependency."""
2
+
3
+ import argparse
4
+ from collections import defaultdict, deque
5
+ from collections.abc import Callable, Iterable
6
+ from dataclasses import dataclass
7
+ from itertools import chain
8
+ from typing import Any
9
+
10
+ from alembic import command
11
+ from alembic.config import Config
12
+ from alembic.migration import MigrationContext
13
+ from alembic.script import ScriptDirectory
14
+ from alembic.script.base import Script
15
+ from sqlalchemy.engine import Connection
16
+
17
+ Style = Callable[..., str]
18
+
19
+ OUTDATED_MESSAGE = "Some branches are outdated, run 'autoupgrade' to upgrade them."
20
+
21
+
22
+ def _no_style(text: str, **_: Any) -> str:
23
+ return text
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class StatusReport:
28
+ text: str
29
+ outdated: bool
30
+
31
+
32
+ def box_drawing(up: bool, down: bool, left: bool, right: bool, bold: bool = True) -> str:
33
+ if not up and not down and not left and not right:
34
+ return "─"
35
+ elif up and not down and not left and not right:
36
+ return "┸"
37
+ elif not up and down and not left and not right:
38
+ return "┰"
39
+ elif up and down and not left and not right:
40
+ return "┃"
41
+ elif up and not down and left and not right:
42
+ return "┛"
43
+ elif up and not down and not left and right:
44
+ return "┗" if bold else "└"
45
+ elif not up and not down:
46
+ return "━"
47
+ elif not up and down and left and not right:
48
+ return "┓"
49
+ elif not up and down and not left and right:
50
+ return "┏"
51
+ elif up and down and not left and right:
52
+ return "┣" if bold else "├"
53
+ elif up and down and left and not right:
54
+ return "┫"
55
+ elif up and not down and left and right:
56
+ return "┻"
57
+ elif not up and down and left and right:
58
+ return "┳"
59
+ elif up and down and left and right:
60
+ return "╋"
61
+ else:
62
+ raise ValueError("Unexpected box drawing symbol")
63
+
64
+
65
+ def set_x_args(config: Config, x_args: Iterable[str]) -> None:
66
+ x_args = list(x_args)
67
+ if x_args:
68
+ config.cmd_opts = argparse.Namespace(x=x_args)
69
+
70
+
71
+ def _branch_label(revision: Script) -> str:
72
+ labels = revision.branch_labels
73
+ if not labels:
74
+ raise ValueError(
75
+ f"Revision {revision.revision} has no branch label. Every branch base needs a "
76
+ "branch_labels entry, see the README."
77
+ )
78
+ if len(labels) > 1:
79
+ found = ", ".join(sorted(labels))
80
+ raise ValueError(
81
+ f"Revision {revision.revision} belongs to several branches ({found}). "
82
+ "Merging branches is not supported, see the README."
83
+ )
84
+ (label,) = labels
85
+ return label
86
+
87
+
88
+ def _parent_ids(revision: Script) -> list[str]:
89
+ parents: list[str] = []
90
+ for value in (revision.down_revision, revision.dependencies):
91
+ if isinstance(value, str):
92
+ parents.append(value)
93
+ elif value:
94
+ parents.extend(value)
95
+ return parents
96
+
97
+
98
+ def _find_cycle(graph: dict[str, set[str]]) -> list[str] | None:
99
+ done: set[str] = set()
100
+
101
+ def visit(node: str, path: list[str]) -> list[str] | None:
102
+ if node in path:
103
+ return [*path[path.index(node) :], node]
104
+ if node in done:
105
+ return None
106
+ for successor in sorted(graph.get(node, ())):
107
+ cycle = visit(successor, [*path, node])
108
+ if cycle:
109
+ return cycle
110
+ done.add(node)
111
+ return None
112
+
113
+ for node in sorted(graph):
114
+ cycle = visit(node, [])
115
+ if cycle:
116
+ return cycle
117
+ return None
118
+
119
+
120
+ def _check_branches(script: ScriptDirectory) -> None:
121
+ """Reject projects whose branches cannot be shown and upgraded independently."""
122
+ depends: dict[str, set[str]] = {}
123
+ for revision in script.walk_revisions():
124
+ label = _branch_label(revision)
125
+ for parent_id in _parent_ids(revision):
126
+ parent_label = _branch_label(script.get_revision(parent_id))
127
+ if parent_label != label:
128
+ depends.setdefault(label, set()).add(parent_label)
129
+ cycle = _find_cycle(depends)
130
+ if cycle:
131
+ raise ValueError(
132
+ "Branches depend on each other in a loop ({}). Loops between branches are not "
133
+ "supported, see the README.".format(" -> ".join(cycle))
134
+ )
135
+
136
+
137
+ class _StatusRenderer:
138
+ def __init__(
139
+ self,
140
+ script: ScriptDirectory,
141
+ bases: dict[str, Script],
142
+ applied: set[Script],
143
+ style: Style,
144
+ show_dependencies: bool,
145
+ ) -> None:
146
+ self.script = script
147
+ self.bases = bases
148
+ self.applied = applied
149
+ self.style = style
150
+ self.show_dependencies = show_dependencies
151
+
152
+ def revision_line(
153
+ self,
154
+ lines: list[str],
155
+ prefix: str,
156
+ revision: Script,
157
+ show_branch_label: bool = False,
158
+ ) -> None:
159
+ branch_label = _branch_label(revision)
160
+ branch_base = self.bases[branch_label]
161
+ if branch_base in self.applied:
162
+ fg = "white" if revision in self.applied else "red"
163
+ else:
164
+ fg = None
165
+ branch_display = f"({branch_label}) " if show_branch_label else ""
166
+ lines.append(
167
+ self.style(f"{prefix}{branch_display}{revision.revision} {revision.doc}", fg=fg)
168
+ )
169
+ if self.show_dependencies and revision.dependencies:
170
+ deps = (
171
+ [revision.dependencies]
172
+ if isinstance(revision.dependencies, str)
173
+ else list(revision.dependencies)
174
+ )
175
+ for i, dep in enumerate(deps):
176
+ symbol = box_drawing(
177
+ up=True, down=i < len(deps) - 1, left=False, right=True, bold=False
178
+ )
179
+ self.revision_line(
180
+ lines,
181
+ " " * len(prefix) + symbol + " ",
182
+ self.script.get_revision(dep),
183
+ show_branch_label=True,
184
+ )
185
+
186
+
187
+ def get_status(
188
+ config: Config,
189
+ connection: Connection,
190
+ *,
191
+ branches: Iterable[str] = (),
192
+ show_dependencies: bool = False,
193
+ style: Style = _no_style,
194
+ ) -> StatusReport:
195
+ """Render all revisions grouped by branch, marking the ones applied in the database."""
196
+ script = ScriptDirectory.from_config(config)
197
+ _check_branches(script)
198
+ migration_context = MigrationContext.configure(connection)
199
+ current_heads = migration_context.get_current_heads()
200
+ applied = set(script.iterate_revisions(current_heads, "base"))
201
+
202
+ bases: dict[str, Script] = {}
203
+ for base in sorted((script.get_revision(b) for b in script.get_bases()), key=_branch_label):
204
+ bases[_branch_label(base)] = base
205
+
206
+ renderer = _StatusRenderer(script, bases, applied, style, show_dependencies)
207
+ branches = tuple(branches)
208
+ blocks: list[str] = []
209
+ outdated = False
210
+ for branch_label, branch_base in bases.items():
211
+ if branches and branch_label not in branches:
212
+ continue
213
+ branch_applied = branch_base in applied
214
+ branch_outdated = False
215
+ lines: list[str] = []
216
+ levels: defaultdict[Script, set[int]] = defaultdict(set)
217
+ seen: set[Script] = set()
218
+ todo: deque[Script] = deque([branch_base])
219
+ while todo:
220
+ rev = todo.pop()
221
+
222
+ down_levels = levels[rev]
223
+ if rev.is_merge_point:
224
+ down_ids = rev.down_revision
225
+ elif rev.down_revision:
226
+ down_ids = [rev.down_revision]
227
+ else:
228
+ down_ids = []
229
+ down_revisions = [script.get_revision(r) for r in down_ids]
230
+ next_revisions = [script.get_revision(r) for r in sorted(rev.nextrev)]
231
+
232
+ if rev.is_merge_point and (not seen.issuperset(down_revisions) or rev in todo):
233
+ continue
234
+ seen.add(rev)
235
+
236
+ next_levels = set()
237
+ for j, nextrev in enumerate(next_revisions):
238
+ if j == 0:
239
+ next_level = min(down_levels) if down_levels else 0
240
+ else:
241
+ next_level = max(chain(*(levels[r] for r in todo))) + 1
242
+ levels[nextrev].add(next_level)
243
+ next_levels.add(next_level)
244
+ todo.append(nextrev)
245
+
246
+ all_levels = list(chain(down_levels, next_levels))
247
+ min_level = min(all_levels, default=0)
248
+ max_level = max(all_levels, default=0)
249
+ symbol = "".join(
250
+ " "
251
+ if i < min_level
252
+ else box_drawing(
253
+ up=i in down_levels,
254
+ down=i in next_levels,
255
+ left=i > min_level,
256
+ right=i < max_level,
257
+ )
258
+ for i in range(max_level + 1)
259
+ )
260
+
261
+ check = "x" if rev in applied else " "
262
+ if branch_applied and rev not in applied:
263
+ outdated = True
264
+ branch_outdated = True
265
+ renderer.revision_line(lines, f" [{check}] {symbol} ", rev)
266
+
267
+ if branch_applied:
268
+ fg = "white"
269
+ mark = " " + (style("×", fg="red") if branch_outdated else style("✓", fg="green"))
270
+ else:
271
+ fg = None
272
+ mark = ""
273
+ header = style(f"[{branch_label}", bold=True, fg=fg) + mark + style("]", bold=True, fg=fg)
274
+ blocks.append("\n".join([header, *lines]))
275
+
276
+ text = "\n".join(blocks)
277
+ if outdated:
278
+ text += "\n" + style(OUTDATED_MESSAGE, fg="red")
279
+ return StatusReport(text=text, outdated=outdated)
280
+
281
+
282
+ def autoupgrade(
283
+ config: Config,
284
+ connection: Connection,
285
+ *,
286
+ sql: bool = False,
287
+ tag: str | None = None,
288
+ x_args: Iterable[str] = (),
289
+ ) -> list[str]:
290
+ """Upgrade every started branch that has revisions not applied yet.
291
+
292
+ A branch is started when its base is applied. A branch can fork, so each of its heads that
293
+ is not applied is upgraded in turn. Returns the upgraded heads in upgrade order.
294
+ """
295
+ set_x_args(config, x_args)
296
+ script = ScriptDirectory.from_config(config)
297
+ _check_branches(script)
298
+ current_heads = MigrationContext.configure(connection).get_current_heads()
299
+ applied = set(script.iterate_revisions(current_heads, "base"))
300
+ targets = _outdated_targets(script, applied)
301
+ for target in targets:
302
+ command.upgrade(config, target, sql=sql, tag=tag)
303
+ return targets
304
+
305
+
306
+ def _outdated_targets(script: ScriptDirectory, applied: set[Script]) -> list[str]:
307
+ bases: dict[str, Script] = {}
308
+ for base_id in script.get_bases():
309
+ base = script.get_revision(base_id)
310
+ bases[_branch_label(base)] = base
311
+ heads: dict[str, list[str]] = defaultdict(list)
312
+ for head_id in script.get_heads():
313
+ heads[_branch_label(script.get_revision(head_id))].append(head_id)
314
+ revisions: dict[str, set[Script]] = defaultdict(set)
315
+ for revision in script.walk_revisions():
316
+ revisions[_branch_label(revision)].add(revision)
317
+
318
+ targets = []
319
+ for label in sorted(bases):
320
+ started = bases[label] in applied
321
+ if started and not revisions[label] <= applied:
322
+ targets.extend(
323
+ head_id
324
+ for head_id in sorted(heads[label])
325
+ if script.get_revision(head_id) not in applied
326
+ )
327
+ return targets
@@ -0,0 +1,74 @@
1
+ """Optional Flask-Migrate integration: adds ``status`` and ``autoupgrade`` to ``flask db``.
2
+
3
+ Requires the ``flask`` extra. Call :func:`register_commands` once, for example in the
4
+ application factory or the module that defines the Flask CLI.
5
+ """
6
+
7
+ import click
8
+ from flask import current_app
9
+ from flask.cli import with_appcontext
10
+ from flask_migrate.cli import db as db_cli
11
+
12
+ from alembic_status.core import autoupgrade as run_autoupgrade
13
+ from alembic_status.core import get_status
14
+
15
+
16
+ @click.command("status")
17
+ @click.option(
18
+ "-d",
19
+ "--directory",
20
+ default=None,
21
+ help='Migration script directory (default is "migrations")',
22
+ )
23
+ @click.option(
24
+ "--deps", "--dependencies", "show_dependencies", is_flag=True, help="Show dependencies"
25
+ )
26
+ @click.argument("branches", nargs=-1)
27
+ @with_appcontext
28
+ def status_command(directory, show_dependencies, branches):
29
+ """Show all revisions sorted by branches."""
30
+ db = current_app.extensions["sqlalchemy"]
31
+ config = current_app.extensions["migrate"].migrate.get_config(directory)
32
+ report = get_status(
33
+ config,
34
+ db.session.connection(),
35
+ branches=branches,
36
+ show_dependencies=show_dependencies,
37
+ style=click.style,
38
+ )
39
+ click.echo(report.text)
40
+
41
+
42
+ @click.command("autoupgrade")
43
+ @click.option(
44
+ "-d",
45
+ "--directory",
46
+ default=None,
47
+ help='Migration script directory (default is "migrations")',
48
+ )
49
+ @click.option(
50
+ "--sql",
51
+ is_flag=True,
52
+ help="Don't emit SQL to database - dump to standard output instead",
53
+ )
54
+ @click.option(
55
+ "--tag",
56
+ default=None,
57
+ help='Arbitrary "tag" name - can be used by custom env.py scripts',
58
+ )
59
+ @click.option(
60
+ "-x", "--x-arg", multiple=True, help="Additional arguments consumed by custom env.py scripts"
61
+ )
62
+ @with_appcontext
63
+ def autoupgrade_command(directory, sql, tag, x_arg):
64
+ """Upgrade all branches to head."""
65
+ db = current_app.extensions["sqlalchemy"]
66
+ config = current_app.extensions["migrate"].migrate.get_config(directory)
67
+ run_autoupgrade(config, db.session.connection(), sql=sql, tag=tag, x_args=x_arg)
68
+
69
+
70
+ def register_commands(group: click.Group | None = None) -> None:
71
+ """Add ``status`` and ``autoupgrade`` to the ``flask db`` group, or to ``group``."""
72
+ target = db_cli if group is None else group
73
+ target.add_command(status_command)
74
+ target.add_command(autoupgrade_command)