pylembic 0.2.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.
pylembic/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """Package configuration"""
2
+
3
+ __author__ = "Marco Espinosa"
4
+ __email__ = "marco@marcoespinosa.com"
pylembic/cli.py ADDED
@@ -0,0 +1,46 @@
1
+ import typer
2
+
3
+ from pylembic.migrations import Validator
4
+
5
+ app = typer.Typer(
6
+ help="pylembic CLI for validating and visualizing Alembic migrations."
7
+ )
8
+
9
+
10
+ @app.command()
11
+ def main(
12
+ migrations_path: str = typer.Argument(..., help="Path to the migrations folder."),
13
+ validate: bool = typer.Option(False, "--validate", help="Validate the migrations."),
14
+ show_graph: bool = typer.Option(
15
+ False, "--show-graph", help="Visualize the migration dependency graph."
16
+ ),
17
+ verbose: bool = typer.Option(
18
+ False, "--verbose", help="Show migrations validation logs."
19
+ ),
20
+ ):
21
+ """
22
+ Main command to validate and/or visualize migrations.
23
+ """
24
+ typer.echo(f"Processing migrations in: {migrations_path}")
25
+ validator = Validator(migrations_path)
26
+
27
+ if verbose:
28
+ typer.echo("Verbose mode enabled.")
29
+
30
+ if validate:
31
+ typer.echo("Validating migrations...")
32
+ if validator.validate():
33
+ typer.secho("Migrations validation passed!", fg=typer.colors.GREEN)
34
+ else:
35
+ typer.secho("Migrations validation failed!", fg=typer.colors.RED)
36
+
37
+ if show_graph:
38
+ typer.echo("Visualizing migration graph...")
39
+ validator.show_graph()
40
+
41
+ if not validate and not show_graph:
42
+ typer.echo("No action specified. Use --help for more information.")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ app()
pylembic/exceptions.py ADDED
@@ -0,0 +1,8 @@
1
+ class CircularDependencyError(Exception):
2
+ """Raised when a circular dependency is detected in the migration graph.
3
+
4
+ Original exception is CommandError from Alembic util module. This exception
5
+ is created for readability.
6
+ """
7
+
8
+ pass
pylembic/formatter.py ADDED
@@ -0,0 +1,15 @@
1
+ from logging import Formatter
2
+
3
+
4
+ class CustomFormatter(Formatter):
5
+ """Custom formatter that handles missing fields gracefully."""
6
+
7
+ params = ["orphans", "dependency", "migration", "heads", "bases"]
8
+
9
+ def format(self, record):
10
+ """Format the log record with default values for missing fields."""
11
+ for param in self.params:
12
+ if not hasattr(record, param):
13
+ setattr(record, param, "")
14
+
15
+ return super().format(record)
pylembic/logger.py ADDED
@@ -0,0 +1,30 @@
1
+ import logging
2
+
3
+ from pylembic.formatter import CustomFormatter
4
+
5
+
6
+ def configure_logger(verbose: bool = False):
7
+ """Configure the logger with a custom formatter and verbosity level.
8
+
9
+ Args:
10
+ verbose (bool): Whether to enable verbose logging.
11
+
12
+ Returns:
13
+ logging.Logger: The configured logger.
14
+ """
15
+ logger = logging.getLogger()
16
+
17
+ if not verbose:
18
+ logger.setLevel(logging.CRITICAL + 1)
19
+ return logger
20
+
21
+ logger.setLevel(logging.INFO)
22
+ handler = logging.StreamHandler()
23
+ formatter = CustomFormatter(
24
+ "%(levelname)s\t %(asctime)s | %(message)s | %(migration)s"
25
+ "%(dependency)s%(orphans)s%(heads)s%(bases)s",
26
+ datefmt="%d %b %Y | %H:%M:%S",
27
+ )
28
+ handler.setFormatter(formatter)
29
+ logger.addHandler(handler)
30
+ return logger
pylembic/migrations.py ADDED
@@ -0,0 +1,152 @@
1
+ import os
2
+
3
+ import matplotlib.pyplot as plt
4
+ import networkx as nx
5
+ from alembic.config import Config
6
+ from alembic.script import ScriptDirectory
7
+ from alembic.util import CommandError
8
+
9
+ from pylembic.exceptions import CircularDependencyError
10
+ from pylembic.logger import configure_logger
11
+
12
+
13
+ logger = configure_logger()
14
+
15
+
16
+ class Validator:
17
+ """This class provides methods to validate Alembic migrations for linearity,
18
+ missing nodes, and circular dependencies.
19
+
20
+ Here is a summary of the checks performed:
21
+ - Linearity: Ensures a clean and predictable migration chain.
22
+ - Circular dependencies: Prevents migration failures due to loops in the
23
+ dependency chain.
24
+ - Disconnected roots: Identifies migrations improperly created without linking
25
+ to the base.
26
+ - Disconnected leaves: Flags migrations that are improperly disconnected from
27
+ subsequent migrations.
28
+ - Multiple roots/heads: Warns about unintentional forks or branching.
29
+ - Graph visualization: Provides a visual way to catch anomalies and understand
30
+ migration flow.
31
+ """
32
+
33
+ ALEMBIC_CONFIG_FILE = "alembic.ini"
34
+
35
+ def __init__(
36
+ self, alembic_config_path: str, alembic_config_file: str = None
37
+ ) -> None:
38
+ if not os.path.exists(alembic_config_path):
39
+ raise FileNotFoundError(f"Path '{alembic_config_path}' does not exist!")
40
+
41
+ self.alembic_config_path = alembic_config_path
42
+ self.alembic_config_file = alembic_config_file or self.ALEMBIC_CONFIG_FILE
43
+ self.graph = nx.DiGraph()
44
+ self.verbose = False
45
+ self.script: ScriptDirectory = None
46
+
47
+ # Load the Alembic configuration
48
+ self._load_alembic_config()
49
+
50
+ # Build the migration graph
51
+ self._build_graph()
52
+
53
+ def _load_alembic_config(self) -> None:
54
+ """Loads the Alembic configuration file and initializes the script directory."""
55
+ alembic_config = Config(
56
+ os.path.join(self.alembic_config_path, self.alembic_config_file)
57
+ )
58
+ alembic_config.set_main_option("script_location", self.alembic_config_path)
59
+ self.script = ScriptDirectory.from_config(alembic_config)
60
+
61
+ def _build_graph(self) -> None:
62
+ """Builds a directed graph of migrations."""
63
+ graph = nx.DiGraph()
64
+ try:
65
+ for revision in self.script.walk_revisions():
66
+ graph.add_node(revision.revision)
67
+ if revision.down_revision:
68
+ if isinstance(revision.down_revision, tuple):
69
+ # Handle branching migrations
70
+ for down_rev in revision.down_revision:
71
+ graph.add_edge(revision.revision, down_rev)
72
+ else:
73
+ graph.add_edge(revision.revision, revision.down_revision)
74
+ except CommandError as exc:
75
+ raise CircularDependencyError(str(exc)) from exc
76
+
77
+ self.graph = graph
78
+
79
+ def _orphans(self) -> bool:
80
+ """
81
+ Checks for orphan migrations in the Alembic script directory.
82
+ As the orphan migrations are not connected to the migration graph, they are
83
+ considered as a valid base and head.
84
+
85
+ Returns:
86
+ bool: True if orphan migrations are found.
87
+ """
88
+ bases = set(self.script.get_bases())
89
+ heads = set(self.script.get_heads())
90
+ orphans = bases.intersection(heads)
91
+ if orphans:
92
+ logger.warning("Orphan migrations detected.", extra={"orphans": orphans})
93
+ return True
94
+
95
+ logger.info("No orphan migrations detected.")
96
+ return False
97
+
98
+ def _multiple_bases_or_heads(self) -> bool:
99
+ """
100
+ Checks if there are multiple bases or heads in the migration graph.
101
+
102
+ Returns:
103
+ bool: True if multiple bases or heads are found.
104
+ """
105
+ bases = set(self.script.get_bases())
106
+ if len(bases) > 1:
107
+ logger.info("Multiple bases detected", extra={"bases": bases})
108
+ return True
109
+
110
+ heads = set(self.script.get_heads())
111
+ if len(heads) > 1:
112
+ logger.info("Multiple heads detected", extra={"heads": heads})
113
+ return True
114
+
115
+ return False
116
+
117
+ def validate(self, verbose: bool = False) -> bool:
118
+ """This method validates the Alembic migrations for linearity and missing nodes.
119
+
120
+ Args:
121
+ verbose (bool): If True, the logger verbosity is increased.
122
+
123
+ Returns:
124
+ bool: True if the migrations are valid.
125
+ """
126
+ # Reconfigure the logger verbosity
127
+ logger = configure_logger(verbose) # noqa F841
128
+
129
+ # Perform validation checks within the graph
130
+ return not (self._orphans() or self._multiple_bases_or_heads())
131
+
132
+ def show_graph(self) -> None:
133
+ """
134
+ Visualizes the migration dependency graph.
135
+ """
136
+ plt.figure(figsize=(12, 8))
137
+ pos = nx.spring_layout(self.graph)
138
+ labels = {node: f"{node[:8]}" for node in self.graph.nodes} # Short revision ID
139
+ nx.draw(
140
+ self.graph,
141
+ pos,
142
+ labels=labels,
143
+ node_size=3000,
144
+ node_color="lightblue",
145
+ font_size=10,
146
+ font_weight="bold",
147
+ label="Alembic Migration Graph",
148
+ )
149
+ # Set the custom window title
150
+ manager = plt.get_current_fig_manager()
151
+ manager.set_window_title("Alembic Migration Dependency Graph")
152
+ plt.show()
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.4
2
+ Name: pylembic
3
+ Version: 0.2.0
4
+ Summary: This package provides validation for Alembic migrations.
5
+ Author-email: Marco Espinosa <marco@marcoespinosa.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 Marco Espinosa
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ License-File: LICENSE
28
+ Requires-Python: >=3.11
29
+ Requires-Dist: alembic>=1.14.0
30
+ Requires-Dist: matplotlib>=3.10.0
31
+ Requires-Dist: networkx>=3.4.2
32
+ Requires-Dist: typer>=0.15.1
33
+ Description-Content-Type: text/markdown
34
+
35
+ <!-- Shields -->
36
+ <p align="center">
37
+ <a href="https://github.com/maekind/pylembic"><img src="https://img.shields.io/github/actions/workflow/status/maekind/pylembic/.github%2Fworkflows%2Ftesting.yml?label=tests&color=green" hspace="5"></a>
38
+ <a href="https://codecov.io/gh/maekind/pylembic"><img src="https://codecov.io/gh/maekind/pylembic/graph/badge.svg?token=JcGna50uJL" hspace="5"/>
39
+ </a>
40
+ <a href="https://github.com/maekind/pylembic/releases"><img src="https://img.shields.io/github/actions/workflow/status/maekind/pylembic/.github%2Fworkflows%2Frelease.yml?label=package&color=green" hspace="5"></a>
41
+ <a href="https://pypi.org/project/pylembic"><img src="https://img.shields.io/github/v/release/maekind/pylembic?color=blue&label=pypi latest" hspace="5"></a>
42
+ <br>
43
+ <a href="https://github.com/maekind/kairo/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-orange.svg" hspace="5"></a>
44
+ <a href="https://github.com/maekind/kairo"><img src="https://img.shields.io/github/repo-size/maekind/pylembic?color=red" hspace="5"></a>
45
+ <a href="https://github.com/maekind/pylembic"><img src="https://img.shields.io/github/last-commit/maekind/pylembic?color=black" hspace="5"></a>
46
+ <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/github/languages/top/maekind/pylembic?color=darkgreen" hspace="5"></a>
47
+ <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python%20version-%3E3.11-lightblue" hspace="5"></a>
48
+ </p>
49
+
50
+ # pylembic
51
+
52
+ ## Description
53
+
54
+ This package provides validation of Alembic migrations for Python projects.
55
+
56
+ It will check:
57
+
58
+ - Linearity: Ensures a clean and predictable migration chain.
59
+ - Circular dependencies: Prevents migration failures due to loops in the
60
+ dependency chain.
61
+ - Orphan migrations: Identifies migrations improperly created without linking
62
+ to any other migration.
63
+ - Multiple bases/heads: Identifies multiple bases or heads in the migration graph.
64
+ - Graph visualization: Provides a visual way to catch anomalies and understand the
65
+ migration flow.
66
+
67
+ ## Installation
68
+
69
+ You can install this package using pip:
70
+
71
+ ```bash
72
+ pip install pylembic
73
+ ```
74
+
75
+ ## Usage
76
+
77
+ ### Testing
78
+
79
+ You can use this module with your preferred testing framework as follows:
80
+
81
+ ```python
82
+ from os import path
83
+
84
+ from pytest import fixture
85
+
86
+ from pylembic.migrations import Validator
87
+
88
+
89
+ @fixture
90
+ def with_alembic_config_path():
91
+ # We assume the migrations folder is at the root of the project,
92
+ # and this test file is in the tests folder, also at the root of the project.
93
+ # TODO: Feel free to adjust the path to your project's migrations folder.
94
+ return path.abspath(
95
+ path.join(path.dirname(path.dirname(__file__)), "migrations")
96
+ )
97
+
98
+
99
+ def test_migrations(with_alembic_config_path):
100
+ migration_validator = Validator(with_alembic_config_path)
101
+ assert migration_validator.validate()
102
+ ```
103
+
104
+ ### Visualizing the migration graph
105
+
106
+ You can show the migrations graph by calling the method `show_graph`:
107
+
108
+ ```python
109
+
110
+ from os import path
111
+
112
+ from pylembic.migrations import Validator
113
+
114
+ alembic_config_path = path.abspath(path.join("your path", "migrations"))
115
+
116
+ migration_validator = Validator(alembic_config_path)
117
+
118
+ migration_validator.show_graph()
119
+ ```
120
+
121
+ ### Command line
122
+
123
+ You can also use the command line for:
124
+
125
+ - Validating migrations:
126
+
127
+ ```bash
128
+ pylembic ./path/to/migrations --validate
129
+ ```
130
+
131
+ - Visualizing the migration graph:
132
+
133
+ ```bash
134
+ pylembic ./path/to/migrations --show-graph
135
+ ```
136
+
137
+ (c) 2024, <a href="mailto:marco@marcoespinosa.com">Marco Espinosa</a>
@@ -0,0 +1,11 @@
1
+ pylembic/__init__.py,sha256=mxZWJyh9P5VqsH8lnghUoFt9VTuP869lvvcujmIGadI,97
2
+ pylembic/cli.py,sha256=Fg4hX7sB9Y8VKRm2zfduO40r5fpVCYfY9nNWzitcZcE,1363
3
+ pylembic/exceptions.py,sha256=-By4dH3X9z4Pyyg-pQCzNBsAvq5piu3KwyoMT2AUQcA,250
4
+ pylembic/formatter.py,sha256=6WJfPrO7UXj3rJTIeLlGRI3sJJFScgh0U_fStS3JY9A,470
5
+ pylembic/logger.py,sha256=x3MIP-mKc7nGSQiVri2ZhoTjw857pHGOd8Fi7vNbItI,803
6
+ pylembic/migrations.py,sha256=_VWBKMxS_5fWn4SDJsiRroE2Z7Vufp6BoLcscQ0wvZs,5471
7
+ pylembic-0.2.0.dist-info/METADATA,sha256=LzcVlqiSK6cKGdPLA73RJ2lJ2EBwv1sETzM5pTlIdqE,5153
8
+ pylembic-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ pylembic-0.2.0.dist-info/entry_points.txt,sha256=Ta6Ra5zsE9KGAfvAbRMdvceIgqQ09b_FWh6UDhAqF34,46
10
+ pylembic-0.2.0.dist-info/licenses/LICENSE,sha256=tN1cVPGIuSLIoeLQZ3LJFMdEAFQ1BluFCO8kvCGQKlA,1070
11
+ pylembic-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pylembic = pylembic.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Marco Espinosa
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.