### Install django-migration-linter Source: https://github.com/3yourmind/django-migration-linter/blob/main/README.md Install the package using pip. ```bash pip install django-migration-linter ``` -------------------------------- ### split_path() usage examples Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/utils.md Examples showing how paths are split into lists of strings. ```python split_path("/a/b/migrations/0001.py") # ['/', 'a', 'b', 'migrations', '0001.py'] split_path("a/b/c.py") # ['a', 'b', 'c.py'] ``` -------------------------------- ### Config file format example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md Example of the INI configuration format used by the linter. ```ini [django_migration_linter] no_cache = True exclude_apps = users ``` -------------------------------- ### pyproject.toml configuration example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md Example of the TOML configuration format used within pyproject.toml. ```toml [tool.django_migration_linter] git_commit_id = "main" ``` -------------------------------- ### MIGRATION_LINTER_OPTIONS example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md Example of the MIGRATION_LINTER_OPTIONS dictionary structure in Django settings. ```python MIGRATION_LINTER_OPTIONS = { "no_cache": True, "exclude_apps": ["users"], } ``` -------------------------------- ### Using analyse_sql_statements Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/sql-analyser-analyser.md Example of running the analysis pipeline with a specific analyser class and SQL statements. ```python from django_migration_linter.sql_analyser import ( MySqlAnalyser, analyse_sql_statements, ) errors, ignored, warnings = analyse_sql_statements( MySqlAnalyser, [ "ALTER TABLE `orders` ADD CONSTRAINT uq UNIQUE (`email`);", "DROP TABLE `legacy`;", ], exclude_migration_tests=["ADD_UNIQUE"], ) for issue in errors: print(issue.code, issue.message, issue.table) # DROP_TABLE ... ``` -------------------------------- ### get_migration_abspath() usage example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/utils.md Demonstrates resolving a migration path and safely opening the file. ```python from django_migration_linter.utils import get_migration_abspath path = get_migration_abspath("shop", "0002_auto") try: with open(path, "rb") as fh: content = fh.read() except (OSError, ValueError) as exc: ... ``` -------------------------------- ### analyse_data_migration usage example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter-data-migrations.md Example of calling analyse_data_migration and processing the returned lists of issues. ```python errors, ignored, warnings = linter.analyse_data_migration(migration) print(f"{len(errors)} errors, {len(warnings)} warnings") ``` -------------------------------- ### Initialize MigrationLinter with constructor options Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/configuration.md Example of instantiating the MigrationLinter class with various configuration parameters such as path, database, and migration filtering rules. ```python from django_migration_linter import MigrationLinter linter = MigrationLinter( path=".", database="replica", ignore_name_contains="squash", exclude_migration_tests=["ALTER_COLUMN", "ADD_UNIQUE"], quiet=["ok", "ignore"], no_cache=True, ) ``` -------------------------------- ### Cache Usage Example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/cache.md Demonstrates initializing the cache, loading data, performing lookups by migration hash, updating entries, and saving the cache to disk. ```python from django_migration_linter.cache import Cache cache = Cache("/srv/myapp", "default", "/tmp/lint-cache") cache.load() if "9bb9f8..." in cache: # migration-file MD5 print(cache["9bb9f8..."]) # {'result': 'OK'} cache["9bb9f8..."] = {"result": "OK"} cache.save() ``` -------------------------------- ### Using get_sql_analyser_class Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/sql-analyser-analyser.md Examples of retrieving an analyser class by database vendor string or by explicit analyser name. ```python from django_migration_linter.sql_analyser import get_sql_analyser_class cls = get_sql_analyser_class("django.db.backends.sqlite3") # SqliteAnalyser cls = get_sql_analyser_class("anything", analyser_string="mysql") # MySqlAnalyser ``` -------------------------------- ### Example RunPython migration operation Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter-data-migrations.md An example of a RunPython operation that triggers the RUNPYTHON_ARGS_NAMING_CONVENTION warning. ```python class Migration(migrations.Migration): operations = [ migrations.RunPython(forwards, backwards) # missing apps, schema_editor args ] ``` -------------------------------- ### MigrationLinter with options and error handling Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Advanced example showing MigrationLinter instantiation with various options (exclude_apps, ignore_name_contains, only_unapplied_migrations, exclude_migration_tests, warnings_as_errors_tests, no_cache) and handling of MigrationLinterException. ```APIDOC ## MigrationLinter with options and error handling ### Description Advanced example showing MigrationLinter instantiation with various options (exclude_apps, ignore_name_contains, only_unapplied_migrations, exclude_migration_tests, warnings_as_errors_tests, no_cache) and handling of MigrationLinterException. ### Code Example ```python from django_migration_linter import MigrationLinter linter = MigrationLinter( path="/path/to/my/project", exclude_apps=["legacy"], ignore_name_contains="squash", only_unapplied_migrations=True, exclude_migration_tests=["ALTER_COLUMN"], warnings_as_errors_tests=["CREATE_INDEX"], no_cache=True, ) try: linter.lint_all_migrations(git_commit_id="HEAD~10") except MigrationLinterException as exc: # e.g. git diff failed print(f"Linting aborted: {exc}") ``` ``` -------------------------------- ### MigrationLinter basic usage Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Basic example showing how to instantiate MigrationLinter, lint all migrations, print a summary, and exit with an error code if any linting errors are found. ```APIDOC ## MigrationLinter basic usage ### Description Basic example showing how to instantiate MigrationLinter, lint all migrations, print a summary, and exit with an error code if any linting errors are found. ### Code Example ```python from django_migration_linter import MigrationLinter linter = MigrationLinter(path="/path/to/my/project") linter.lint_all_migrations() linter.print_summary() if linter.has_errors: raise SystemExit(1) ``` ``` -------------------------------- ### RunSQL operation example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter-data-migrations.md Example of a RunSQL operation that triggers a RUNSQL_REVERSIBLE warning. ```python from django.db import migrations operations = [ migrations.RunSQL( sql=[("UPDATE t SET x = %s WHERE y = 1", ("val",))], reverse_sql=migrations.RunSQL.noop, # -> RUNSQL_REVERSIBLE warning ) ] ``` -------------------------------- ### Run lintmigrations via CLI Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md Examples of executing the lintmigrations command with various arguments and flags to control scope, git references, and output. ```bash python manage.py lintmigrations python manage.py lintmigrations shop 0002_auto python manage.py lintmigrations --git-commit-id origin/main --no-cache python manage.py lintmigrations --include-apps shop billing --exclude-migration-tests ALTER_COLUMN python manage.py lintmigrations -q ok ignore ``` -------------------------------- ### Cache.__init__ Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/cache.md Initializes a Cache instance with the given Django folder, database alias, and cache path. Creates the cache directory if missing and starts with an empty dict. ```APIDOC ## Cache.__init__ ### Description Initializes a Cache instance. Sets the filename to `/_.pickle`, creates the directory if missing, and initializes the dict as empty. ### Method Constructor ### Signature ```python def __init__(self, django_folder: str | None, database: str, cache_path: str): ``` ### Parameters - **django_folder** (str | None) - Required - Django project path; `os.sep` replaced with `_` to form the file name slug. - **database** (str) - Required - Database alias, appended to the file name. - **cache_path** (str) - Required - Directory where the pickle file is stored. ### Behavior Sets `self.filename = os.path.join(cache_path, "_.pickle")`, creates the directory if missing (`os.makedirs` on `os.path.dirname(self.filename)`), then calls `super().__init__()` — the cache starts empty; content is populated via `load()` or direct item assignment. ``` -------------------------------- ### Usage of get_runpython_model_import_issues Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter-data-migrations.md Example showing how to iterate over issues returned by the model import linter. ```python for issue in MigrationLinter.get_runpython_model_import_issues(migration_func): print(issue.code, issue.message) ``` -------------------------------- ### Excluding migration tests in lint_runpython Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter-data-migrations.md Example of initializing MigrationLinter with excluded tests and running lint_runpython. ```python linter = MigrationLinter(exclude_migration_tests=["RUNPYTHON_REVERSIBLE"]) errors, ignored, warnings = linter.lint_runpython(op) # warnings == [] (reversible warning downgraded to ignored) ``` -------------------------------- ### Catching MigrationLinterException Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/errors.md Example of how to wrap lint_all_migrations to catch and handle MigrationLinterException when running the linter programmatically. ```python from django_migration_linter import MigrationLinter from django_migration_linter.exceptions import MigrationLinterException linter = MigrationLinter(path="/path/to/project") try: linter.lint_all_migrations(git_commit_id="HEAD~5") except MigrationLinterException as exc: print(str(exc)) # "Error while executing git diff command" ``` -------------------------------- ### split_migration_path() usage example Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/utils.md Extracts the app label and migration name from a full migration file path. ```python split_migration_path("tests/test_project/app_a/migrations/0002_b.py") # ('app_a', '0002_b') ``` -------------------------------- ### Handling lint_runsql exceptions Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter-data-migrations.md Example of catching ValueError exceptions that may occur during RunSQL linting due to malformed tuples. ```python try: errors, ignored, warnings = linter.lint_runsql(op) except ValueError as exc: # malformed (sql, params) tuples logger.error("Malformed RunSQL: %s", exc) ``` -------------------------------- ### Interactive linting session Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/makemigrations-command.md Example of an interactive session where the linter identifies an error and prompts the user to keep or delete the migration file. ```text $ python manage.py makemigrations --lint Linting for 'app_correct': (app_correct, 0003_a_column)... ERR NOT NULL constraint on columns Do you want to keep the migration? [y/N] n Deleted tests/test_project/app_correct/migrations/0003_a_column.py ``` -------------------------------- ### Run lintmigrations via call_command Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md Example of invoking the lintmigrations command programmatically using Django's call_command. Note that it raises SystemExit when errors are detected. ```python from django.core.management import call_command try: call_command("lintmigrations", git_commit_id="HEAD~1", verbosity=0) except SystemExit as exc: # SystemExit(1) when errors were found if exc.code != 0: handle_failure() ``` -------------------------------- ### lintmigrations Command Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md The primary CLI entry point for django-migration-linter. Installed as a Django management command and can be used programmatically via the Command class. ```APIDOC ## Command: lintmigrations ### Description Lint your Django migrations for potential issues. This command is the primary CLI entry point for django-migration-linter. ### Usage Run as a Django management command: `python manage.py lintmigrations` ### Programmatic Import ```python from django_migration_linter.management.commands.lintmigrations import Command ``` ### Module Constants - `CONFIG_NAME` (string) - Section name in config files and key in `[tool]` of `pyproject.toml`. Value: `"django_migration_linter"` - `PYPROJECT_TOML` (string) - TOML config file name. Value: `"pyproject.toml"` - `DEFAULT_CONFIG_FILES` (tuple) - INI-style config files probed in order. Value: `(".django_migration_linter.cfg", "setup.cfg", "tox.ini")` ### Command Class Subclasses `django.core.management.base.BaseCommand`. #### Attributes - `help` (string) - "Lint your migrations" #### Methods - `add_arguments(self, parser: CommandParser) -> None` - Registers CLI arguments. - `handle(self, *args, **options)` - Entry point: merges config layers, builds a MigrationLinter, lints, prints summary, exits 1 on errors. - `read_django_settings(options: dict[str, Any]) -> dict[str, Any]` (static) - Reads `settings.MIGRATION_LINTER_OPTIONS` keys matching CLI option names. - `read_config_file(options: dict[str, Any]) -> dict[str, Any]` (static) - Reads `[django_migration_linter]` from INI config files. - `read_toml_file(options: dict[str, Any]) -> dict[str, Any]` (static) - Reads `[tool.django_migration_linter]` from `pyproject.toml`. - `get_version(self) -> str` - Returns `__version__` ("6.0.0"). ### Option Precedence For each option name, the first non-falsy value wins in this order: 1. CLI arguments (argparse values already present in `options`) 2. `MIGRATION_LINTER_OPTIONS` from Django settings 3. `[django_migration_linter]` from `.django_migration_linter.cfg` / `setup.cfg` / `tox.ini` 4. `[tool.django_migration_linter]` from `pyproject.toml` Dashes in CLI options map to underscores in config files (e.g., `--git-commit-id` → `git_commit_id`). Boolean options are parsed with `config_parser.getboolean`; `--warnings-as-errors` is post-processed by `extract_warnings_as_errors_option`. ### CLI Arguments #### Positional Arguments - `app_label` (optional) - App label of an application to lint migrations. - `migration_name` (optional) - Linting will only be done on that migration only. #### Options - `--git-commit-id` - Only migrations since this commit are considered. - `--ignore-name-contains` - Ignore migrations containing this name. - `--ignore-name` (nargs `*`) - Ignore migrations with exactly one of these names. - `--include-name-contains` - Only consider migrations containing this name. - `--include-name` (nargs `*`) - Only consider migrations with exactly one of these names. - `--project-root-path` - Django project root path (defaults to the directory of `DJANGO_SETTINGS_MODULE`). - `--include-migrations-from FILE_PATH` - Only migrations listed in the file are considered. - `--cache-path` / `--no-cache` - Mutually exclusive group: cache directory vs. disable cache. - `--include-apps` / `--exclude-apps` - Mutually exclusive group: restrict/ignore apps (nargs `*`). - `--unapplied-migrations` / `--applied-migrations` - Mutually exclusive group: only unapplied/applied migrations. - `-q` / `--quiet` - `nargs="+"`, `choices=MessageType.values()` (`ok`, `ignore`, `warning`, `error`); suppresses output of those result types. - `--database`, `--exclude-migration-tests`, `--warnings-as-errors`, `--sql-analyser`, `--ignore-sqlmigrate-errors`, `--ignore-initial-migrations` - Shared linting options from `register_linting_configuration_options`. Standard Django options (`--verbosity`, etc.) are inherited from `BaseCommand`; `verbosity == 0` sets `no_output=True` and `verbosity > 1` enables DEBUG logging. ``` -------------------------------- ### Get migration hash static method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Computes the MD5 hex digest of a migration file's contents. ```python @staticmethod def get_migration_hash(app_label: str, migration_name: str) -> str: ``` -------------------------------- ### Usage example: IgnoreMigration in a Django migration Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/ignore-migration.md Demonstrates using linter.IgnoreMigration() as the first operation in a migration to ignore the entire migration, preventing the linter from flagging the subsequent RemoveField operation. ```python from django.db import migrations import django_migration_linter as linter class Migration(migrations.Migration): dependencies = [ ("myapp", "0001_initial"), ] operations = [ linter.IgnoreMigration(), migrations.RemoveField( model_name="order", name="legacy_column", ), ] ``` -------------------------------- ### Advanced Migration Linter configuration and error handling Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Demonstrates using non-trivial options like excluding apps, ignoring specific migration names, and handling exceptions during the linting process. ```python from django_migration_linter import MigrationLinter linter = MigrationLinter( path="/path/to/my/project", exclude_apps=["legacy"], ignore_name_contains="squash", only_unapplied_migrations=True, exclude_migration_tests=["ALTER_COLUMN"], warnings_as_errors_tests=["CREATE_INDEX"], no_cache=True, ) try: linter.lint_all_migrations(git_commit_id="HEAD~10") except MigrationLinterException as exc: # e.g. git diff failed print(f"Linting aborted: {exc}") ``` -------------------------------- ### Lint entire codebase Source: https://github.com/3yourmind/django-migration-linter/blob/main/docs/usage.md Run the linter on all migrations in the project. ```bash python manage.py lintmigrations ``` -------------------------------- ### Importing SQL analyser utilities Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/sql-analyser-analyser.md Standard import path for the primary analyser functions. ```python from django_migration_linter.sql_analyser import ( analyse_sql_statements, get_sql_analyser_class, ) ``` -------------------------------- ### Cache load() method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/cache.md Loads the pickle file into the dictionary. OSError exceptions are silently swallowed, resulting in an empty cache. ```python def load(self) -> None: ``` -------------------------------- ### MigrationLinter with quiet parameter Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/message-type.md Example showing how to use MessageType values with the MigrationLinter's quiet parameter to suppress certain lint messages. ```APIDOC ## MigrationLinter with quiet parameter ### Description Example demonstrating how to use MessageType values with the MigrationLinter's quiet parameter to suppress "OK" and "IGNORE" lines while still printing errors and warnings. ### Example ```python from django_migration_linter import MigrationLinter, MessageType # Suppress "OK" and "IGNORE" lines; errors and warnings still print. linter = MigrationLinter( path=".", quiet=[MessageType.OK.value, MessageType.IGNORE.value], ) ``` ``` -------------------------------- ### Configure linter via INI files Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/configuration.md Use the [django_migration_linter] section in setup.cfg, tox.ini, or .django_migration_linter.cfg to specify options. ```ini # setup.cfg / tox.ini / .django_migration_linter.cfg [django_migration_linter] no_cache = True exclude_apps = users, legacy ignore_name_contains = datafix ``` -------------------------------- ### get_sql() method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Executes Django's sqlmigrate command and returns the SQL as a list of lines. Redirects stdout to os.devnull. ```python def get_sql(self, app_label: str, migration_name: str) -> list[str]: ``` -------------------------------- ### Configure MIGRATION_LINTER_OPTIONS Source: https://github.com/3yourmind/django-migration-linter/blob/main/README.md Optionally add configuration options for the linter. ```python MIGRATION_LINTER_OPTIONS = { ... } ``` -------------------------------- ### Publishing commands for PyPi Source: https://github.com/3yourmind/django-migration-linter/blob/main/docs/internals/publishing.md A sequence of commands to clean the build directory, upgrade build and twine tools, build the package, and upload the resulting distribution files to PyPi. ```bash rm -r django_migration_linter.egg-info/ dist/ pip install --upgrade build python -m build pip install --upgrade twine twine upload dist/django_migration_linter-X.Y.Z-py3-none-any.whl dist/django-migration-linter-X.Y.Z.tar.gz ``` -------------------------------- ### print_summary() method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Prints a summary of migration counts including valid, erroneous, warned, and ignored migrations. Returns without output if no_output is set. ```python def print_summary(self) -> None: ``` -------------------------------- ### Importing BaseAnalyser and utilities Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/sql-analyser-base.md Import the core classes and helper functions from the sql_analyser.base module. ```python from django_migration_linter.sql_analyser.base import ( BaseAnalyser, Check, CheckMode, CheckType, Issue, find_check_from_code, has_add_unique, has_not_null_column, update_migration_checks, ) ``` -------------------------------- ### get_sql(app_label, migration_name) Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Runs Django's sqlmigrate management command for the given migration and returns the SQL split into lines. Errors can bubble up as ValueError, ProgrammingError, or NotSupportedError. ```APIDOC ## get_sql(app_label, migration_name) ### Description Runs Django's `sqlmigrate` management command for `(app_label, migration_name)` on `self.database` with stdout redirected to `os.devnull`, and returns the SQL split into lines. Throws can bubble up as `ValueError`/`ProgrammingError`/`NotSupportedError` (handled by the caller in `lint_migration`). ### Method get_sql ### Parameters - **app_label** (str) - Required - The application label. - **migration_name** (str) - Required - The migration name. ### Response - **sql_lines** (list[str]) - The SQL statements split into lines. ``` -------------------------------- ### Command handle method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/makemigrations-command.md The handle method stores linting options and delegates the migration creation process to Django's base command. ```python def handle(self, *app_labels, **options): ``` -------------------------------- ### analyse_data_migration(migration) Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter-data-migrations.md Iterates over migration.operations and dispatches per type: RunPython to lint_runpython, RunSQL to lint_runsql, anything else to ([], [], []). Aggregates all three lists and returns them as a tuple of errors, ignored issues, and warnings. ```APIDOC ## analyse_data_migration(migration) ### Description Iterates over migration.operations and dispatches per type: RunPython to lint_runpython, RunSQL to lint_runsql, anything else to ([], [], []). Aggregates all three lists and returns them as a tuple of errors, ignored issues, and warnings. ### Method analyse_data_migration ### Signature ```python def analyse_data_migration( self, migration: Migration ) -> tuple[list[Issue], list[Issue], list[Issue]]: ``` ### Parameters - **migration** (Migration) - Required - The migration object to analyze. ### Returns - **tuple[list[Issue], list[Issue], list[Issue]]** - A tuple of (errors, ignored, warnings) where ignored means the issue code is listed in exclude_migration_tests. ### Example ```python errors, ignored, warnings = linter.analyse_data_migration(migration) print(f"{len(errors)} errors, {len(warnings)} warnings") ``` ``` -------------------------------- ### Configure INSTALLED_APPS Source: https://github.com/3yourmind/django-migration-linter/blob/main/README.md Add the migration linter to your Django project's INSTALLED_APPS setting. ```python INSTALLED_APPS = [ ..., "django_migration_linter", ..., ] ``` -------------------------------- ### Configure linter via pyproject.toml Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/configuration.md Use the [tool.django_migration_linter] table in pyproject.toml to specify configuration options. ```toml # pyproject.toml [tool.django_migration_linter] git_commit_id = "origin/main" exclude_migration_tests = ["ALTER_COLUMN"] ``` -------------------------------- ### Lint all migrations method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Main entry point for collecting and linting migrations. It supports filtering by app, specific migration, git commit, or a file path. ```python def lint_all_migrations( self, app_label: str | None = None, migration_name: str | None = None, git_commit_id: str | None = None, migrations_file_path: str | None = None, ) -> None: ``` ```python linter.lint_all_migrations(git_commit_id="a1b2c3d") # PR-based linting linter.lint_all_migrations(app_label="shop") # one app linter.lint_all_migrations(app_label="shop", migration_name="0002_auto") # one migration ``` ```python try: linter.lint_all_migrations(migrations_file_path="changed_migrations.txt") except MigrationLinterException as exc: logger.error("Failed to lint: %s", exc) ``` -------------------------------- ### Importing utility functions Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/utils.md The standard import path for accessing internal utility helpers. ```python from django_migration_linter.utils import ( clean_bytes_to_str, get_migration_abspath, split_migration_path, split_path, ) ``` -------------------------------- ### Basic command syntax: python manage.py lintmigrations Source: https://github.com/3yourmind/django-migration-linter/blob/main/docs/usage.md The linter is invoked as a Django management command. The optional arguments are app_label and migration_name. ```bash python manage.py lintmigrations [app_label] [migration_name] ``` -------------------------------- ### Import the Command class Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md Use this import path to access the Command class programmatically. ```python from django_migration_linter.management.commands.lintmigrations import Command ``` -------------------------------- ### Run lintmigrations command Source: https://github.com/3yourmind/django-migration-linter/blob/main/README.md Execute the lintmigrations command to analyze all migrations in the Django project. ```bash $ python manage.py lintmigrations (app_add_not_null_column, 0001_create_table)... OK (app_add_not_null_column, 0002_add_new_not_null_field)... ERR NOT NULL constraint on columns (app_drop_table, 0001_initial)... OK (app_drop_table, 0002_delete_a)... ERR DROPPING table (app_ignore_migration, 0001_initial)... OK (app_ignore_migration, 0002_ignore_migration)... IGNORE (app_rename_table, 0001_initial)... OK (app_rename_table, 0002_auto_20190414_1500)... ERR RENAMING tables *** Summary *** Valid migrations: 4/8 Erroneous migrations: 3/8 Migrations with warnings: 0/8 Ignored migrations: 1/8 ``` -------------------------------- ### read_migrations_list() class method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Reads a file containing migration paths and returns a list of (app_label, migration_name) tuples. ```python @classmethod def read_migrations_list( cls, migrations_file_path: str | None ) -> list[tuple[str, str]] | None: ``` -------------------------------- ### print_summary() Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Prints a summary with counts of valid, erroneous, warning, and ignored migrations. Returns without output when no_output is set. ```APIDOC ## print_summary() ### Description Prints `*** Summary ***` plus `Valid migrations`, `Erroneous migrations`, `Migrations with warnings`, and `Ignored migrations` counts as `X/nb_total`. Returns without output when `no_output` is set. ### Method print_summary ### Parameters None ### Response None ``` -------------------------------- ### Integrate with makemigrations Source: https://github.com/3yourmind/django-migration-linter/blob/main/README.md Detect incompatibilities during the generation of migrations using the --lint flag. ```bash $ python manage.py makemigrations --lint Migrations for 'app_correct': tests/test_project/app_correct/migrations/0003_a_column.py - Add field column to a Linting for 'app_correct': (app_correct, 0003_a_column)... ERR NOT NULL constraint on columns The migration linter detected that this migration is not backward compatible. - If you keep the migration, you will want to fix the issue or ignore the migration. - By default, the newly created migration file will be deleted. Do you want to keep the migration? [y/N] n Deleted tests/test_project/app_correct/migrations/0003_a_column.py ``` -------------------------------- ### MigrationLinter Constructor Signature Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md The constructor accepts various parameters to configure migration filtering, database settings, caching, and output verbosity. ```python def __init__( self, path: str | None = None, ignore_name_contains: str | None = None, ignore_name: Iterable[str] | None = None, include_name_contains: str | None = None, include_name: Iterable[str] | None = None, include_apps: Iterable[str] | None = None, exclude_apps: Iterable[str] | None = None, database: str = DEFAULT_DB_ALIAS, cache_path: str = DEFAULT_CACHE_PATH, no_cache: bool = False, only_applied_migrations: bool = False, only_unapplied_migrations: bool = False, exclude_migration_tests: Iterable[str] | None = None, quiet: Iterable[str] | None = None, warnings_as_errors_tests: Iterable[str] | None = None, all_warnings_as_errors: bool = False, no_output: bool = False, analyser_string: str | None = None, ignore_sqlmigrate_errors: bool = False, ignore_initial_migrations: bool = False, ): ``` -------------------------------- ### Cache.load() Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/cache.md Loads the pickle file into the dict. An OSError (missing file, corrupted/absent) is silently swallowed, resulting in an empty cache. Must be called before reads when resuming from disk. ```APIDOC ## Cache.load() ### Description Loads the pickle file into the dict (`pickle.load` + `self.update`). An `OSError` (missing file, corrupted/absent) is silently swallowed — an empty cache is used instead. Must be called before reads when resuming from disk. ### Method load ### Signature ```python def load(self) -> None: ``` ### Parameters None ### Returns None ``` -------------------------------- ### Import Cache Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/cache.md Import the Cache class from the django_migration_linter.cache module. ```python from django_migration_linter.cache import Cache ``` -------------------------------- ### Run makemigrations with linting Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/makemigrations-command.md Basic usage of the --lint flag to check migrations for compatibility issues. You can specify an app name, use --noinput to auto-delete incompatible files, or use --exclude-migration-tests to skip specific checks. ```bash python manage.py makemigrations --lint python manage.py makemigrations --lint shop python manage.py makemigrations --lint --noinput # incompatible files auto-deleted python manage.py makemigrations --lint --exclude-migration-tests ALTER_COLUMN ``` -------------------------------- ### Catching analyser-selection ValueError Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/errors.md Demonstrates catching a ValueError during MigrationLinter initialization when an unsupported analyser string is provided. ```python try: linter = MigrationLinter(analyser_string="oracle") except ValueError as exc: print(exc) # Unknown SQL analyser 'oracle'. Known values: 'sqlite','mysql','postgresql' ``` -------------------------------- ### Import management utilities Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/management-utils.md Import the core utility functions from the management utils module. ```python from django_migration_linter.management.utils import ( configure_logging, extract_warnings_as_errors_option, register_linting_configuration_options, ) ``` -------------------------------- ### MigrationLinter.__init__ Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Constructor for the MigrationLinter class. Initializes the linter with options for filtering migrations, controlling cache, and adjusting issue reporting. ```APIDOC ## MigrationLinter.__init__ ### Description Initializes a MigrationLinter instance with options to filter which migrations are linted, control caching behavior, and adjust how issues are reported. ### Method Constructor ### Signature ```python def __init__( self, path: str | None = None, ignore_name_contains: str | None = None, ignore_name: Iterable[str] | None = None, include_name_contains: str | None = None, include_name: Iterable[str] | None = None, include_apps: Iterable[str] | None = None, exclude_apps: Iterable[str] | None = None, database: str = DEFAULT_DB_ALIAS, cache_path: str = DEFAULT_CACHE_PATH, no_cache: bool = False, only_applied_migrations: bool = False, only_unapplied_migrations: bool = False, exclude_migration_tests: Iterable[str] | None = None, quiet: Iterable[str] | None = None, warnings_as_errors_tests: Iterable[str] | None = None, all_warnings_as_errors: bool = False, no_output: bool = False, analyser_string: str | None = None, ignore_sqlmigrate_errors: bool = False, ignore_initial_migrations: bool = False, ) ``` ### Parameters - **path** (str | None) - Optional - Django project root path. When set (and no_cache is falsy), the on-disk lint cache is used. - **ignore_name_contains** (str | None) - Optional - Skip migrations whose name contains this substring. - **ignore_name** (Iterable[str] | None) - Optional - Skip migrations whose name is exactly one of these. - **include_name_contains** (str | None) - Optional - Only keep migrations whose name contains this substring. - **include_name** (Iterable[str] | None) - Optional - Only keep migrations whose name is exactly one of these. - **include_apps** (Iterable[str] | None) - Optional - Only lint migrations of these app labels. - **exclude_apps** (Iterable[str] | None) - Optional - Skip migrations of these app labels. - **database** (str) - Optional - Database alias used to resolve ENGINE and to build the migration loader; defaults to "default". - **cache_path** (str) - Optional - Directory holding the pickle cache files. - **no_cache** (bool) - Optional - Disable reading/writing the lint cache. - **only_applied_migrations** (bool) - Optional - Only lint migrations present in migration_loader.applied_migrations. - **only_unapplied_migrations** (bool) - Optional - Only lint migrations absent from migration_loader.applied_migrations. - **exclude_migration_tests** (Iterable[str] | None) - Optional - Issue codes to downgrade from error/warning to "ignored". - **quiet** (Iterable[str] | None) - Optional - MessageType values whose stdout messages are suppressed. - **warnings_as_errors_tests** (Iterable[str] | None) - Optional - Issue codes to escalate from warning to error. - **all_warnings_as_errors** (bool) - Optional - Escalate every warning to an error. - **no_output** (bool) - Optional - Suppress all print output. - **analyser_string** (str | None) - Optional - Force a SQL analyser: "sqlite", "mysql", "postgresql". - **ignore_sqlmigrate_errors** (bool) - Optional - When sqlmigrate raises, record the issue as ignored instead of an error. - **ignore_initial_migrations** (bool) - Optional - Skip migrations whose Migration.initial attribute is True. ### Returns None ``` -------------------------------- ### Check cache usage method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Returns a boolean indicating whether the cache should be used, based on the project path and cache configuration. ```python def should_use_cache(self) -> bool: ``` -------------------------------- ### lint_all_migrations() Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Main entry point for linting migrations. Collects migrations, sorts them by (app_label, name), and lints each matching migration. Supports filtering by app, migration name, git commit, or a file listing migrations. ```APIDOC ## lint_all_migrations() ### Description Main entry point for linting migrations. Collects migrations, sorts them by (app_label, name), and lints each matching migration. Saves the new cache when caching is enabled. ### Method lint_all_migrations() ### Signature ```python def lint_all_migrations( self, app_label: str | None = None, migration_name: str | None = None, git_commit_id: str | None = None, migrations_file_path: str | None = None, ) -> None: ``` ### Parameters - **app_label** (str | None) - Optional - Restrict linting to one Django app. - **migration_name** (str | None) - Optional - With app_label, restrict to a single migration (resolved via migration_loader.get_migration_by_prefix). - **git_commit_id** (str | None) - Optional - Only lint migrations added (A) or renamed (R) since this git commit (uses git diff --relative --name-only --diff-filter=AR ). - **migrations_file_path** (str | None) - Optional - Path to a file listing migration file paths; only those migrations are considered. ### Returns None ### Exceptions - **MigrationLinterException** - When the migrations-list file cannot be read or git diff fails. ### Example ```python linter.lint_all_migrations(git_commit_id="a1b2c3d") # PR-based linting linter.lint_all_migrations(app_label="shop") # one app linter.lint_all_migrations(app_label="shop", migration_name="0002_auto") # one migration ``` ```python try: linter.lint_all_migrations(migrations_file_path="changed_migrations.txt") except MigrationLinterException as exc: logger.error("Failed to lint: %s", exc) ``` ``` -------------------------------- ### read_migrations_list(migrations_file_path) (classmethod) Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Reads a file containing migration file paths and returns a list of (app_label, migration_name) tuples. Returns None if no file is given, or an empty list if the file has no valid paths. ```APIDOC ## read_migrations_list(migrations_file_path) (classmethod) ### Description Reads a file containing migration file paths, returning a list of `(app_label, migration_name)` tuples. Semantics of the return: `None` means "no file given → consider all migrations", an empty list means "file given but no valid paths → consider none". Throws: `MigrationLinterException` (`"Error while reading migrations list file"`) on `OSError`. ### Method read_migrations_list ### Parameters - **migrations_file_path** (str | None) - Required - Path to the migrations list file. ### Response - **migrations** (list[tuple[str, str]] | None) - List of (app_label, migration_name) tuples, or None if no file was given. ``` -------------------------------- ### Cache Constructor Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/cache.md Initializes the Cache object with the Django project folder, database alias, and cache directory path. ```python def __init__(self, django_folder: str | None, database: str, cache_path: str): ``` -------------------------------- ### BaseAnalyser Constructor Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/sql-analyser-base.md Initializes the BaseAnalyser with an optional list of migration tests to exclude. ```python def __init__(self, exclude_migration_tests: Iterable[str] | None): ``` -------------------------------- ### should_ignore_migration(app_label, migration_name, operations, is_initial) Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Decision procedure for skipping a migration based on include/exclude apps, ignore/include name patterns, applied/unapplied status, and initial migration settings. ```APIDOC ## should_ignore_migration(app_label, migration_name, operations, is_initial) ### Description Decision procedure for skipping a migration; returns `True` when any of these holds: | Condition | Option involved | |-----------|-----------------| | `include_apps` set and `app_label` not in it | `include_apps` | | `exclude_apps` set and `app_label` in it | `exclude_apps` | | any operation is an `IgnoreMigration` instance | — (see [ignore-migration.md](./ignore-migration.md)) | | `ignore_name_contains` is a substring of `migration_name` | `ignore_name_contains` | | `include_name_contains` set and not a substring of `migration_name` | `include_name_contains` | | `migration_name` in `ignore_name` | `ignore_name` | | `include_name` set and `migration_name` not in it | `include_name` | | `only_applied_migrations` and `(app_label, name)` not in `applied_migrations` | only applied | | `only_unapplied_migrations` and `(app_label, name)` in `applied_migrations` | only unapplied | | `ignore_initial_migrations` and `is_initial` | initial migrations | `operations` defaults to `()` and `is_initial` to `False`; `lint_migration` passes the migration's operations and `migration.initial`. ### Method should_ignore_migration ### Parameters - **app_label** (str) - Required - The application label. - **migration_name** (str) - Required - The migration name. - **operations** (Iterable[Operation]) - Optional - The migration operations. Defaults to (). - **is_initial** (bool) - Optional - Whether the migration is initial. Defaults to False. ### Response - **should_ignore** (bool) - True if the migration should be ignored. ### Example ```python linter = MigrationLinter( include_apps=["shop", "billing"], ignore_name_contains="datafix", ) # shop 0001_initial -> False (linted) # legacy 0001_initial -> True (app excluded) # shop 0002_datafix_orders -> True (name contains "datafix") ``` ``` -------------------------------- ### analyse_sql_statements(sql_analyser_class, sql_statements, exclude_migration_tests=None) Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/sql-analyser-analyser.md Instantiates the given analyser class, runs analyse on the SQL statements, and returns a tuple of errors, ignored, and warnings. ```APIDOC ## analyse_sql_statements(sql_analyser_class, sql_statements, exclude_migration_tests=None) ### Description Instantiates sql_analyser_class(exclude_migration_tests), runs analyser.analyse(sql_statements), and returns (analyser.errors, analyser.ignored, analyser.warnings). This is the pattern used by MigrationLinter.lint_migration and lint_runsql. ### Method Function call ### Parameters - **sql_analyser_class** (type[BaseAnalyser]) - Required - The analyser class to instantiate. - **sql_statements** (list[str]) - Required - The SQL statements to analyse. - **exclude_migration_tests** (Iterable[str] | None) - Optional - An iterable of migration test names to exclude. ### Returns - **tuple[list[Issue], list[Issue], list[Issue]]** - A tuple containing (errors, ignored, warnings). ### Example ```python from django_migration_linter.sql_analyser import ( MySqlAnalyser, analyse_sql_statements, ) errors, ignored, warnings = analyse_sql_statements( MySqlAnalyser, [ "ALTER TABLE `orders` ADD CONSTRAINT uq UNIQUE (`email`);", "DROP TABLE `legacy`;", ], exclude_migration_tests=["ADD_UNIQUE"], ) for issue in errors: print(issue.code, issue.message, issue.table) # DROP_TABLE ... ``` ``` -------------------------------- ### Cache save() method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/cache.md Writes the current dictionary state to the pickle file. Failed writes will raise an OSError. ```python def save(self) -> None: ``` -------------------------------- ### read_config_file method signature Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/lintmigrations-command.md The static method signature for reading configuration from a config file. ```python @staticmethod def read_config_file(options: dict[str, Any]) -> dict[str, Any]: ``` -------------------------------- ### Configure logging Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/management-utils.md Configures the django_migration_linter logger based on the provided verbosity level. ```python def configure_logging(verbosity: int) -> None: ``` -------------------------------- ### Basic Migration Linter usage Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md A simple implementation of the MigrationLinter to lint all migrations in a project and exit with an error code if issues are found. ```python from django_migration_linter import MigrationLinter linter = MigrationLinter(path="/path/to/my/project") linter.lint_all_migrations() linter.print_summary() if linter.has_errors: raise SystemExit(1) ``` -------------------------------- ### is_migration_file() static method Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/migration-linter.md Determines if a filename corresponds to a valid migration file, excluding __init__ files. ```python @staticmethod def is_migration_file(filename: str) -> bool: ``` -------------------------------- ### warnings_as_errors_tests / all_warnings_as_errors Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/errors.md Configuration options to escalate warnings to errors. ```APIDOC ## warnings_as_errors_tests / all_warnings_as_errors ### Description Escalates warnings to errors, causing them to be treated as erroneous findings. ### Usage - Configure via `warnings_as_errors_tests` or `all_warnings_as_errors` in the linter configuration. - Affects the `errors` list returned by `analyse_sql_statements`. ``` -------------------------------- ### Configure MIGRATION_LINTER_OPTIONS in Django settings Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/configuration.md Define linter options as a dictionary in Django settings. Keys correspond to CLI option names using underscores instead of dashes. ```python MIGRATION_LINTER_OPTIONS = { "no_cache": True, "exclude_apps": ["users"], "warnings_as_errors": ["CREATE_INDEX"], # or [] for all warnings } ``` -------------------------------- ### Lint one Django app Source: https://github.com/3yourmind/django-migration-linter/blob/main/docs/usage.md Run the linter on a specific Django app by providing its app_label. ```bash python manage.py lintmigrations app_label ``` -------------------------------- ### Importing SQL analysers Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/sql-analyser-vendors.md Import the vendor-specific analyser classes from the sql_analyser package. ```python from django_migration_linter.sql_analyser import ( MySqlAnalyser, PostgresqlAnalyser, SqliteAnalyser, ) ``` -------------------------------- ### Import Command class Source: https://github.com/3yourmind/django-migration-linter/blob/main/_autodocs/api-reference/makemigrations-command.md Import the custom Command class from the django-migration-linter package. ```python from django_migration_linter.management.commands.makemigrations import Command ``` -------------------------------- ### Lint a specific migration Source: https://github.com/3yourmind/django-migration-linter/blob/main/docs/usage.md Run the linter on a specific migration by providing app_label and migration_name. ```bash python manage.py lintmigrations app_label migration_name ```