├── .codecov.yml ├── .github ├── dependabot.yml └── workflows │ └── ci-build.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── incompatibilities.md ├── internals │ ├── cache.md │ ├── publishing.md │ └── testing.md ├── makemigrations.md └── usage.md ├── manage.py ├── pyproject.toml ├── src └── django_migration_linter │ ├── __init__.py │ ├── cache.py │ ├── constants.py │ ├── management │ ├── __init__.py │ ├── commands │ │ ├── __init__.py │ │ ├── lintmigrations.py │ │ └── makemigrations.py │ └── utils.py │ ├── migration_linter.py │ ├── operations.py │ ├── py.typed │ ├── sql_analyser │ ├── __init__.py │ ├── analyser.py │ ├── base.py │ ├── mysql.py │ ├── postgresql.py │ └── sqlite.py │ └── utils.py ├── tests ├── __init__.py ├── fixtures.py ├── functional │ ├── __init__.py │ ├── test_cache.py │ ├── test_data_migrations.py │ ├── test_lintmigrations_command.py │ ├── test_makemigrations_command.py │ └── test_migration_linter.py ├── test_project │ ├── __init__.py │ ├── app_add_manytomany_field │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_b_many_to_many.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_add_not_null_column │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_create_table.py │ │ │ ├── 0002_add_new_not_null_field.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_add_not_null_column_followed_by_db_default │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_a_not_null_field_db_default.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_add_not_null_column_followed_by_default │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_a_not_null_field.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_alter_column │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20190414_1456.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_alter_column_drop_not_null │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_create_table.py │ │ │ ├── 0002_drop_not_null.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_correct │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_foo.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_create_index_exclusive │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_user_email.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_create_table_with_not_null_column │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_data_migrations │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_missing_reverse.py │ │ │ ├── 0003_incorrect_arguments.py │ │ │ ├── 0004_partial_function.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_drop_column │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_remove_a_field_b.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_drop_table │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_delete_a.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_ignore_migration │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_ignore_migration.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_make_not_null_with_django_default │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_make_not_null_with_django_default.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_make_not_null_with_lib_default │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_make_not_null_with_lib_default.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_rename_column │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20190414_1502.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_rename_table │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20190414_1500.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_unique_together │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20190729_2122.py │ │ │ ├── 0003_auto_20190729_2122.py │ │ │ └── __init__.py │ │ └── models.py │ ├── app_with_custom_name │ │ ├── __init__.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ └── models.py │ ├── makemigrations_backward_incompatible_migration_missing │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ └── models.py │ ├── makemigrations_correct_migration_missing │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ └── models.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── unit │ ├── __init__.py │ ├── test_linter.py │ ├── test_sql_analyser.py │ └── test_utils.py └── tox.ini /.codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: off 4 | patch: off 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | assignees: 8 | - "David-Wobrock" 9 | - package-ecosystem: pip 10 | directory: "/" 11 | schedule: 12 | interval: weekly 13 | assignees: 14 | - "David-Wobrock" 15 | -------------------------------------------------------------------------------- /.github/workflows/ci-build.yml: -------------------------------------------------------------------------------- 1 | name: CI Build 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | services: 13 | postgres: 14 | image: postgres 15 | env: 16 | POSTGRES_PASSWORD: postgres 17 | ports: 18 | - 5432:5432 19 | options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 20 | 21 | mysql: 22 | image: mysql:8.0 23 | env: 24 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 25 | ports: 26 | - 3306:3306 27 | options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 28 | 29 | strategy: 30 | matrix: 31 | python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] 32 | 33 | name: Build with Python ${{ matrix.python-version }} 34 | steps: 35 | - name: Checkout code 36 | uses: actions/checkout@v4 37 | # Fetch all tags and branches because tests rely on it 38 | with: 39 | fetch-depth: 0 40 | - name: Set up Python ${{ matrix.python-version }} 41 | uses: actions/setup-python@v5 42 | with: 43 | python-version: ${{ matrix.python-version }} 44 | - name: Install dependencies 45 | run: python -m pip install tox==4.6.3 tox-gh-actions 46 | - name: Test with tox ${{ matrix.python-version }} 47 | run: tox 48 | 49 | lint: 50 | name: Linting 51 | runs-on: ubuntu-latest 52 | steps: 53 | - name: Checkout code 54 | uses: actions/checkout@v4 55 | - name: Set up Python 3.12 56 | uses: actions/setup-python@v5 57 | with: 58 | python-version: '3.12' 59 | - name: Install dependencies 60 | run: python -m pip install tox==4.24.1 61 | - name: Lint with tox 62 | run: tox 63 | env: 64 | TOXENV: lint 65 | 66 | coverage: 67 | name: Generate coverage 68 | runs-on: ubuntu-latest 69 | services: 70 | postgres: 71 | image: postgres 72 | env: 73 | POSTGRES_PASSWORD: postgres 74 | ports: 75 | - 5432:5432 76 | options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 77 | 78 | mysql: 79 | image: mysql:8.0 80 | env: 81 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 82 | ports: 83 | - 3306:3306 84 | options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 85 | 86 | steps: 87 | - name: Checkout code 88 | uses: actions/checkout@v4 89 | # Fetch all tags and branches because tests rely on it 90 | with: 91 | fetch-depth: 0 92 | - name: Set up Python 3.12 93 | uses: actions/setup-python@v5 94 | with: 95 | python-version: '3.12' 96 | - name: Install dependencies and coverage 97 | run: python -m pip install tox==4.24.1 98 | - name: Test with tox with coverage 99 | run: tox 100 | env: 101 | TOXENV: coverage 102 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | .idea/ 3 | .vscode/ 4 | *.swp 5 | tags 6 | __pycache__/ 7 | *.pyc 8 | build/ 9 | dist/ 10 | *.egg-info/ 11 | .cache/ 12 | env/ 13 | .tox/ 14 | *.sqlite3 15 | *.pickle 16 | .mypy_cache/ 17 | .ruff_cache/ 18 | venv/ 19 | .python-version 20 | sqlite3 21 | .DS_Store 22 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v5.0.0 4 | hooks: 5 | - id: check-added-large-files 6 | - id: check-ast 7 | - id: check-case-conflict 8 | - id: check-json 9 | - id: check-merge-conflict 10 | - id: check-toml 11 | - id: check-yaml 12 | - id: debug-statements 13 | - id: end-of-file-fixer 14 | - id: forbid-submodules 15 | - id: trailing-whitespace 16 | - repo: https://github.com/psf/black 17 | rev: 25.1.0 18 | hooks: 19 | - id: black 20 | - repo: https://github.com/PyCQA/flake8 21 | rev: 7.2.0 22 | hooks: 23 | - id: flake8 24 | exclude: ^tests/ 25 | - repo: https://github.com/pycqa/isort 26 | rev: 6.0.1 27 | hooks: 28 | - id: isort 29 | - repo: https://github.com/pre-commit/mirrors-mypy 30 | rev: v1.15.0 31 | hooks: 32 | - id: mypy 33 | additional_dependencies: 34 | - types-toml==0.10.8.20240310 35 | args: 36 | - "--ignore-missing-imports" 37 | exclude: ^tests/ 38 | - repo: https://github.com/astral-sh/ruff-pre-commit 39 | rev: v0.11.2 40 | hooks: 41 | - id: ruff 42 | args: 43 | - "--line-length=88" 44 | exclude: ^tests/ 45 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 6.0.0 2 | 3 | Feature: 4 | - **Breaking change**: Handle custom Django app label when gathering migrations from git reference. (#262) 5 | This means that, an app that was previously referenced by its folder name, will now be referenced by its Django app label. 6 | 7 | Miscellaneous: 8 | - Add py.typed file (#303) 9 | - Add support for Django 5.2 (#304) 10 | 11 | ## 5.2.0 12 | 13 | Feature: 14 | - Allow ignoring all initial migrations, with `--ignore-initial-migrations` 15 | 16 | Bug: 17 | - Don't detect an index creation during a transaction with an exclusive lock, when the table is being created (#264) 18 | 19 | Miscellaneous: 20 | - Add support for Python 3.13 21 | - Add support for Django 5.1 22 | - Drop support for Python 3.7 and 3.8 23 | - Mark md5 hashing as not used for security 24 | 25 | ## 5.1.0 26 | 27 | Feature: 28 | - Support Django 5.0 `db_default` attribute (issue #275) 29 | - Allow ignoring the failures of `sqlmigrate` commands, with `--ignore-sqlmigrate-errors` option (issue #274) 30 | 31 | Bug: 32 | - Don't detect 'IS NOT NULL' as backward incompatible changes (issue #263) 33 | - Don't consider UNIQUE INDEX creation as making a column not nullable 34 | 35 | Miscellaneous: 36 | - Migrated from `setup.py` and `setup.cfg` to `pyproject.toml` 37 | - Add support for Python 3.12 38 | - Add support for Django 5.0 39 | - Avoid git command injections 40 | - Remove Codecov integration 41 | 42 | ## 5.0.0 43 | 44 | - **Breaking change**: stop silently ignoring when the internal `sqlmigrate` call fails and the linter cannot analyse the migration. 45 | Instead, the linter crashes and lets the `sqlmigrate` error raise, in order to avoid letting a problematic migration pass. 46 | One common reason for such an error is the SQL generation which requires the database to be actually migrated in order to fetch actual constraint names from it. 47 | The crash is a sign to double-check the migration. But if you are certain the migration is safe, you can ignore it (issue #209) 48 | 49 | Features: 50 | - Fixed `RunPython` model import check when using a `through` object like `MyModel.many_to_many.through.objects.filter(...)` (issue #218) 51 | - Mark the `IgnoreMigration` operation as `elidable=True` 52 | - Handle `functools.partial` functions in RunPython data migrations 53 | - Add a new check, `CREATE_INDEX_EXCLUSIVE` to detect index creation while an exclusive lock is held 54 | 55 | Bug: 56 | - Don't detect not nullable field on partial index creation (issue #250) 57 | 58 | Miscellaneous: 59 | - Add support for Python 3.11 60 | - Add support for Django 4.1 61 | - Add support for Django 4.2 62 | - Drop support for Django 2.2 63 | - Internally rename "migration tests" to "migration checks" 64 | - Add dataclasses internally instead of custom dicts 65 | - Use pre-commit hooks for linting 66 | - Add `mypy` and `ruff` usages 67 | 68 | ## 4.1.0 69 | 70 | - Allow configuring logging for `makemigrations` command and unify behaviour with `lintmigrations` (issue #207) 71 | - Adapt `--warnings-as-errors` option to allow selecting some migration tests only (issue #201) 72 | - Add `sql_analyser` option to `makemigrations` in order to specify the SQL analyser to use (issue #208) 73 | - Make `project_root_path` and `verbosity` configurable from other setting source (issue #203) 74 | 75 | ## 4.0.0 76 | 77 | - Drop support for Python 2.7, 3.5 and 3.6 78 | - Add support for Python 3.10 79 | - Drop support for Django 1.11, 2.0, 2.1, 3.0 and 3.1 80 | - Add support for Django 4.0 81 | - Fix index creation detection when table is being created in the transaction (issue #178) 82 | - Handle unique index creation as adding a unique constraint (issue #183) 83 | - Allow any option to be set/unset in config file (issue #167) 84 | - Allow using Django settings for any option to be set/unset (issue #198) 85 | - Raise when unsupported database vendor, allow passing an option to select SQL analyser (issue #138 and #169) 86 | 87 | ## 3.0.1 88 | 89 | Fixed bug: 90 | - Setting a field as NOT NULL without default passed the linter. 91 | 92 | ## 3.0.0 93 | 94 | **Breaking API change on `lintmigrations` command**: 95 | * the positional argument `GIT_COMMIT_ID` becomes an optional argument with the named parameter ` --git-commit-id [GIT_COMMIT_ID]` 96 | * the `lintmigrations` command takes now two positional arguments: `lintmigrations [app_label] [migration_name]` 97 | 98 | New features: 99 | * raise warning when create or dropping an index in a non-concurrent manner using postgresql 100 | 101 | Miscellaneous: 102 | * Add complete and working support for `toml` configuration files 103 | * Handle `--verbosity 0` or `-v 0` correctly to not print anything from the linter 104 | * Add code coverage to the linter 105 | * Renamed `master` branch to `main` 106 | 107 | ## 2.5.3 108 | 109 | * Stop packaging the 'tests' module into the release wheel file 110 | * Add Django 3.2 support 111 | 112 | ## 2.5.2 113 | 114 | * Remove `toml` support for config files 115 | 116 | ## 2.5.1 117 | 118 | * Remove `.editorconfig` from default config file 119 | * Allow utf-8 encoding in config files 120 | 121 | ## 2.5.0 122 | 123 | **Renamed lint checks**: 124 | * `REVERSIBLE_DATA_MIGRATION` -> `RUNPYTHON_REVERSIBLE` 125 | * `NAMING_CONVENTION_RUNPYTHON_ARGS` -> `RUNPYTHON_ARGS_NAMING_CONVENTION` 126 | * `DATA_MIGRATION_MODEL_IMPORT` -> `RUNPYTHON_MODEL_IMPORT` 127 | * `DATA_MIGRATION_MODEL_VARIABLE_NAME` -> `RUNPYTHON_MODEL_VARIABLE_NAME` 128 | * `REVERSIBLE_RUNSQL_DATA_MIGRATION` -> `RUNSQL_REVERSIBLE` 129 | 130 | Features/fixes: 131 | * Add Python 3.9 support 132 | * Make data migration model import error less strict (issue #121) 133 | * Add warning detection on RunPython call when model variable name is not the same as model class name 134 | * Run checks on RunSQL migration operations 135 | * Rename the RunPython data migration lint checks for improved consistency 136 | * Refactor and commonise the loggers, so that all modules the `django_migration_linter` logger 137 | * Allow using configuration file for linter options 138 | * Add option `--include-name` and `--include-name-contains` to only include migration with a certain name 139 | 140 | Others: 141 | * Switched from Travis CI to GitHub Actions for tests 142 | * Apply `isort` to the project 143 | 144 | ## 2.4.1 145 | 146 | * Add Django 3.1 support 147 | * Upgrade linter versions of `flake8` and `black` to the latest 148 | 149 | ## 2.4.0 150 | 151 | * Add possibility to lint newly generated migrations through the `makemigrations` command. 152 | You can activate it through the `--lint` command option, or by default with the `MIGRATION_LINTER_OVERRIDE_MAKEMIGRATIONS = True` Django settings. 153 | 154 | ## 2.3.0 155 | 156 | * Handle making a column NOT NULL with a Django default value as backward incompatible. 157 | This should have been the case from the beginning, but it was not. 158 | When one uses the `django-add-default-value` lib, the operation should still be compatible. 159 | * Improve behaviour of the `--include-migrations-from` option. 160 | When the given filename is missplelled, fail instead of linting all migrations. 161 | When the file is empty, lint no migrations instead of linting all migrations. 162 | * Update libraries used for testing (`tox`, `flake8`, etc.) 163 | 164 | ## 2.2.2 165 | 166 | * Don't pin dependencies but only define minimal versions 167 | 168 | ## 2.2.1 169 | 170 | Fixed bug: 171 | * Correctly detect `apps.get_models` when on multiple lines in data migration 172 | 173 | ## 2.2.0 174 | 175 | * Make summary output more friendly (Thanks to @vald-phoenix) 176 | * Add forgotten documentation about `IgnoreMigration` 177 | * Don't pin the `appdirs` strictly to 1.4.3, but allow higher versions 178 | 179 | ## 2.1.0 180 | 181 | * Detect in data migrations if models are imported the correct way or not 182 | 183 | ## 2.0.0 184 | 185 | * Add linting on data migrations that will raise warnings 186 | * Add `--quiet warning` option to suppress warning messages 187 | * Add `--warnings-as-errors` option to handle warnings as errors 188 | 189 | ## 1.5.0 190 | 191 | * Rework documentation. 192 | Make README smaller and clearer. 193 | Move detailed documentation to docs/ folder. 194 | * Add Django 3.0 to test matrix. 195 | 196 | ## 1.4.1 197 | 198 | * Update testing dependencies (``mysqlclient``, Django 2.2 and ``black``) 199 | 200 | ## 1.4.0 201 | 202 | * Add `--include-migrations-from` option to only consider migrations specified in a given file. 203 | No matter if the migrations are selected from a git commit or not, we only select the ones in the given file. 204 | * Add ``--quiet {ok,ignore,error}`` option to remove different or multiple types of messages from being printed to stdout. 205 | * Make detection of problematic table and column a bit more resilient for UX. 206 | * Add Python 3.8 to test matrix and update test dependencies. 207 | 208 | Fixed bugs: 209 | 210 | * Handle adding many to many fields correctly. 211 | 212 | ## 1.3.0 213 | 214 | * Add `--exclude-migration-tests` option to ignore backward incompatible migration tests. 215 | * Do not falsely detect dropping `NOT NULL` constraint. 216 | * Detect `DROP TABLE` backward incompatible migration. 217 | * Detect adding a `UNIQUE` constraint as backward incompatible migration. 218 | * Handle when Django tries to generate the SQL of a migration but raises an exception because 219 | it cannot find the name of a certain constraint (because it has been dropped already). 220 | 221 | Internal change: 222 | 223 | * Differentiate different database vendors during SQL analysis. 224 | 225 | ## 1.2.0 226 | 227 | * Add `--unapplied-migrations` and `--applied-migrations` mutually exclusive options 228 | in order to respectively lint only unapplied or applied migrations. 229 | * When loading migration starting from a git ref, cross the found migrations 230 | with the currently loaded migrations in the project. 231 | * Add `--project-root-path` which allows to specify the root path 232 | which is used for finding the `.git` folder. (thanks to @linuxmaniac) 233 | 234 | ## 1.1.0 235 | 236 | * Improve speed of ignored migration through the `IgnoreMigration` operation. 237 | Instead of generating their SQL, we verify if the Operation class is present. 238 | Thus we don't have to wait for the SQL generation. Also improves the caching strategy. 239 | 240 | Breaks some internal APIs, so minor update to 1.1.0. 241 | 242 | ## 1.0.0 243 | 244 | **Breaking changes** of the linter usage. The linter now is a Django management command. 245 | It should be used with a `python manage.py lintmigrations` followed by the usual options. 246 | Additionally, the linter now needs to be added the to the `INSTALLED_APPS` in your Django settings. 247 | 248 | * The linter is now much faster: we don't setup django once for each migration 249 | * The linter is now more robust: we rely on Django internals to discover migrations 250 | * Clean up of the testing setup: it is cleaner, less brittle and we have more confidence that it works 251 | * Added support for Django 2.2 252 | * Dropped support for Python 3.4 253 | 254 | Fixed bugs: 255 | 256 | * Made the cache database-dependent. Between multiple databases, some migrations would be considered correct while they are not on the used DB. 257 | * Adding an erroneous migration to the ignore list on the second run would get the migration content from the cache and not ignore it. 258 | 259 | ## 0.1.5 260 | 261 | * Bug fix: handle migration files with spaces in their name by quoting the migration name 262 | 263 | ## 0.1.4 264 | 265 | * Explicitly test for mysql, sqlite3 and postgresql 266 | * Fix alter column type detection in postgresql 267 | * Do not create cache folder when -no-cache option 268 | * Fix tests on Windows 269 | * Use the same Python interpreter as used for launching the linter, instead of manually trying to re-create the path 270 | 271 | ## 0.1.3 272 | 273 | * Fixes migrations that are ignored to generate empty SQL, that PostgreSQL complains about. It throws an exception making migrations fail, that are in fact valid. (Thanks to @fevral13 and @mes3yd) 274 | * Add options -V and --version to show the current linter version 275 | 276 | ## 0.1.2 277 | 278 | * Bug fix: handle when the linter is called in the working dir django-migration-linter . 279 | * Bug fix: don't assume that the git root is at the same path as the django project 280 | 281 | ## 0.1.1 282 | 283 | * Fix caching when app is in a folder and not at the root of the project 284 | * Do not check for .git folder at root, because it might be located somewhere else. Let git itself do the job 285 | * Make some imports relative 286 | 287 | ## 0.1.0 288 | 289 | The django migration linter is now set to a Beta version, instead of Alpha since it has been used for quite some time. 290 | 291 | Version 0.1.0 comes with: 292 | 293 | * Possibility to ignore migration files entirely (without specifying them on the command line) 294 | * This can be used by adding the migration operation IgnoreMigration() in the migrations operations list. See readme 295 | * Caching. We cache failed and succeeded migrations (w.r.t. migration linting) in a cache file. 296 | * Each migration file is stored as the MD5 hash of its content with the result of the linting 297 | 298 | Other things: 299 | 300 | * Added support for Python 3.7 301 | * Added support for Django 2.1 302 | * The codebase is now in black format to improve Python-code readability 303 | * 2019 ! Happy new year 304 | 305 | ## 0.0.7 306 | 307 | * Minor bug fix when no errors detected 308 | 309 | ## 0.0.6 310 | 311 | * Use logger correctly 312 | * Drop django 1.10 support 313 | 314 | ## 0.0.5 315 | 316 | * Only consider added migrations during linting 317 | * Change readme to rst format (for PyPi) 318 | * Added examples folder 319 | * Add django (at least 1.10) as requirement for the linter 320 | 321 | ## 0.0.4 322 | 323 | Assure compatibility for multiple python and django versions. 324 | 325 | * Try to improve PyPi readme 326 | * Better error messages 327 | 328 | ## 0.0.3 329 | 330 | * Made a mistake and accidentally deleted 0.0.2 from PyPi 331 | 332 | ## 0.0.2 333 | 334 | * Python 3 compatibility 335 | * Faster migration gathering 336 | 337 | * Code base refactoring 338 | * Test base refactoring 339 | 340 | ## 0.0.1 341 | 342 | First version of command line tool to lint django migrations. 343 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | prune tests 2 | include README.md 3 | include LICENSE 4 | include CHANGELOG.md 5 | include MANIFEST.in 6 | recursive-include docs * 7 | include tox.ini 8 | include pyproject.toml 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django migration linter 2 | 3 | Detect backward incompatible migrations for your Django project. 4 | It will save you time by making sure migrations will not break with a older codebase. 5 | 6 | [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2F3YOURMIND%2Fdjango-migration-linter%2Fbadge%3Fref%3Dmain&style=flat)](https://actions-badge.atrox.dev/3YOURMIND/django-migration-linter/goto?ref=main) 7 | [![PyPI](https://img.shields.io/pypi/v/django-migration-linter.svg)](https://pypi.python.org/pypi/django-migration-linter/) 8 | [![PR_Welcome](https://img.shields.io/badge/PR-welcome-green.svg)](https://github.com/3YOURMIND/django-migration-linter/pulls) 9 | [![3YD_Hiring](https://img.shields.io/badge/3YOURMIND-Hiring-brightgreen.svg)](https://www.3yourmind.com/career) 10 | [![GitHub_Stars](https://img.shields.io/github/stars/3YOURMIND/django-migration-linter.svg?style=social&label=Stars)](https://github.com/3YOURMIND/django-migration-linter/stargazers) 11 | 12 | ## Quick installation 13 | 14 | ``` 15 | pip install django-migration-linter 16 | ``` 17 | 18 | And add the migration linter to your ``INSTALLED_APPS``: 19 | ``` 20 | INSTALLED_APPS = [ 21 | ..., 22 | "django_migration_linter", 23 | ..., 24 | ] 25 | ``` 26 | 27 | Optionally, add a configuration: 28 | ``` 29 | MIGRATION_LINTER_OPTIONS = { 30 | ... 31 | } 32 | ``` 33 | 34 | For details about configuration options, checkout [Usage](docs/usage.md). 35 | 36 | ## Usage example 37 | 38 | ``` 39 | $ python manage.py lintmigrations 40 | 41 | (app_add_not_null_column, 0001_create_table)... OK 42 | (app_add_not_null_column, 0002_add_new_not_null_field)... ERR 43 | NOT NULL constraint on columns 44 | (app_drop_table, 0001_initial)... OK 45 | (app_drop_table, 0002_delete_a)... ERR 46 | DROPPING table 47 | (app_ignore_migration, 0001_initial)... OK 48 | (app_ignore_migration, 0002_ignore_migration)... IGNORE 49 | (app_rename_table, 0001_initial)... OK 50 | (app_rename_table, 0002_auto_20190414_1500)... ERR 51 | RENAMING tables 52 | 53 | *** Summary *** 54 | Valid migrations: 4/8 55 | Erroneous migrations: 3/8 56 | Migrations with warnings: 0/8 57 | Ignored migrations: 1/8 58 | ``` 59 | 60 | The linter analysed all migrations from the Django project. 61 | It found 3 migrations that are doing backward incompatible operations and 1 that is explicitly ignored. 62 | The list of incompatibilities that the linter analyses [can be found at docs/incompatibilities.md](./docs/incompatibilities.md). 63 | 64 | More advanced usages of the linter and options [can be found at docs/usage.md](./docs/usage.md). 65 | 66 | ## Integration 67 | 68 | One can either integrate the linter in the CI using its `lintmigrations` command, or detect incompatibilities during generation of migrations with 69 | ``` 70 | $ python manage.py makemigrations --lint 71 | 72 | Migrations for 'app_correct': 73 | tests/test_project/app_correct/migrations/0003_a_column.py 74 | - Add field column to a 75 | Linting for 'app_correct': 76 | (app_correct, 0003_a_column)... ERR 77 | NOT NULL constraint on columns 78 | 79 | The migration linter detected that this migration is not backward compatible. 80 | - If you keep the migration, you will want to fix the issue or ignore the migration. 81 | - By default, the newly created migration file will be deleted. 82 | Do you want to keep the migration? [y/N] n 83 | Deleted tests/test_project/app_correct/migrations/0003_a_column.py 84 | ``` 85 | 86 | The linter found that the newly created migration is not backward compatible and deleted the file after confirmation. 87 | This behaviour can be the default of the `makemigrations` command through the `MIGRATION_LINTER_OVERRIDE_MAKEMIGRATIONS` Django setting. 88 | Find out more about the [makemigrations command at docs/makemigrations.md](./docs/makemigrations.md). 89 | 90 | ### More information 91 | 92 | Please find more documentation [in the docs/ folder](./docs/). 93 | 94 | Some implementation details [can be found in the ./docs/internals/ folder](./docs/internals/). 95 | 96 | ### Blog post 97 | 98 | * [Keeping Django database migrations backward compatible](https://medium.com/3yourmind/keeping-django-database-migrations-backward-compatible-727820260dbb) 99 | * [Django and its default values](https://medium.com/botify-labs/django-and-its-default-values-c21a13cff9f) 100 | 101 | ### They talk about the linter 102 | 103 | * [Django News](https://django-news.com/issues/6?m=web#uMmosw7) 104 | * [wemake-django-template](https://wemake-django-template.readthedocs.io/en/latest/pages/template/linters.html#django-migration-linter) 105 | * [Testing Django migrations on sobolevn's blog](https://sobolevn.me/2019/10/testing-django-migrations#existing-setup) 106 | 107 | ### Related 108 | 109 | * [django-test-migrations](https://github.com/wemake-services/django-test-migrations) - Test django schema and data migrations, including migrations' order and best practices. 110 | 111 | ### License 112 | 113 | *django-migration-linter* is released under the [Apache 2.0 License](./LICENSE). 114 | 115 | ##### Maintained by [David Wobrock](https://github.com/David-Wobrock) 116 | -------------------------------------------------------------------------------- /docs/internals/cache.md: -------------------------------------------------------------------------------- 1 | # Cache 2 | 3 | By default, the linter uses a cache to prevent linting the same migration multiple times. 4 | The default location of the cache on Linux is 5 | `/home//.cache/django-migration-linter//_.pickle`. 6 | 7 | Since the linter uses hashes of the file's content, modifying a migration file will re-run the linter on that migration. 8 | If you want to run the linter without cache, use the flag `--no-cache`. 9 | If you want to invalidate the cache, delete the cache folder. 10 | The cache folder can also be defined manually through the `--cache-path` option. 11 | -------------------------------------------------------------------------------- /docs/internals/publishing.md: -------------------------------------------------------------------------------- 1 | # Publishing the package 2 | 3 | A small note on how the linter is usually published to PyPi: 4 | 5 | - `rm -r django_migration_linter.egg-info/ dist/` 6 | - `pip install --upgrade build` 7 | - `python -m build` 8 | - `pip install --upgrade twine` 9 | - `twine upload dist/django_migration_linter-X.Y.Z-py3-none-any.whl dist/django-migration-linter-X.Y.Z.tar.gz` 10 | -------------------------------------------------------------------------------- /docs/internals/testing.md: -------------------------------------------------------------------------------- 1 | # Testing 2 | 3 | The easiest way to run the tests is to invoke `tox` on the command line. 4 | 5 | You will need to install the test requirements, which can be found in the ``setup.py`` file. 6 | A good way to get started is to install the development version of the linter by doing ``pip install -e .[test]``. 7 | 8 | To be able to fully test the linter, you will need both MySQL and PostgreSQL databases running. 9 | You can either tweak the ``tests/test_project/settings.py`` file to get your DB settings right, or to have databases and users corresponding to the default CI users. 10 | 11 | ## Database setup 12 | 13 | By default, the test Django project in the repository has multiple databases configured in order to make the CI tests work. 14 | Do not hesitate to modify [the configured test databases](../../tests/test_project/settings.py). 15 | -------------------------------------------------------------------------------- /docs/makemigrations.md: -------------------------------------------------------------------------------- 1 | # makemigrations 2 | 3 | The linter can override the behaviour of the [Django makemigrations command](https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-makemigrations). 4 | 5 | Either: 6 | * by specifying the `--lint` option in the command line 7 | * by setting the `MIGRATION_LINTER_OVERRIDE_MAKEMIGRATIONS` Django setting to `True` 8 | 9 | ## Example 10 | ``` 11 | $ python manage.py makemigrations --lint 12 | 13 | Migrations for 'app_correct': 14 | tests/test_project/app_correct/migrations/0003_a_column.py 15 | - Add field column to a 16 | Linting for 'app_correct': 17 | (app_correct, 0003_a_column)... ERR 18 | NOT NULL constraint on columns 19 | 20 | The migration linter detected that this migration is not backward compatible. 21 | - If you keep the migration, you will want to fix the issue or ignore the migration. 22 | - By default, the newly created migration file will be deleted. 23 | Do you want to keep the migration? [y/N] n 24 | Deleted tests/test_project/app_correct/migrations/0003_a_column.py 25 | ``` 26 | 27 | ## Options 28 | 29 | Among the options that can be given, additionally to the default `makemigrations` options, you can count the options 30 | to configure what should be linted: 31 | * `--database DATABASE` - specify the database for which to generate the SQL. Defaults to *default*. 32 | * `--warnings-as-errors [MIGRATION_TEST_CASE ...]` - handle warnings as errors. Optionally specify the selected tests using their code. 33 | * `--exclude-migration-tests MIGRATION_TEST_CODE [...]` - specify backward incompatible migration tests to be ignored using the code (e.g. ALTER_COLUMN). 34 | -------------------------------------------------------------------------------- /docs/usage.md: -------------------------------------------------------------------------------- 1 | # Usage 2 | 3 | ## Command line usage 4 | 5 | The linter is installed as a Django app and is integrated through the Django management command system. 6 | 7 | `python manage.py lintmigrations [app_label] [migration_name]` 8 | 9 | The three main usages are: 10 | 11 | * Lint your entire code base 12 | `python manage.py lintmigrations` 13 | 14 | * Lint one Django app 15 | `python manage.py lintmigrations app_label` 16 | 17 | * Lint a specific migration 18 | `python manage.py lintmigrations app_label migration_name` 19 | 20 | Below the detailed command line options, which can all also be defined using a config file: 21 | - `settings.py` 22 | - `setup.cfg` 23 | - `tox.ini` 24 | - `pyproject.toml` 25 | - `.django_migration_linter.cfg` 26 | 27 | If you are using a config file, replace any dashes (`-`) with an underscore (`_`). 28 | 29 | | Parameter | Description | 30 | |-------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 31 | | `--git-commit-id GIT_COMMIT_ID` | If specified, only migrations since this commit will be taken into account. | 32 | | `--ignore-name-contains IGNORE_NAME_CONTAINS` | Ignore migrations containing this name. | 33 | | `--ignore-name IGNORE_NAME [IGNORE_NAME ...]` | Ignore migrations with exactly one of these names. | 34 | | `--include-name-contains INCLUDE_NAME_CONTAINS` | Include migrations containing this name. | 35 | | `--include-name INCLUDE_NAME [INCLUDE_NAME ...]` | Include migrations with exactly one of these names. | 36 | | `--include-apps INCLUDE_APPS [INCLUDE_APPS ...]` | Check only migrations that are in the specified django apps. | 37 | | `--exclude-apps EXCLUDE_APPS [EXCLUDE_APPS ...]` | Ignore migrations that are in the specified django apps. | 38 | | `--exclude-migration-tests MIGRATION_TEST_CODE [...]` | Specify backward incompatible migration tests to be ignored using the code (e.g. ALTER_COLUMN). | 39 | | `--verbosity or -v {0,1,2,3}` | Print more information during execution. | 40 | | `--database DATABASE` | Specify the database for which to generate the SQL. Defaults to *default*. | 41 | | `--cache-path PATH` | specify a directory that should be used to store cache-files in. | 42 | | `--no-cache` | Don't use a cache. | 43 | | `--applied-migrations` | Only lint migrations that are applied to the selected database. Other migrations are ignored. | 44 | | `--unapplied-migrations` | Only lint migrations that are not yet applied to the selected database. Other migrations are ignored. | 45 | | `--project-root-path DJANGO_PROJECT_FOLDER` | An absolute or relative path to the django project. | 46 | | `--include-migrations-from FILE_PATH` | If specified, only migrations listed in the given file will be considered. | 47 | | `--quiet or -q {ok,ignore,warning,error}` | Suppress certain output messages, instead of writing them to stdout. | 48 | | `--warnings-as-errors [MIGRATION_TEST_CODE [...]]` | Handle warnings as errors and therefore return an error status code if we should. Optionally specify migration test codes to handle as errors. When no test code specified, all warnings are handled as errors. | 49 | | `--sql-analyser` | Specify the SQL analyser that should be used. Allowed values: 'sqlite', 'mysql', 'postgresql'. | 50 | | `--ignore-sqlmigrate-errors` | Ignore failures of sqlmigrate commands. | 51 | | `--ignore-initial-migrations` | Ignore initial migrations. | 52 | 53 | ## Django settings configuration 54 | 55 | All settings can be defined in the Django settings: 56 | 57 | ``` 58 | MIGRATION_LINTER_OPTIONS = { 59 | "no_cache": True, 60 | "exclude_apps": ["users"] 61 | } 62 | ``` 63 | 64 | ## File configuration 65 | 66 | Example `setup.cfg` file: 67 | 68 | ``` 69 | [django_migration_linter] 70 | no_cache = True 71 | exclude_apps = users 72 | ``` 73 | 74 | ## Ignoring migrations 75 | 76 | You can also ignore migrations by adding an `IgnoreMigration()` to your migration operations: 77 | ``` 78 | from django.db import migrations, models 79 | import django_migration_linter as linter 80 | 81 | class Migration(migrations.Migration): 82 | dependencies = [...] 83 | operations = [ 84 | linter.IgnoreMigration(), 85 | # ... 86 | ] 87 | ``` 88 | 89 | Or you can restrict the migrations that should be selected by a file containing there paths with the `--include-migrations-from` option. 90 | Or you can ignore all initial migrations with the `--ignore-initial-migrations` option. 91 | 92 | ## Ignoring migration tests 93 | 94 | You can also ignore backward incompatible migration tests by adding this option during execution: 95 | 96 | `python manage.py lintmigrations --exclude-migration-tests ALTER_COLUMN` 97 | 98 | The migration test codes can be found in the [corresponding source code files](../src/django_migration_linter/sql_analyser/base.py). 99 | 100 | ## Production usage example 101 | 102 | [3YOURMIND](https://www.3yourmind.com/) is running the linter on every build getting pushed through CI. 103 | That enables to be sure that the migrations will allow A/B testing, Blue/Green deployment, and they won't break your development environment. 104 | A non-zero error code is returned to express that at least one invalid migration has been found. 105 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from __future__ import annotations 3 | 4 | import os 5 | import sys 6 | 7 | if __name__ == "__main__": 8 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.test_project.settings") 9 | 10 | from django.core.management import execute_from_command_line 11 | 12 | execute_from_command_line(sys.argv) 13 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "django-migration-linter" 7 | version = "5.2.0" 8 | description = "Detect backward incompatible migrations for your django project" 9 | authors = [ 10 | { name="3YOURMIND GmbH", email="fb@3yourmind.com" }, 11 | ] 12 | maintainers = [{name = "David Wobrock", email = "david.wobrock@gmail.com"}] 13 | license = {text = "Apache-2.0"} 14 | readme = "README.md" 15 | requires-python = ">=3.9" 16 | dependencies = [ 17 | "django>=2.2", 18 | "appdirs>=1.4.3", 19 | "toml>=0.10.2", 20 | ] 21 | classifiers = [ 22 | "Development Status :: 5 - Production/Stable", 23 | "Intended Audience :: Developers", 24 | "Environment :: Web Environment", 25 | "Framework :: Django", 26 | "Framework :: Django :: 3.2", 27 | "Framework :: Django :: 4.0", 28 | "Framework :: Django :: 4.1", 29 | "Framework :: Django :: 4.2", 30 | "Framework :: Django :: 5.0", 31 | "Framework :: Django :: 5.1", 32 | "Framework :: Django :: 5.2", 33 | "Programming Language :: Python", 34 | "Programming Language :: Python :: 3", 35 | "Programming Language :: Python :: 3.9", 36 | "Programming Language :: Python :: 3.10", 37 | "Programming Language :: Python :: 3.11", 38 | "Programming Language :: Python :: 3.12", 39 | "Programming Language :: Python :: 3.13", 40 | ] 41 | keywords = [ 42 | "django", 43 | "migration", 44 | "lint", 45 | "linter", 46 | "database", 47 | "backward", 48 | "compatibility", 49 | ] 50 | 51 | [project.urls] 52 | Changelog = "https://github.com/3YOURMIND/django-migration-linter/blob/main/CHANGELOG.md" 53 | Repository = "https://github.com/3YOURMIND/django-migration-linter" 54 | 55 | [tool.setuptools.package-data] 56 | django_migration_linter = ['py.typed'] 57 | 58 | [project.optional-dependencies] 59 | test = [ 60 | "tox>=4.6.3", 61 | "mysqlclient>=2.1.1", 62 | "psycopg2>=2.9.6", 63 | "django_add_default_value>=0.4.0", 64 | "coverage>=7.2.7", 65 | ] 66 | 67 | [tool.isort] 68 | multi_line_output = 3 69 | include_trailing_comma = "True" 70 | force_grid_wrap = 0 71 | use_parentheses = "True" 72 | ensure_newline_before_comments = "True" 73 | line_length = 88 74 | add_imports = [ "from __future__ import annotations" ] 75 | -------------------------------------------------------------------------------- /src/django_migration_linter/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from .migration_linter import * # noqa 4 | from .operations import * # noqa 5 | -------------------------------------------------------------------------------- /src/django_migration_linter/cache.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import pickle 5 | 6 | 7 | class Cache(dict): 8 | def __init__(self, django_folder: str | None, database: str, cache_path: str): 9 | self.filename = os.path.join( 10 | cache_path, 11 | "{}_{}.pickle".format(str(django_folder).replace(os.sep, "_"), database), 12 | ) 13 | 14 | if not os.path.exists(os.path.dirname(self.filename)): 15 | os.makedirs(os.path.dirname(self.filename)) 16 | 17 | super().__init__() 18 | 19 | def load(self) -> None: 20 | try: 21 | with open(self.filename, "rb") as f: 22 | tmp_dict = pickle.load(f) 23 | self.update(tmp_dict) 24 | except OSError: 25 | pass 26 | 27 | def save(self) -> None: 28 | with open(self.filename, "wb") as f: 29 | pickle.dump(self, f, protocol=2) 30 | -------------------------------------------------------------------------------- /src/django_migration_linter/constants.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from appdirs import user_cache_dir 4 | 5 | __version__ = "5.2.0" 6 | 7 | DEFAULT_CACHE_PATH = user_cache_dir("django-migration-linter", version=__version__) 8 | 9 | DJANGO_APPS_WITH_MIGRATIONS = ("admin", "auth", "contenttypes", "sessions") 10 | EXPECTED_DATA_MIGRATION_ARGS = ("apps", "schema_editor") 11 | -------------------------------------------------------------------------------- /src/django_migration_linter/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/src/django_migration_linter/management/__init__.py -------------------------------------------------------------------------------- /src/django_migration_linter/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/src/django_migration_linter/management/commands/__init__.py -------------------------------------------------------------------------------- /src/django_migration_linter/management/commands/lintmigrations.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import configparser 4 | import itertools 5 | import os 6 | import sys 7 | from importlib import import_module 8 | from typing import Any, Callable 9 | 10 | import toml 11 | from django.conf import settings 12 | from django.core.management.base import BaseCommand, CommandParser 13 | 14 | from ...constants import __version__ 15 | from ...migration_linter import MessageType, MigrationLinter 16 | from ..utils import ( 17 | configure_logging, 18 | extract_warnings_as_errors_option, 19 | register_linting_configuration_options, 20 | ) 21 | 22 | CONFIG_NAME = "django_migration_linter" 23 | PYPROJECT_TOML = "pyproject.toml" 24 | DEFAULT_CONFIG_FILES = ( 25 | f".{CONFIG_NAME}.cfg", 26 | "setup.cfg", 27 | "tox.ini", 28 | ) 29 | 30 | 31 | class Command(BaseCommand): 32 | help = "Lint your migrations" 33 | 34 | def add_arguments(self, parser: CommandParser) -> None: 35 | parser.add_argument( 36 | "app_label", 37 | nargs="?", 38 | type=str, 39 | help="App label of an application to lint migrations.", 40 | ) 41 | parser.add_argument( 42 | "migration_name", 43 | nargs="?", 44 | type=str, 45 | help="Linting will only be done on that migration only.", 46 | ) 47 | parser.add_argument( 48 | "--git-commit-id", 49 | type=str, 50 | nargs="?", 51 | help=( 52 | "if specified, only migrations since this commit " 53 | "will be taken into account" 54 | ), 55 | ) 56 | parser.add_argument( 57 | "--ignore-name-contains", 58 | type=str, 59 | nargs="?", 60 | help="ignore migrations containing this name", 61 | ) 62 | parser.add_argument( 63 | "--ignore-name", 64 | type=str, 65 | nargs="*", 66 | help="ignore migrations with exactly one of these names", 67 | ) 68 | parser.add_argument( 69 | "--include-name-contains", 70 | type=str, 71 | nargs="?", 72 | help="only consider migrations containing this name", 73 | ) 74 | parser.add_argument( 75 | "--include-name", 76 | type=str, 77 | nargs="*", 78 | help="only consider migrations with exactly one of these names", 79 | ) 80 | parser.add_argument( 81 | "--project-root-path", type=str, nargs="?", help="django project root path" 82 | ) 83 | parser.add_argument( 84 | "--include-migrations-from", 85 | metavar="FILE_PATH", 86 | type=str, 87 | nargs="?", 88 | help="if specified, only migrations listed in the file will be considered", 89 | ) 90 | cache_group = parser.add_mutually_exclusive_group(required=False) 91 | cache_group.add_argument( 92 | "--cache-path", 93 | type=str, 94 | help="specify a directory that should be used to store cache-files in.", 95 | ) 96 | cache_group.add_argument( 97 | "--no-cache", action="store_true", help="don't use a cache" 98 | ) 99 | 100 | incl_excl_group = parser.add_mutually_exclusive_group(required=False) 101 | incl_excl_group.add_argument( 102 | "--include-apps", 103 | type=str, 104 | nargs="*", 105 | help="check only migrations that are in the specified django apps", 106 | ) 107 | incl_excl_group.add_argument( 108 | "--exclude-apps", 109 | type=str, 110 | nargs="*", 111 | help="ignore migrations that are in the specified django apps", 112 | ) 113 | 114 | applied_unapplied_migrations_group = parser.add_mutually_exclusive_group( 115 | required=False 116 | ) 117 | applied_unapplied_migrations_group.add_argument( 118 | "--unapplied-migrations", 119 | action="store_true", 120 | help="check only migrations have not been applied to the database yet", 121 | ) 122 | applied_unapplied_migrations_group.add_argument( 123 | "--applied-migrations", 124 | action="store_true", 125 | help="check only migrations that have already been applied to the database", 126 | ) 127 | 128 | parser.add_argument( 129 | "-q", 130 | "--quiet", 131 | nargs="+", 132 | choices=MessageType.values(), 133 | help="don't print linting messages to stdout", 134 | ) 135 | register_linting_configuration_options(parser) 136 | 137 | def handle(self, *args, **options): 138 | django_settings_options = self.read_django_settings(options) 139 | config_options = self.read_config_file(options) 140 | toml_options = self.read_toml_file(options) 141 | for k, v in itertools.chain( 142 | django_settings_options.items(), 143 | config_options.items(), 144 | toml_options.items(), 145 | ): 146 | if not options[k]: 147 | options[k] = v 148 | 149 | ( 150 | warnings_as_errors_tests, 151 | all_warnings_as_errors, 152 | ) = extract_warnings_as_errors_option(options["warnings_as_errors"]) 153 | 154 | configure_logging(options["verbosity"]) 155 | 156 | root_path = options["project_root_path"] or os.path.dirname( 157 | import_module(os.getenv("DJANGO_SETTINGS_MODULE")).__file__ 158 | ) 159 | linter = MigrationLinter( 160 | root_path, 161 | ignore_name_contains=options["ignore_name_contains"], 162 | ignore_name=options["ignore_name"], 163 | include_name_contains=options["include_name_contains"], 164 | include_name=options["include_name"], 165 | include_apps=options["include_apps"], 166 | exclude_apps=options["exclude_apps"], 167 | database=options["database"], 168 | cache_path=options["cache_path"], 169 | no_cache=options["no_cache"], 170 | only_applied_migrations=options["applied_migrations"], 171 | only_unapplied_migrations=options["unapplied_migrations"], 172 | exclude_migration_tests=options["exclude_migration_tests"], 173 | quiet=options["quiet"], 174 | warnings_as_errors_tests=warnings_as_errors_tests, 175 | all_warnings_as_errors=all_warnings_as_errors, 176 | no_output=options["verbosity"] == 0, 177 | analyser_string=options["sql_analyser"], 178 | ignore_sqlmigrate_errors=options["ignore_sqlmigrate_errors"], 179 | ignore_initial_migrations=options["ignore_initial_migrations"], 180 | ) 181 | linter.lint_all_migrations( 182 | app_label=options["app_label"], 183 | migration_name=options["migration_name"], 184 | git_commit_id=options["git_commit_id"], 185 | migrations_file_path=options["include_migrations_from"], 186 | ) 187 | linter.print_summary() 188 | if linter.has_errors: 189 | sys.exit(1) 190 | 191 | @staticmethod 192 | def read_django_settings(options: dict[str, Any]) -> dict[str, Any]: 193 | django_settings_options = dict() 194 | 195 | django_migration_linter_settings = getattr( 196 | settings, "MIGRATION_LINTER_OPTIONS", dict() 197 | ) 198 | for key in options: 199 | if key in django_migration_linter_settings: 200 | django_settings_options[key] = django_migration_linter_settings[key] 201 | 202 | return django_settings_options 203 | 204 | @staticmethod 205 | def read_config_file(options: dict[str, Any]) -> dict[str, Any]: 206 | config_options = dict() 207 | 208 | config_parser = configparser.ConfigParser() 209 | config_parser.read(DEFAULT_CONFIG_FILES, encoding="utf-8") 210 | for key, value in options.items(): 211 | config_get_fn: Callable 212 | if isinstance(value, bool): 213 | config_get_fn = config_parser.getboolean 214 | else: 215 | config_get_fn = config_parser.get 216 | 217 | config_value = config_get_fn(CONFIG_NAME, key, fallback=None) 218 | if config_value is not None: 219 | config_options[key] = config_value 220 | return config_options 221 | 222 | @staticmethod 223 | def read_toml_file(options: dict[str, Any]) -> dict[str, Any]: 224 | toml_options = dict() 225 | 226 | if os.path.exists(PYPROJECT_TOML): 227 | pyproject_toml = toml.load(PYPROJECT_TOML) 228 | section = pyproject_toml.get("tool", {}).get(CONFIG_NAME, {}) 229 | for key in options: 230 | if key in section: 231 | toml_options[key] = section[key] 232 | 233 | return toml_options 234 | 235 | def get_version(self) -> str: 236 | return __version__ 237 | -------------------------------------------------------------------------------- /src/django_migration_linter/management/commands/makemigrations.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | 5 | from django.conf import settings 6 | from django.core.management import CommandParser 7 | from django.core.management.commands.makemigrations import ( 8 | Command as MakeMigrationsCommand, 9 | ) 10 | from django.db.migrations import Migration 11 | from django.db.migrations.questioner import InteractiveMigrationQuestioner 12 | from django.db.migrations.writer import MigrationWriter 13 | 14 | from django_migration_linter import MigrationLinter 15 | 16 | from ..utils import ( 17 | configure_logging, 18 | extract_warnings_as_errors_option, 19 | register_linting_configuration_options, 20 | ) 21 | 22 | 23 | def ask_should_keep_migration() -> bool: 24 | questioner = InteractiveMigrationQuestioner() 25 | msg = """ 26 | The migration linter detected that this migration is not backward compatible. 27 | - If you keep the migration, you will want to fix the issue or ignore the migration. 28 | - By default, the newly created migration file will be deleted. 29 | Do you want to keep the migration? [y/N]""" 30 | return questioner._boolean_input(msg, False) 31 | 32 | 33 | def default_should_keep_migration(): 34 | return False 35 | 36 | 37 | class Command(MakeMigrationsCommand): 38 | help = "Creates new migration(s) for apps and lints them." 39 | 40 | def add_arguments(self, parser: CommandParser) -> None: 41 | super().add_arguments(parser) 42 | parser.add_argument( 43 | "--lint", 44 | action="store_true", 45 | help="Lint newly generated migrations.", 46 | ) 47 | register_linting_configuration_options(parser) 48 | 49 | def handle(self, *app_labels, **options): 50 | self.lint = options["lint"] 51 | self.database = options["database"] 52 | self.exclude_migrations_tests = options["exclude_migration_tests"] 53 | self.warnings_as_errors = options["warnings_as_errors"] 54 | self.sql_analyser = options["sql_analyser"] 55 | self.ignore_sqlmigrate_errors = options["ignore_sqlmigrate_errors"] 56 | configure_logging(options["verbosity"]) 57 | return super().handle(*app_labels, **options) 58 | 59 | def write_migration_files(self, changes: dict[str, list[Migration]]) -> None: 60 | super().write_migration_files(changes) 61 | 62 | if ( 63 | not getattr(settings, "MIGRATION_LINTER_OVERRIDE_MAKEMIGRATIONS", False) 64 | and not self.lint 65 | ): 66 | return 67 | 68 | if self.dry_run: 69 | """ 70 | Since we rely on the 'sqlmigrate' to lint the migrations, we can only 71 | lint if the migration files have been generated. Since the 'dry-run' 72 | option won't generate the files, we cannot lint migrations. 73 | """ 74 | return 75 | 76 | should_keep_migration = ( 77 | ask_should_keep_migration 78 | if self.interactive 79 | else default_should_keep_migration 80 | ) 81 | 82 | ( 83 | warnings_as_errors_tests, 84 | all_warnings_as_errors, 85 | ) = extract_warnings_as_errors_option(self.warnings_as_errors) 86 | 87 | # Lint migrations. 88 | linter = MigrationLinter( 89 | path=os.environ["DJANGO_SETTINGS_MODULE"], 90 | database=self.database, 91 | no_cache=True, 92 | exclude_migration_tests=self.exclude_migrations_tests, 93 | warnings_as_errors_tests=warnings_as_errors_tests, 94 | all_warnings_as_errors=all_warnings_as_errors, 95 | analyser_string=self.sql_analyser, 96 | ignore_sqlmigrate_errors=self.ignore_sqlmigrate_errors, 97 | ) 98 | 99 | for app_label, app_migrations in changes.items(): 100 | if self.verbosity >= 1: 101 | self.stdout.write( 102 | self.style.MIGRATE_HEADING("Linting for '%s':" % app_label) + "\n" 103 | ) 104 | 105 | for migration in app_migrations: 106 | linter.lint_migration(migration) 107 | if linter.has_errors: 108 | if not should_keep_migration(): 109 | self.delete_migration(migration) 110 | linter.reset_counters() 111 | 112 | def delete_migration(self, migration: Migration) -> None: 113 | writer = MigrationWriter(migration) 114 | os.remove(writer.path) 115 | 116 | if self.verbosity >= 1: 117 | try: 118 | migration_string = os.path.relpath(writer.path) 119 | except ValueError: 120 | migration_string = writer.path 121 | if migration_string.startswith(".."): 122 | migration_string = writer.path 123 | self.stdout.write( 124 | "Deleted %s\n" % (self.style.MIGRATE_LABEL(migration_string)) 125 | ) 126 | -------------------------------------------------------------------------------- /src/django_migration_linter/management/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | 5 | from django.core.management import CommandParser 6 | 7 | from ..sql_analyser.analyser import ANALYSER_STRING_MAPPING 8 | 9 | 10 | def register_linting_configuration_options(parser: CommandParser) -> None: 11 | parser.add_argument( 12 | "--database", 13 | type=str, 14 | nargs="?", 15 | help=( 16 | "specify the database for which to generate the SQL. Defaults to default" 17 | ), 18 | ) 19 | 20 | parser.add_argument( 21 | "--exclude-migration-tests", 22 | type=str, 23 | nargs="*", 24 | help="Specify backward incompatible migration tests " 25 | "to be ignored (e.g. ALTER_COLUMN)", 26 | ) 27 | 28 | parser.add_argument( 29 | "--warnings-as-errors", 30 | type=str, 31 | nargs="*", 32 | help="handle warnings as errors. Optionally specify the tests to handle as " 33 | "errors (e.g. RUNPYTHON_REVERSIBLE)", 34 | ) 35 | 36 | parser.add_argument( 37 | "--sql-analyser", 38 | nargs="?", 39 | choices=list(ANALYSER_STRING_MAPPING.keys()), 40 | help="select the SQL analyser", 41 | ) 42 | 43 | parser.add_argument( 44 | "--ignore-sqlmigrate-errors", 45 | action="store_true", 46 | help="ignore failures of sqlmigrate command", 47 | ) 48 | 49 | parser.add_argument( 50 | "--ignore-initial-migrations", 51 | action="store_true", 52 | help="ignore initial migrations", 53 | ) 54 | 55 | 56 | def configure_logging(verbosity: int) -> None: 57 | logger = logging.getLogger("django_migration_linter") 58 | 59 | if verbosity > 1: 60 | logging.basicConfig(format="%(message)s", level=logging.DEBUG) 61 | elif verbosity == 0: 62 | logger.disabled = True 63 | else: 64 | logging.basicConfig(format="%(message)s") 65 | 66 | 67 | def extract_warnings_as_errors_option( 68 | warnings_as_errors: list[str] | None, 69 | ) -> tuple[list[str] | None, bool]: 70 | if isinstance(warnings_as_errors, list): 71 | warnings_as_errors_tests = warnings_as_errors 72 | # If the option is specified but without any test codes, 73 | # all warnings become errors 74 | all_warnings_as_errors = len(warnings_as_errors) == 0 75 | else: 76 | warnings_as_errors_tests = None 77 | all_warnings_as_errors = False 78 | 79 | return warnings_as_errors_tests, all_warnings_as_errors 80 | -------------------------------------------------------------------------------- /src/django_migration_linter/operations.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db.migrations.operations.base import Operation 4 | 5 | 6 | class IgnoreMigration(Operation): 7 | """ 8 | No-op migration operation that will enable the Django Migration Linter 9 | to detect if the entire migration should be ignored (through code). 10 | """ 11 | 12 | reversible = True 13 | reduces_to_sql = False 14 | elidable = True 15 | 16 | def state_forwards(self, app_label, state): 17 | pass 18 | 19 | def database_forwards(self, app_label, schema_editor, from_state, to_state): 20 | pass 21 | 22 | def database_backwards(self, app_label, schema_editor, from_state, to_state): 23 | pass 24 | 25 | def describe(self): 26 | return "The Django migration linter will ignore this migration" 27 | -------------------------------------------------------------------------------- /src/django_migration_linter/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/src/django_migration_linter/py.typed -------------------------------------------------------------------------------- /src/django_migration_linter/sql_analyser/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from .base import BaseAnalyser # noqa 4 | from .mysql import MySqlAnalyser # noqa 5 | from .postgresql import PostgresqlAnalyser # noqa 6 | from .sqlite import SqliteAnalyser # noqa 7 | 8 | from .analyser import analyse_sql_statements, get_sql_analyser_class # noqa isort:skip 9 | -------------------------------------------------------------------------------- /src/django_migration_linter/sql_analyser/analyser.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from typing import TYPE_CHECKING, Iterable, Type 5 | 6 | if TYPE_CHECKING: 7 | from sql_analyser.base import Issue 8 | 9 | from django_migration_linter.sql_analyser import ( 10 | BaseAnalyser, 11 | MySqlAnalyser, 12 | PostgresqlAnalyser, 13 | SqliteAnalyser, 14 | ) 15 | 16 | logger = logging.getLogger("django_migration_linter") 17 | 18 | ANALYSER_STRING_MAPPING: dict[str, Type[BaseAnalyser]] = { 19 | "sqlite": SqliteAnalyser, 20 | "mysql": MySqlAnalyser, 21 | "postgresql": PostgresqlAnalyser, 22 | } 23 | 24 | 25 | def get_sql_analyser_class( 26 | database_vendor: str, analyser_string: str | None = None 27 | ) -> Type[BaseAnalyser]: 28 | if analyser_string: 29 | return get_sql_analyser_from_string(analyser_string) 30 | return get_sql_analyser_class_from_db_vendor(database_vendor) 31 | 32 | 33 | def get_sql_analyser_from_string(analyser_string: str) -> Type[BaseAnalyser]: 34 | if analyser_string not in ANALYSER_STRING_MAPPING: 35 | raise ValueError( 36 | "Unknown SQL analyser '{}'. Known values: '{}'".format( 37 | analyser_string, 38 | "','".join(ANALYSER_STRING_MAPPING.keys()), 39 | ) 40 | ) 41 | return ANALYSER_STRING_MAPPING[analyser_string] 42 | 43 | 44 | def get_sql_analyser_class_from_db_vendor(database_vendor: str) -> Type[BaseAnalyser]: 45 | sql_analyser_class: Type[BaseAnalyser] 46 | if "mysql" in database_vendor: 47 | sql_analyser_class = MySqlAnalyser 48 | elif "postgre" in database_vendor: 49 | sql_analyser_class = PostgresqlAnalyser 50 | elif "sqlite" in database_vendor: 51 | sql_analyser_class = SqliteAnalyser 52 | else: 53 | raise ValueError( 54 | "Unsupported database vendor '{}'. Try specifying an SQL analyser.".format( 55 | database_vendor 56 | ) 57 | ) 58 | 59 | logger.debug("Chosen SQL analyser class: %s", sql_analyser_class) 60 | return sql_analyser_class 61 | 62 | 63 | def analyse_sql_statements( 64 | sql_analyser_class: Type[BaseAnalyser], 65 | sql_statements: list[str], 66 | exclude_migration_tests: Iterable[str] | None = None, 67 | ) -> tuple[list[Issue], list[Issue], list[Issue]]: 68 | sql_analyser = sql_analyser_class(exclude_migration_tests) 69 | sql_analyser.analyse(sql_statements) 70 | return sql_analyser.errors, sql_analyser.ignored, sql_analyser.warnings 71 | -------------------------------------------------------------------------------- /src/django_migration_linter/sql_analyser/base.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | import re 5 | from copy import deepcopy 6 | from dataclasses import dataclass 7 | from enum import Enum 8 | from typing import Callable, Iterable 9 | 10 | logger = logging.getLogger("django_migration_linter") 11 | 12 | 13 | def find_check_from_code(checks: list[Check], code: str) -> Check | None: 14 | return next((c for c in checks if c.code == code), None) 15 | 16 | 17 | def update_migration_checks( 18 | base_checks: list[Check], specific_checks: list[Check] 19 | ) -> list[Check]: 20 | new_checks = deepcopy(base_checks) 21 | for override_check in specific_checks: 22 | migration_check = find_check_from_code(new_checks, override_check.code) 23 | 24 | if migration_check is None or not override_check.code: 25 | migration_check = deepcopy(override_check) 26 | new_checks.append(migration_check) 27 | 28 | for field in override_check.__dataclass_fields__: 29 | setattr(migration_check, field, getattr(override_check, field)) 30 | return new_checks 31 | 32 | 33 | def has_not_null_column(sql_statements: list[str], **kwargs) -> bool: 34 | # TODO: improve to detect that the same column is concerned 35 | not_null_column = False 36 | has_default_value = False 37 | 38 | for sql in sql_statements: 39 | if re.search("(? bool: 56 | regex_result = None 57 | for sql in sql_statements: 58 | regex_result = re.search( 59 | "ALTER TABLE (.*) ADD CONSTRAINT .* UNIQUE", sql 60 | ) or re.search('CREATE UNIQUE INDEX .* ON (".*?")', sql) 61 | if regex_result: 62 | break 63 | if not regex_result: 64 | return False 65 | 66 | concerned_table = regex_result.group(1) 67 | table_is_added_in_transaction = any( 68 | sql.startswith(f"CREATE TABLE {concerned_table}") for sql in sql_statements 69 | ) 70 | return not table_is_added_in_transaction 71 | 72 | 73 | class CheckMode(Enum): 74 | """ 75 | Defines whether the Check.fn gets a str or a list[str] as first parameter. 76 | """ 77 | 78 | ONE_LINER = 1 79 | TRANSACTION = 2 80 | 81 | 82 | class CheckType(Enum): 83 | ERROR = 1 84 | WARNING = 2 85 | 86 | 87 | @dataclass 88 | class Check: 89 | """ 90 | Represents a check that will be done against SQL statement(s). 91 | """ 92 | 93 | code: str 94 | fn: Callable 95 | message: str 96 | mode: CheckMode 97 | type: CheckType 98 | 99 | 100 | @dataclass 101 | class Issue: 102 | code: str 103 | message: str 104 | table: str | None = None 105 | column: str | None = None 106 | 107 | 108 | class BaseAnalyser: 109 | base_migration_checks: list[Check] = [ 110 | Check( 111 | code="RENAME_TABLE", 112 | fn=lambda sql, **kw: re.search("RENAME TABLE", sql) 113 | or re.search("ALTER TABLE .* RENAME TO", sql), 114 | message="RENAMING tables", 115 | mode=CheckMode.ONE_LINER, 116 | type=CheckType.ERROR, 117 | ), 118 | Check( 119 | code="NOT_NULL", 120 | fn=has_not_null_column, 121 | message="NOT NULL constraint on columns", 122 | mode=CheckMode.TRANSACTION, 123 | type=CheckType.ERROR, 124 | ), 125 | Check( 126 | code="DROP_COLUMN", 127 | fn=lambda sql, **kw: re.search("DROP COLUMN", sql), 128 | message="DROPPING columns", 129 | mode=CheckMode.ONE_LINER, 130 | type=CheckType.ERROR, 131 | ), 132 | Check( 133 | code="DROP_TABLE", 134 | fn=lambda sql, **kw: sql.startswith("DROP TABLE"), 135 | message="DROPPING table", 136 | mode=CheckMode.ONE_LINER, 137 | type=CheckType.ERROR, 138 | ), 139 | Check( 140 | code="RENAME_COLUMN", 141 | fn=lambda sql, **kw: re.search("ALTER TABLE .* CHANGE", sql) 142 | or re.search("ALTER TABLE .* RENAME COLUMN", sql), 143 | message="RENAMING columns", 144 | mode=CheckMode.ONE_LINER, 145 | type=CheckType.ERROR, 146 | ), 147 | Check( 148 | code="ALTER_COLUMN", 149 | fn=lambda sql, **kw: re.search("ALTER TABLE .* ALTER COLUMN .* TYPE", sql), 150 | message=( 151 | "ALTERING columns (Could be backward compatible. " 152 | "You may ignore this migration.)" 153 | ), 154 | mode=CheckMode.ONE_LINER, 155 | type=CheckType.ERROR, 156 | ), 157 | Check( 158 | code="ADD_UNIQUE", 159 | fn=has_add_unique, 160 | message="ADDING unique constraint", 161 | mode=CheckMode.TRANSACTION, 162 | type=CheckType.ERROR, 163 | ), 164 | ] 165 | 166 | migration_checks: list[Check] = [] 167 | 168 | def __init__(self, exclude_migration_tests: Iterable[str] | None): 169 | self.exclude_migration_tests: Iterable[str] = exclude_migration_tests or [] 170 | self.errors: list[Issue] = [] 171 | self.warnings: list[Issue] = [] 172 | self.ignored: list[Issue] = [] 173 | self.migration_checks = update_migration_checks( 174 | self.base_migration_checks, self.migration_checks 175 | ) 176 | 177 | def analyse(self, sql_statements: list[str]) -> None: 178 | for statement in sql_statements: 179 | for test in self.one_line_migration_checks: 180 | self._check_sql(test, sql=statement) 181 | 182 | for test in self.transaction_migration_checks: 183 | self._check_sql(test, sql=sql_statements) 184 | 185 | @property 186 | def one_line_migration_checks(self) -> Iterable[Check]: 187 | return (c for c in self.migration_checks if c.mode == CheckMode.ONE_LINER) 188 | 189 | @property 190 | def transaction_migration_checks(self) -> Iterable[Check]: 191 | return (c for c in self.migration_checks if c.mode == CheckMode.TRANSACTION) 192 | 193 | def _check_sql(self, check: Check, sql: list[str] | str) -> None: 194 | if check.fn(sql, errors=self.errors): 195 | if check.code in self.exclude_migration_tests: 196 | action = "IGNORED" 197 | list_to_add = self.ignored 198 | elif check.type == CheckType.WARNING: 199 | action = "WARNING" 200 | list_to_add = self.warnings 201 | else: 202 | action = "ERROR" 203 | list_to_add = self.errors 204 | logger.debug("Testing %s -- %s", sql, action) 205 | issue = self.build_issue(migration_check=check, sql_statement=sql) 206 | list_to_add.append(issue) 207 | else: 208 | logger.debug("Testing %s -- PASSED", sql) 209 | 210 | def build_issue( 211 | self, migration_check: Check, sql_statement: list[str] | str 212 | ) -> Issue: 213 | table = self.detect_table(sql_statement) 214 | col = self.detect_column(sql_statement) 215 | return Issue( 216 | code=migration_check.code, 217 | message=migration_check.message, 218 | table=table, 219 | column=col, 220 | ) 221 | 222 | @staticmethod 223 | def detect_table(sql: list[str] | str) -> str | None: 224 | if isinstance(sql, str): 225 | regex_result = re.search("TABLE [`\"'](.*?)[`\"']", sql, re.IGNORECASE) 226 | if regex_result: 227 | return regex_result.group(1) 228 | return None 229 | 230 | @staticmethod 231 | def detect_column(sql: list[str] | str) -> str | None: 232 | if isinstance(sql, str): 233 | regex_result = re.search("COLUMN [`\"'](.*?)[`\"']", sql, re.IGNORECASE) 234 | if regex_result: 235 | return regex_result.group(1) 236 | return None 237 | -------------------------------------------------------------------------------- /src/django_migration_linter/sql_analyser/mysql.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import re 4 | 5 | from .base import BaseAnalyser, Check, CheckMode, CheckType 6 | 7 | 8 | class MySqlAnalyser(BaseAnalyser): 9 | migration_checks: list[Check] = [ 10 | Check( 11 | code="ALTER_COLUMN", 12 | fn=lambda sql, **kw: re.search("ALTER TABLE .* MODIFY .* (?!NULL);?$", sql), 13 | message=( 14 | "ALTERING columns (Could be backward compatible. " 15 | "You may ignore this migration.)" 16 | ), 17 | mode=CheckMode.ONE_LINER, 18 | type=CheckType.ERROR, 19 | ), 20 | ] 21 | 22 | @staticmethod 23 | def detect_column(sql: list[str] | str) -> str | None: 24 | if isinstance(sql, str): 25 | regex_result = re.search("COLUMN [`\"'](.*?)[`\"']", sql, re.IGNORECASE) 26 | if regex_result: 27 | return regex_result.group(1) 28 | regex_result = re.search("MODIFY [`\"'](.*?)[`\"']", sql, re.IGNORECASE) 29 | if regex_result: 30 | return regex_result.group(1) 31 | return None 32 | -------------------------------------------------------------------------------- /src/django_migration_linter/sql_analyser/postgresql.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import re 4 | 5 | from .base import BaseAnalyser, Check, CheckMode, CheckType 6 | 7 | 8 | def has_create_index_in_transaction(sql_statements: list[str], **kwargs) -> bool: 9 | """Return if a migration opens a transaction, acquires EXCLUSIVE lock, then indexes. 10 | 11 | Any locks that are obtained after a transaction is opened will not be released 12 | until that transaction either commits or rolls back. 13 | 14 | Accordingly, it's extremely important that a migration avoid any long-running 15 | queries while exclusive locks are held. 16 | 17 | Building an index is generally a long-running operation. A standard index 18 | creation (that is, avoiding use of `CONCURRENTLY`) can be safe to run on 19 | tables which are small in size and/or read-heavy. (`CREATE INDEX` only 20 | prevents writes to a table; reads are allowed during index creation). 21 | 22 | This check is a stricter version of `CREATE_INDEX` -- if a team wishes 23 | to build indices nonconcurrently, it's imperative to be mindful of locks. 24 | """ 25 | if not (sql_statements and sql_statements[0].startswith("BEGIN")): 26 | return False 27 | 28 | for i, sql in enumerate(sql_statements): 29 | # If any statements acquire an exclusive lock, complain about index creation 30 | # later. 31 | # Nearly every single `ALTER TABLE` command requires an exclusive lock: 32 | # https://www.postgresql.org/docs/current/sql-altertable.html 33 | # (Most common example is `ALTER TABLE... ADD COLUMN`, then later 34 | # `CREATE INDEX`) 35 | if sql.startswith("ALTER TABLE"): 36 | return has_create_index(sql_statements, ignore_concurrently=False) 37 | return False 38 | 39 | 40 | def has_create_index( 41 | sql_statements: list[str], ignore_concurrently: bool = True, **kwargs 42 | ) -> bool: 43 | regex_result = None 44 | for i, sql in enumerate(sql_statements): 45 | regex_result = re.search(r"CREATE (UNIQUE )?INDEX.*ON (.*) \(", sql) 46 | if ignore_concurrently and re.search("INDEX CONCURRENTLY", sql): 47 | regex_result = None 48 | if regex_result: 49 | break 50 | if not regex_result: 51 | return False 52 | 53 | preceding_sql_statements = sql_statements[:i] 54 | concerned_table = regex_result.group(2) 55 | table_is_added_in_transaction = any( 56 | sql.startswith(f"CREATE TABLE {concerned_table}") 57 | for sql in preceding_sql_statements 58 | ) 59 | return not table_is_added_in_transaction 60 | 61 | 62 | class PostgresqlAnalyser(BaseAnalyser): 63 | migration_checks: list[Check] = [ 64 | Check( 65 | code="CREATE_INDEX", 66 | fn=has_create_index, 67 | message="CREATE INDEX locks table", 68 | mode=CheckMode.TRANSACTION, 69 | type=CheckType.WARNING, 70 | ), 71 | Check( 72 | code="CREATE_INDEX_EXCLUSIVE", 73 | fn=has_create_index_in_transaction, 74 | message="CREATE INDEX prolongs transaction, delaying lock release", 75 | mode=CheckMode.TRANSACTION, 76 | type=CheckType.WARNING, 77 | ), 78 | Check( 79 | code="DROP_INDEX", 80 | fn=lambda sql, **kw: re.search("DROP INDEX", sql) 81 | and not re.search("INDEX CONCURRENTLY", sql), 82 | message="DROP INDEX locks table", 83 | mode=CheckMode.ONE_LINER, 84 | type=CheckType.WARNING, 85 | ), 86 | Check( 87 | code="REINDEX", 88 | fn=lambda sql, **kw: sql.startswith("REINDEX"), 89 | message="REINDEX locks table", 90 | mode=CheckMode.ONE_LINER, 91 | type=CheckType.WARNING, 92 | ), 93 | ] 94 | -------------------------------------------------------------------------------- /src/django_migration_linter/sql_analyser/sqlite.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import re 4 | 5 | from .base import BaseAnalyser, Check, CheckMode, CheckType 6 | 7 | 8 | class SqliteAnalyser(BaseAnalyser): 9 | migration_checks: list[Check] = [ 10 | Check( 11 | code="RENAME_TABLE", 12 | fn=lambda sql, **kw: re.search("ALTER TABLE .* RENAME TO", sql) 13 | and "__old" not in sql 14 | and "new__" not in sql, 15 | message="RENAMING tables", 16 | mode=CheckMode.ONE_LINER, 17 | type=CheckType.ERROR, 18 | ), 19 | Check( 20 | code="DROP_TABLE", 21 | # TODO: improve to detect that the table names overlap 22 | fn=lambda sql_statements, **kw: any( 23 | sql.startswith("DROP TABLE") for sql in sql_statements 24 | ) 25 | and not any(sql.startswith("CREATE TABLE") for sql in sql_statements), 26 | message="DROPPING table", 27 | mode=CheckMode.TRANSACTION, 28 | type=CheckType.ERROR, 29 | ), 30 | Check( 31 | code="NOT_NULL", 32 | fn=lambda sql_statements, **kw: any( 33 | re.search("NOT NULL(?! PRIMARY)(?! DEFAULT)", sql) 34 | for sql in sql_statements 35 | ) 36 | and any( 37 | re.search("ALTER TABLE .* RENAME TO", sql) 38 | and ("__old" in sql or "new__" in sql) 39 | for sql in sql_statements 40 | ), 41 | message="NOT NULL constraint on columns", 42 | mode=CheckMode.TRANSACTION, 43 | type=CheckType.ERROR, 44 | ), 45 | ] 46 | 47 | @staticmethod 48 | def detect_table(sql: list[str] | str) -> str | None: 49 | if isinstance(sql, str): 50 | regex_result = re.search("TABLE [`\"'](.*?)[`\"']", sql, re.IGNORECASE) 51 | if regex_result: 52 | return regex_result.group(1) 53 | regex_result = re.search("ON [`\"'](.*?)[`\"']", sql, re.IGNORECASE) 54 | if regex_result: 55 | return regex_result.group(1) 56 | return None 57 | -------------------------------------------------------------------------------- /src/django_migration_linter/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | from importlib import import_module 5 | 6 | 7 | def split_path(path: str) -> list[str]: 8 | decomposed_path: list[str] = [] 9 | while 1: 10 | head, tail = os.path.split(path) 11 | if head == path: # sentinel for absolute paths 12 | decomposed_path.insert(0, head) 13 | break 14 | elif tail == path: # sentinel for relative paths 15 | decomposed_path.insert(0, tail) 16 | break 17 | else: 18 | path = head 19 | decomposed_path.insert(0, tail) 20 | 21 | if not decomposed_path[-1]: 22 | decomposed_path = decomposed_path[:-1] 23 | return decomposed_path 24 | 25 | 26 | def split_migration_path(migration_path: str) -> tuple[str, str]: 27 | from django.db.migrations.loader import MIGRATIONS_MODULE_NAME 28 | 29 | decomposed_path = split_path(migration_path) 30 | for i, p in enumerate(decomposed_path): 31 | if p == MIGRATIONS_MODULE_NAME: 32 | return decomposed_path[i - 1], os.path.splitext(decomposed_path[i + 1])[0] 33 | return "", "" 34 | 35 | 36 | def clean_bytes_to_str(byte_input: bytes) -> str: 37 | return byte_input.decode("utf-8").strip() 38 | 39 | 40 | def get_migration_abspath(app_label: str, migration_name: str) -> str: 41 | from django.db.migrations.loader import MigrationLoader 42 | 43 | module_name, _ = MigrationLoader.migrations_module(app_label) 44 | migration_path = f"{module_name}.{migration_name}" 45 | migration_module = import_module(migration_path) 46 | 47 | migration_file = migration_module.__file__ 48 | if not migration_file: 49 | raise ValueError("Migration file not found") 50 | 51 | if migration_file.endswith(".pyc"): 52 | migration_file = migration_file[:-1] 53 | return migration_file 54 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/__init__.py -------------------------------------------------------------------------------- /tests/fixtures.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | CREATE_TABLE_WITH_NOT_NULL_COLUMN = "app_create_table_with_not_null_column" 4 | ADD_NOT_NULL_COLUMN = "app_add_not_null_column" 5 | DROP_COLUMN = "app_drop_column" 6 | DROP_TABLE = "app_drop_table" 7 | RENAME_COLUMN = "app_rename_column" 8 | RENAME_TABLE = "app_rename_table" 9 | IGNORE_MIGRATION = "app_ignore_migration" 10 | ADD_NOT_NULL_COLUMN_FOLLOWED_BY_DEFAULT = "app_add_not_null_column_followed_by_default" 11 | ADD_NOT_NULL_COLUMN_FOLLOWED_BY_DB_DEFAULT = ( 12 | "app_add_not_null_column_followed_by_db_default" 13 | ) 14 | ALTER_COLUMN = "app_alter_column" 15 | ALTER_COLUMN_DROP_NOT_NULL = "app_alter_column_drop_not_null" 16 | DROP_UNIQUE_TOGETHER = "app_unique_together" 17 | ADD_MANYTOMANY_FIELD = "app_add_manytomany_field" 18 | DATA_MIGRATIONS = "app_data_migrations" 19 | MAKE_NOT_NULL_WITH_DJANGO_DEFAULT = "app_make_not_null_with_django_default" 20 | MAKE_NOT_NULL_WITH_LIB_DEFAULT = "app_make_not_null_with_lib_default" 21 | CREATE_INDEX_EXCLUSIVE = "app_create_index_exclusive" 22 | CUSTOM_APP_NAME_DIRECTORY = "app_with_custom_name" 23 | CUSTOM_APP_LABEL = "my_custom_name" 24 | -------------------------------------------------------------------------------- /tests/functional/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/functional/__init__.py -------------------------------------------------------------------------------- /tests/functional/test_cache.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import unittest 5 | import unittest.mock as mock 6 | 7 | from django.conf import settings 8 | from django.db.migrations import Migration 9 | 10 | from django_migration_linter import ( 11 | IgnoreMigration, 12 | Issue, 13 | MigrationLinter, 14 | analyse_sql_statements, 15 | get_migration_abspath, 16 | ) 17 | 18 | 19 | class OperationsIgnoreMigration(Migration): 20 | operations = [IgnoreMigration()] 21 | 22 | 23 | class CacheTestCase(unittest.TestCase): 24 | def setUp(self): 25 | self.test_project_path = os.path.dirname(settings.BASE_DIR) 26 | 27 | @mock.patch( 28 | "django_migration_linter.MigrationLinter._gather_all_migrations", 29 | return_value=[ 30 | Migration("0001_create_table", "app_add_not_null_column"), 31 | Migration("0002_add_new_not_null_field", "app_add_not_null_column"), 32 | ], 33 | ) 34 | def test_cache_normal(self, *args): 35 | linter = MigrationLinter(self.test_project_path, database="mysql") 36 | linter.old_cache.clear() 37 | linter.old_cache.save() 38 | 39 | with mock.patch( 40 | "django_migration_linter.migration_linter.analyse_sql_statements", 41 | wraps=analyse_sql_statements, 42 | ) as analyse_sql_statements_mock: 43 | linter.lint_all_migrations() 44 | self.assertEqual(2, analyse_sql_statements_mock.call_count) 45 | 46 | cache = linter.new_cache 47 | cache.load() 48 | 49 | self.assertEqual("OK", cache["eb6832d34f7ad40903a51a8b053ac13c"]["result"]) 50 | self.assertEqual("ERR", cache["31fa92230495861937bd6fd35b63c4e7"]["result"]) 51 | self.assertListEqual( 52 | [ 53 | Issue( 54 | code="NOT_NULL", 55 | message="NOT NULL constraint on columns", 56 | ), 57 | ], 58 | cache["31fa92230495861937bd6fd35b63c4e7"]["errors"], 59 | ) 60 | 61 | # Start the Linter again -> should use cache now. 62 | linter = MigrationLinter(self.test_project_path, database="mysql") 63 | 64 | with mock.patch( 65 | "django_migration_linter.migration_linter.analyse_sql_statements", 66 | wraps=analyse_sql_statements, 67 | ) as analyse_sql_statements_mock: 68 | linter.lint_all_migrations() 69 | analyse_sql_statements_mock.assert_not_called() 70 | 71 | self.assertTrue(linter.has_errors) 72 | 73 | @mock.patch( 74 | "django_migration_linter.MigrationLinter._gather_all_migrations", 75 | return_value=[ 76 | Migration("0001_create_table", "app_add_not_null_column"), 77 | Migration("0002_add_new_not_null_field", "app_add_not_null_column"), 78 | ], 79 | ) 80 | def test_cache_different_databases(self, *args): 81 | linter = MigrationLinter(self.test_project_path, database="mysql") 82 | linter.old_cache.clear() 83 | linter.old_cache.save() 84 | 85 | linter = MigrationLinter(self.test_project_path, database="sqlite") 86 | linter.old_cache.clear() 87 | linter.old_cache.save() 88 | 89 | with mock.patch( 90 | "django_migration_linter.migration_linter.analyse_sql_statements", 91 | wraps=analyse_sql_statements, 92 | ) as analyse_sql_statements_mock: 93 | linter.lint_all_migrations() 94 | self.assertEqual(2, analyse_sql_statements_mock.call_count) 95 | 96 | cache = linter.new_cache 97 | cache.load() 98 | 99 | self.assertEqual("OK", cache["eb6832d34f7ad40903a51a8b053ac13c"]["result"]) 100 | self.assertEqual("ERR", cache["31fa92230495861937bd6fd35b63c4e7"]["result"]) 101 | self.assertListEqual( 102 | [ 103 | Issue( 104 | code="NOT_NULL", 105 | message="NOT NULL constraint on columns", 106 | ), 107 | ], 108 | cache["31fa92230495861937bd6fd35b63c4e7"]["errors"], 109 | ) 110 | 111 | # Start the Linter again but with different database, should not be the same cache 112 | linter = MigrationLinter(self.test_project_path, database="mysql") 113 | 114 | with mock.patch( 115 | "django_migration_linter.migration_linter.analyse_sql_statements", 116 | wraps=analyse_sql_statements, 117 | ) as analyse_sql_statements_mock: 118 | linter.lint_all_migrations() 119 | self.assertEqual(2, analyse_sql_statements_mock.call_count) 120 | 121 | cache = linter.new_cache 122 | cache.load() 123 | 124 | self.assertEqual("OK", cache["eb6832d34f7ad40903a51a8b053ac13c"]["result"]) 125 | self.assertEqual("ERR", cache["31fa92230495861937bd6fd35b63c4e7"]["result"]) 126 | self.assertListEqual( 127 | [ 128 | Issue( 129 | code="NOT_NULL", 130 | message="NOT NULL constraint on columns", 131 | ), 132 | ], 133 | cache["31fa92230495861937bd6fd35b63c4e7"]["errors"], 134 | ) 135 | 136 | self.assertTrue(linter.has_errors) 137 | 138 | @mock.patch( 139 | "django_migration_linter.MigrationLinter._gather_all_migrations", 140 | return_value=[ 141 | Migration("0001_initial", "app_ignore_migration"), 142 | OperationsIgnoreMigration("0002_ignore_migration", "app_ignore_migration"), 143 | ], 144 | ) 145 | def test_cache_ignored(self, *args): 146 | linter = MigrationLinter(self.test_project_path, ignore_name_contains="0001") 147 | linter.old_cache.clear() 148 | linter.old_cache.save() 149 | 150 | with mock.patch( 151 | "django_migration_linter.migration_linter.analyse_sql_statements", 152 | wraps=analyse_sql_statements, 153 | ) as analyse_sql_statements_mock: 154 | linter.lint_all_migrations() 155 | analyse_sql_statements_mock.assert_not_called() 156 | 157 | cache = linter.new_cache 158 | cache.load() 159 | 160 | self.assertFalse(cache) 161 | 162 | @mock.patch( 163 | "django_migration_linter.MigrationLinter._gather_all_migrations", 164 | return_value=[ 165 | Migration("0002_add_new_not_null_field", "app_add_not_null_column") 166 | ], 167 | ) 168 | def test_cache_modified(self, *args): 169 | linter = MigrationLinter(self.test_project_path, database="mysql") 170 | linter.old_cache.clear() 171 | linter.old_cache.save() 172 | 173 | with mock.patch( 174 | "django_migration_linter.migration_linter.analyse_sql_statements", 175 | wraps=analyse_sql_statements, 176 | ) as analyse_sql_statements_mock: 177 | linter.lint_all_migrations() 178 | self.assertEqual(1, analyse_sql_statements_mock.call_count) 179 | 180 | cache = linter.new_cache 181 | cache.load() 182 | 183 | self.assertEqual("ERR", cache["31fa92230495861937bd6fd35b63c4e7"]["result"]) 184 | 185 | # Get the content of the migration file and mock the open call to append 186 | # some content to change the hash 187 | migration_path = get_migration_abspath( 188 | "app_add_not_null_column", "0002_add_new_not_null_field" 189 | ) 190 | with open(migration_path, "rb") as f: 191 | file_content = f.read() 192 | file_content += b"# test comment" 193 | 194 | linter = MigrationLinter(self.test_project_path) 195 | with mock.patch( 196 | "django_migration_linter.migration_linter.open", 197 | mock.mock_open(read_data=file_content), 198 | ): 199 | with mock.patch( 200 | "django_migration_linter.migration_linter.analyse_sql_statements", 201 | wraps=analyse_sql_statements, 202 | ) as analyse_sql_statements_mock: 203 | linter.lint_all_migrations() 204 | self.assertEqual(1, analyse_sql_statements_mock.call_count) 205 | 206 | cache = linter.new_cache 207 | cache.load() 208 | 209 | self.assertNotIn("31fa92230495861937bd6fd35b63c4e7", cache) 210 | self.assertEqual(1, len(cache)) 211 | self.assertEqual("ERR", cache["864f9dc59e9dccd57ef6fa45143f1ef0"]["result"]) 212 | 213 | @mock.patch( 214 | "django_migration_linter.MigrationLinter._gather_all_migrations", 215 | return_value=[ 216 | Migration("0001_create_table", "app_add_not_null_column"), 217 | Migration("0002_add_new_not_null_field", "app_add_not_null_column"), 218 | ], 219 | ) 220 | def test_ignore_cached_migration(self, *args): 221 | linter = MigrationLinter(self.test_project_path, database="mysql") 222 | linter.old_cache.clear() 223 | linter.old_cache.save() 224 | 225 | with mock.patch( 226 | "django_migration_linter.migration_linter.analyse_sql_statements", 227 | wraps=analyse_sql_statements, 228 | ) as analyse_sql_statements_mock: 229 | linter.lint_all_migrations() 230 | self.assertEqual(2, analyse_sql_statements_mock.call_count) 231 | 232 | cache = linter.new_cache 233 | cache.load() 234 | 235 | self.assertEqual("OK", cache["eb6832d34f7ad40903a51a8b053ac13c"]["result"]) 236 | self.assertEqual("ERR", cache["31fa92230495861937bd6fd35b63c4e7"]["result"]) 237 | self.assertListEqual( 238 | [ 239 | Issue( 240 | code="NOT_NULL", 241 | message="NOT NULL constraint on columns", 242 | ), 243 | ], 244 | cache["31fa92230495861937bd6fd35b63c4e7"]["errors"], 245 | ) 246 | 247 | # Start the Linter again -> should use cache now but ignore the erroneous 248 | linter = MigrationLinter( 249 | self.test_project_path, 250 | ignore_name_contains="0002_add_new_not_null_field", 251 | database="mysql", 252 | ) 253 | 254 | with mock.patch( 255 | "django_migration_linter.migration_linter.analyse_sql_statements", 256 | wraps=analyse_sql_statements, 257 | ) as analyse_sql_statements_mock: 258 | linter.lint_all_migrations() 259 | analyse_sql_statements_mock.assert_not_called() 260 | 261 | self.assertFalse(linter.has_errors) 262 | 263 | cache = linter.new_cache 264 | cache.load() 265 | self.assertEqual(1, len(cache)) 266 | self.assertEqual("OK", cache["eb6832d34f7ad40903a51a8b053ac13c"]["result"]) 267 | -------------------------------------------------------------------------------- /tests/functional/test_data_migrations.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import unittest 5 | 6 | from django.conf import settings 7 | from django.db import migrations 8 | 9 | from django_migration_linter import MigrationLinter 10 | from tests import fixtures 11 | 12 | 13 | class DataMigrationDetectionTestCase(unittest.TestCase): 14 | def setUp(self, *args, **kwargs): 15 | self.test_project_path = os.path.dirname(settings.BASE_DIR) 16 | self.linter = MigrationLinter( 17 | self.test_project_path, 18 | include_apps=fixtures.DATA_MIGRATIONS, 19 | ) 20 | 21 | def test_reverse_data_migration(self): 22 | self.assertEqual(0, self.linter.nb_warnings) 23 | reverse_migration = self.linter.migration_loader.disk_migrations[ 24 | ("app_data_migrations", "0002_missing_reverse") 25 | ] 26 | self.linter.lint_migration(reverse_migration) 27 | 28 | self.assertEqual(1, self.linter.nb_warnings) 29 | self.assertFalse(self.linter.has_errors) 30 | 31 | def test_reverse_data_migration_ignore(self): 32 | reverse_migration = self.linter.migration_loader.disk_migrations[ 33 | ("app_data_migrations", "0003_incorrect_arguments") 34 | ] 35 | self.linter.lint_migration(reverse_migration) 36 | 37 | self.assertEqual(1, self.linter.nb_warnings) 38 | self.assertFalse(self.linter.has_errors) 39 | 40 | def test_exclude_warning_from_test(self): 41 | self.linter = MigrationLinter( 42 | self.test_project_path, 43 | include_apps=fixtures.DATA_MIGRATIONS, 44 | exclude_migration_tests=("RUNPYTHON_REVERSIBLE",), 45 | ) 46 | 47 | reverse_migration = self.linter.migration_loader.disk_migrations[ 48 | ("app_data_migrations", "0002_missing_reverse") 49 | ] 50 | self.linter.lint_migration(reverse_migration) 51 | 52 | self.assertEqual(0, self.linter.nb_warnings) 53 | self.assertEqual(1, self.linter.nb_valid) 54 | self.assertFalse(self.linter.has_errors) 55 | 56 | def test_all_warnings_as_errors(self): 57 | self.linter = MigrationLinter( 58 | self.test_project_path, 59 | include_apps=fixtures.DATA_MIGRATIONS, 60 | all_warnings_as_errors=True, 61 | ) 62 | 63 | reverse_migration = self.linter.migration_loader.disk_migrations[ 64 | ("app_data_migrations", "0003_incorrect_arguments") 65 | ] 66 | self.linter.lint_migration(reverse_migration) 67 | 68 | self.assertEqual(0, self.linter.nb_warnings) 69 | self.assertEqual(1, self.linter.nb_erroneous) 70 | self.assertTrue(self.linter.has_errors) 71 | 72 | def test_warnings_as_errors_tests_matches(self): 73 | self.linter = MigrationLinter( 74 | self.test_project_path, 75 | include_apps=fixtures.DATA_MIGRATIONS, 76 | warnings_as_errors_tests=["RUNPYTHON_ARGS_NAMING_CONVENTION"], 77 | ) 78 | 79 | reverse_migration = self.linter.migration_loader.disk_migrations[ 80 | ("app_data_migrations", "0003_incorrect_arguments") 81 | ] 82 | self.linter.lint_migration(reverse_migration) 83 | 84 | self.assertEqual(0, self.linter.nb_warnings) 85 | self.assertEqual(1, self.linter.nb_erroneous) 86 | self.assertTrue(self.linter.has_errors) 87 | 88 | def test_warnings_as_errors_tests_no_match(self): 89 | self.linter = MigrationLinter( 90 | self.test_project_path, 91 | include_apps=fixtures.DATA_MIGRATIONS, 92 | warnings_as_errors_tests=[ 93 | "RUNPYTHON_MODEL_IMPORT", 94 | "RUNPYTHON_MODEL_VARIABLE_NAME", 95 | ], 96 | ) 97 | 98 | reverse_migration = self.linter.migration_loader.disk_migrations[ 99 | ("app_data_migrations", "0003_incorrect_arguments") 100 | ] 101 | self.linter.lint_migration(reverse_migration) 102 | 103 | self.assertEqual(1, self.linter.nb_warnings) 104 | self.assertEqual(0, self.linter.nb_erroneous) 105 | self.assertFalse(self.linter.has_errors) 106 | 107 | def test_partial_function(self): 108 | reverse_migration = self.linter.migration_loader.disk_migrations[ 109 | ("app_data_migrations", "0004_partial_function") 110 | ] 111 | self.linter.lint_migration(reverse_migration) 112 | 113 | self.assertEqual(1, self.linter.nb_warnings) 114 | self.assertFalse(self.linter.has_errors) 115 | 116 | 117 | class DataMigrationModelImportTestCase(unittest.TestCase): 118 | def test_missing_get_model_import(self): 119 | def incorrect_importing_model_forward(apps, schema_editor): 120 | from tests.test_project.app_data_migrations.models import MyModel 121 | 122 | MyModel.objects.filter(id=1).first() 123 | 124 | issues = MigrationLinter.get_runpython_model_import_issues( 125 | incorrect_importing_model_forward 126 | ) 127 | self.assertEqual(1, len(issues)) 128 | 129 | def test_correct_get_model_import(self): 130 | def correct_importing_model_forward(apps, schema_editor): 131 | MyModel = apps.get_model("app_data_migrations", "MyModel") 132 | MyVeryLongLongLongModel = apps.get_model( 133 | "app_data_migrations", "MyVeryLongLongLongModel" 134 | ) 135 | MultiLineModel = apps.get_model( 136 | "app_data_migrations", 137 | "MultiLineModel", 138 | ) 139 | 140 | MyModel.objects.filter(id=1).first() 141 | MyVeryLongLongLongModel.objects.filter(id=1).first() 142 | MultiLineModel.objects.all() 143 | 144 | issues = MigrationLinter.get_runpython_model_import_issues( 145 | correct_importing_model_forward 146 | ) 147 | self.assertEqual(0, len(issues)) 148 | 149 | def test_not_overlapping_model_name(self): 150 | """ 151 | Correct for the import error, but should raise a warning. 152 | """ 153 | 154 | def forward_method(apps, schema_editor): 155 | User = apps.get_model("auth", "CustomUserModel") 156 | 157 | User.objects.filter(id=1).first() 158 | 159 | issues = MigrationLinter.get_runpython_model_import_issues(forward_method) 160 | self.assertEqual(0, len(issues)) 161 | 162 | def test_correct_one_param_get_model_import(self): 163 | def forward_method(apps, schema_editor): 164 | User = apps.get_model("auth.User") 165 | 166 | User.objects.filter(id=1).first() 167 | 168 | issues = MigrationLinter.get_runpython_model_import_issues(forward_method) 169 | self.assertEqual(0, len(issues)) 170 | 171 | def test_not_overlapping_one_param(self): 172 | """ 173 | Not an error, but should raise a warning. 174 | """ 175 | 176 | def forward_method(apps, schema_editor): 177 | User = apps.get_model("auth.CustomUserModel") 178 | 179 | User.objects.filter(id=1).first() 180 | 181 | issues = MigrationLinter.get_runpython_model_import_issues(forward_method) 182 | self.assertEqual(0, len(issues)) 183 | 184 | def test_m2m_through_orm_usage(self): 185 | def forward_method(apps, schema_editor): 186 | MyModel = apps.get_model("myapp", "MyModel") 187 | 188 | MyModel.many_to_many.through.objects.filter(id=1).first() 189 | 190 | issues = MigrationLinter.get_runpython_model_import_issues(forward_method) 191 | self.assertEqual(0, len(issues)) 192 | 193 | def test_missing_m2m_through_orm(self): 194 | def forward_method(apps, schema_editor): 195 | from tests.test_project.app_data_migrations.models import MyModel 196 | 197 | MyModel.many_to_many.through.objects.filter(id=1).first() 198 | 199 | issues = MigrationLinter.get_runpython_model_import_issues(forward_method) 200 | self.assertEqual(1, len(issues)) 201 | 202 | 203 | class DataMigrationModelVariableNamingTestCase(unittest.TestCase): 204 | def test_same_variable_name(self): 205 | def forward_op(apps, schema_editor): 206 | MyModel = apps.get_model("app", "MyModel") 207 | 208 | MyModel.objects.filter(id=1).first() 209 | 210 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 211 | self.assertEqual(0, len(issues)) 212 | 213 | def test_same_variable_name_multiline(self): 214 | def forward_op(apps, schema_editor): 215 | MyModelVeryLongLongLongLongLong = apps.get_model( 216 | "app", "MyModelVeryLongLongLongLongLong" 217 | ) 218 | 219 | MyModelVeryLongLongLongLongLong.objects.filter(id=1).first() 220 | 221 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 222 | self.assertEqual(0, len(issues)) 223 | 224 | def test_same_variable_name_multiline2(self): 225 | def forward_op(apps, schema_editor): 226 | MyModelVeryLongLongLongLongLong = apps.get_model( 227 | "app_name_longlonglonglongapp", 228 | "MyModelVeryLongLongLongLongLong", 229 | ) 230 | 231 | MyModelVeryLongLongLongLongLong.objects.filter(id=1).first() 232 | 233 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 234 | self.assertEqual(0, len(issues)) 235 | 236 | def test_different_variable_name(self): 237 | def forward_op(apps, schema_editor): 238 | some_model = apps.get_model("app", "MyModel") 239 | 240 | some_model.objects.filter(id=1).first() 241 | 242 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 243 | self.assertEqual(1, len(issues)) 244 | 245 | def test_diff_variable_name_multiline(self): 246 | def forward_op(apps, schema_editor): 247 | MyModelVeryLongLongLongLongLongNot = apps.get_model( 248 | "app", "MyModelVeryLongLongLongLongLong" 249 | ) 250 | 251 | MyModelVeryLongLongLongLongLongNot.objects.filter(id=1).first() 252 | 253 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 254 | self.assertEqual(1, len(issues)) 255 | 256 | def test_diff_variable_name_multiline2(self): 257 | def forward_op(apps, schema_editor): 258 | MyModelVeryLongLongLongLongLongNot = apps.get_model( 259 | "app_name_longlonglonglongapp", 260 | "MyModelVeryLongLongLongLongLong", 261 | ) 262 | 263 | MyModelVeryLongLongLongLongLongNot.objects.filter(id=1).first() 264 | 265 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 266 | self.assertEqual(1, len(issues)) 267 | 268 | def test_same_variable_name_one_param(self): 269 | def forward_op(apps, schema_editor): 270 | MyModel = apps.get_model("app.MyModel") 271 | 272 | MyModel.objects.filter(id=1).first() 273 | 274 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 275 | self.assertEqual(0, len(issues)) 276 | 277 | def test_different_variable_name_one_param(self): 278 | def forward_op(apps, schema_editor): 279 | mymodel = apps.get_model("app.MyModel") 280 | 281 | mymodel.objects.filter(id=1).first() 282 | 283 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 284 | self.assertEqual(1, len(issues)) 285 | 286 | def test_correct_variable_name_one_param_multiline(self): 287 | def forward_op(apps, schema_editor): 288 | AVeryLongModelName = apps.get_model( 289 | "quite_long_app_name.AVeryLongModelName" 290 | ) 291 | 292 | AVeryLongModelName.objects.filter(id=1).first() 293 | 294 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 295 | self.assertEqual(0, len(issues)) 296 | 297 | def test_different_variable_name_one_param_multiline(self): 298 | def forward_op(apps, schema_editor): 299 | m = apps.get_model( 300 | "quite_long_app_name_name_name.AVeryLongModelNameNameName" 301 | ) 302 | 303 | m.objects.filter(id=1).first() 304 | 305 | issues = MigrationLinter.get_runpython_model_variable_naming_issues(forward_op) 306 | self.assertEqual(1, len(issues)) 307 | 308 | 309 | class RunSQLMigrationTestCase(unittest.TestCase): 310 | def setUp(self): 311 | test_project_path = os.path.dirname(settings.BASE_DIR) 312 | self.linter = MigrationLinter( 313 | test_project_path, 314 | include_apps=fixtures.DATA_MIGRATIONS, 315 | ) 316 | 317 | def test_missing_reserve_migration(self): 318 | runsql = migrations.RunSQL("sql;") 319 | 320 | error, ignored, warning = self.linter.lint_runsql(runsql) 321 | self.assertEqual("RUNSQL_REVERSIBLE", warning[0].code) 322 | 323 | def test_sql_linting_error(self): 324 | runsql = migrations.RunSQL("ALTER TABLE t DROP COLUMN t;") 325 | 326 | error, ignored, warning = self.linter.lint_runsql(runsql) 327 | self.assertEqual("DROP_COLUMN", error[0].code) 328 | 329 | def test_sql_linting_error_array(self): 330 | runsql = migrations.RunSQL( 331 | ["ALTER TABLE t DROP COLUMN c;", "ALTER TABLE t RENAME COLUMN c;"] 332 | ) 333 | 334 | error, ignored, warning = self.linter.lint_runsql(runsql) 335 | self.assertEqual("DROP_COLUMN", error[0].code) 336 | self.assertEqual("RENAME_COLUMN", error[1].code) 337 | 338 | def test_sql_linting_error_args(self): 339 | runsql = migrations.RunSQL([("ALTER TABLE %s DROP COLUMN %s;", ("t", "c"))]) 340 | 341 | error, ignored, warning = self.linter.lint_runsql(runsql) 342 | self.assertEqual("DROP_COLUMN", error[0].code) 343 | -------------------------------------------------------------------------------- /tests/functional/test_lintmigrations_command.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from unittest.mock import patch 4 | 5 | from django.core.management import call_command 6 | from django.test import TransactionTestCase 7 | from django.test.utils import override_settings 8 | 9 | 10 | class LintMigrationsCommandTestCase(TransactionTestCase): 11 | databases = {"default", "sqlite"} 12 | 13 | def setUp(self): 14 | call_command("migrate", "app_unique_together", "0002") 15 | self.addCleanup(call_command, "migrate", "app_unique_together") 16 | super().setUp() 17 | 18 | def test_plain(self): 19 | with self.assertRaises(SystemExit): 20 | call_command("lintmigrations") 21 | 22 | def test_config_file_app_label(self): 23 | with patch( 24 | "django_migration_linter.management.commands.lintmigrations.Command.read_config_file" 25 | ) as config_fn: 26 | config_fn.return_value = {"app_label": "app_correct"} 27 | call_command("lintmigrations") 28 | 29 | def test_command_line_app_label(self): 30 | call_command("lintmigrations", app_label="app_correct") 31 | 32 | def test_command_line_and_config_file_app_label(self): 33 | with patch( 34 | "django_migration_linter.management.commands.lintmigrations.Command.read_config_file" 35 | ) as config_fn: 36 | config_fn.return_value = {"app_label": "app_correct"} 37 | 38 | with self.assertRaises(SystemExit): 39 | call_command("lintmigrations", app_label="app_drop_table") 40 | 41 | @override_settings(MIGRATION_LINTER_OPTIONS={"app_label": "app_correct"}) 42 | def test_django_settings_option(self): 43 | call_command("lintmigrations") 44 | -------------------------------------------------------------------------------- /tests/functional/test_makemigrations_command.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import shutil 5 | import tempfile 6 | import unittest.mock as mock 7 | from contextlib import contextmanager 8 | from importlib import import_module 9 | from io import StringIO 10 | 11 | from django.apps import apps 12 | from django.conf import settings 13 | from django.core.management import call_command 14 | from django.test import TransactionTestCase 15 | from django.test.utils import extend_sys_path, override_settings 16 | from django.utils.module_loading import module_dir 17 | 18 | MAKEMIGRATIONS_INSTALLED_APPS = settings.INSTALLED_APPS + [ 19 | "tests.test_project.makemigrations_correct_migration_missing", 20 | "tests.test_project.makemigrations_backward_incompatible_migration_missing", 21 | ] 22 | 23 | 24 | @override_settings(INSTALLED_APPS=MAKEMIGRATIONS_INSTALLED_APPS) 25 | class BaseMakeMigrationsTestCase(TransactionTestCase): 26 | @contextmanager 27 | def temporary_migration_module(self, app_label="migrations", module=None): 28 | """ 29 | Shamelessly copied from Django. 30 | See django.tests.migrations.test_base.MigrationTestBase.temporary_migration_module 31 | 32 | Allows testing management commands in a temporary migrations module. 33 | 34 | Wrap all invocations to makemigrations and squashmigrations with this 35 | context manager in order to avoid creating migration files in your 36 | source tree inadvertently. 37 | """ 38 | with tempfile.TemporaryDirectory() as temp_dir: 39 | target_dir = tempfile.mkdtemp(dir=temp_dir) 40 | with open(os.path.join(target_dir, "__init__.py"), "w"): 41 | pass 42 | target_migrations_dir = os.path.join(target_dir, "migrations") 43 | 44 | if module is None: 45 | module = apps.get_app_config(app_label).name + ".migrations" 46 | 47 | try: 48 | source_migrations_dir = module_dir(import_module(module)) 49 | except (ImportError, ValueError): 50 | pass 51 | else: 52 | shutil.copytree(source_migrations_dir, target_migrations_dir) 53 | 54 | with extend_sys_path(temp_dir): 55 | new_module = os.path.basename(target_dir) + ".migrations" 56 | with self.settings(MIGRATION_MODULES={app_label: new_module}): 57 | yield target_migrations_dir 58 | 59 | 60 | class MakeMigrationsCorrectTestCase(BaseMakeMigrationsTestCase): 61 | available_apps = [ 62 | "django_migration_linter", 63 | "tests.test_project.makemigrations_correct_migration_missing", 64 | ] 65 | databases = {"default", "postgresql"} 66 | 67 | def test_correct_linted_makemigrations(self): 68 | out = StringIO() 69 | with self.temporary_migration_module( 70 | app_label="makemigrations_correct_migration_missing" 71 | ) as migration_dir: 72 | call_command("makemigrations", lint=True, database="postgresql", stdout=out) 73 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 74 | self.assertTrue(os.path.exists(new_migration_file)) 75 | output = out.getvalue() 76 | self.assertIn("Linting for 'makemigrations_correct_migration_missing':", output) 77 | 78 | @override_settings(MIGRATION_LINTER_OVERRIDE_MAKEMIGRATIONS=True) 79 | def test_correct_linted_makemigrations_using_settings(self): 80 | out = StringIO() 81 | with self.temporary_migration_module( 82 | app_label="makemigrations_correct_migration_missing" 83 | ) as migration_dir: 84 | call_command("makemigrations", database="postgresql", stdout=out) 85 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 86 | self.assertTrue(os.path.exists(new_migration_file)) 87 | output = out.getvalue() 88 | self.assertIn("Linting for 'makemigrations_correct_migration_missing':", output) 89 | 90 | def test_no_linting_when_no_option(self): 91 | out = StringIO() 92 | with self.temporary_migration_module( 93 | app_label="makemigrations_correct_migration_missing" 94 | ) as migration_dir: 95 | call_command("makemigrations", database="postgresql", stdout=out) 96 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 97 | self.assertTrue(os.path.exists(new_migration_file)) 98 | output = out.getvalue() 99 | self.assertNotIn("Linting", output) 100 | 101 | def test_correct_linted_makemigrations_dry_run(self): 102 | out = StringIO() 103 | with self.temporary_migration_module( 104 | app_label="makemigrations_correct_migration_missing" 105 | ) as migration_dir: 106 | call_command( 107 | "makemigrations", 108 | lint=True, 109 | database="postgresql", 110 | dry_run=True, 111 | stdout=out, 112 | ) 113 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 114 | self.assertFalse(os.path.exists(new_migration_file)) 115 | output = out.getvalue() 116 | self.assertNotIn("Linting", output) 117 | 118 | 119 | @override_settings(MIGRATION_LINTER_OVERRIDE_MAKEMIGRATIONS=True) 120 | class MakeMigrationsBackwardIncompatibleTestCase(BaseMakeMigrationsTestCase): 121 | available_apps = [ 122 | "django_migration_linter", 123 | "tests.test_project.makemigrations_backward_incompatible_migration_missing", 124 | ] 125 | databases = {"default", "sqlite", "mysql", "postgresql"} 126 | 127 | def test_backward_incompatible_migration_postgresql(self): 128 | out = StringIO() 129 | with self.temporary_migration_module( 130 | app_label="makemigrations_backward_incompatible_migration_missing" 131 | ) as migration_dir: 132 | call_command( 133 | "makemigrations", interactive=False, database="postgresql", stdout=out 134 | ) 135 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 136 | self.assertFalse(os.path.exists(new_migration_file)) 137 | output = out.getvalue() 138 | self.assertIn("Deleted", output) 139 | 140 | def test_backward_incompatible_migration_mysql(self): 141 | out = StringIO() 142 | with self.temporary_migration_module( 143 | app_label="makemigrations_backward_incompatible_migration_missing" 144 | ) as migration_dir: 145 | call_command( 146 | "makemigrations", interactive=False, database="mysql", stdout=out 147 | ) 148 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 149 | self.assertFalse(os.path.exists(new_migration_file)) 150 | output = out.getvalue() 151 | self.assertIn("Deleted", output) 152 | 153 | def test_backward_incompatible_migration_sqlite(self): 154 | out = StringIO() 155 | with self.temporary_migration_module( 156 | app_label="makemigrations_backward_incompatible_migration_missing" 157 | ) as migration_dir: 158 | call_command( 159 | "makemigrations", interactive=False, database="sqlite", stdout=out 160 | ) 161 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 162 | self.assertFalse(os.path.exists(new_migration_file)) 163 | output = out.getvalue() 164 | self.assertIn("Deleted", output) 165 | 166 | @mock.patch("django.db.migrations.questioner.input", return_value="yes") 167 | def test_backward_incompatible_migration_interactive_keep_migration(self, *args): 168 | out = StringIO() 169 | with self.temporary_migration_module( 170 | app_label="makemigrations_backward_incompatible_migration_missing" 171 | ) as migration_dir: 172 | call_command( 173 | "makemigrations", interactive=True, database="postgresql", stdout=out 174 | ) 175 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 176 | self.assertTrue(os.path.exists(new_migration_file)) 177 | output = out.getvalue() 178 | self.assertNotIn("Deleted", output) 179 | 180 | @mock.patch("django.db.migrations.questioner.input", return_value="no") 181 | def test_backward_incompatible_migration_interactive_delete_migration(self, *args): 182 | out = StringIO() 183 | with self.temporary_migration_module( 184 | app_label="makemigrations_backward_incompatible_migration_missing" 185 | ) as migration_dir: 186 | call_command( 187 | "makemigrations", interactive=True, database="postgresql", stdout=out 188 | ) 189 | new_migration_file = os.path.join(migration_dir, "0002_a_new_field.py") 190 | self.assertFalse(os.path.exists(new_migration_file)) 191 | output = out.getvalue() 192 | self.assertIn("Deleted", output) 193 | -------------------------------------------------------------------------------- /tests/functional/test_migration_linter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import unittest 5 | from unittest import skipIf 6 | 7 | import django 8 | from django.conf import settings 9 | from django.core.management import call_command 10 | 11 | from django_migration_linter import MigrationLinter 12 | from tests import fixtures 13 | 14 | 15 | class BaseBackwardCompatibilityDetection: 16 | def setUp(self, *args, **kwargs): 17 | self.database = next(iter(self.databases)) 18 | self.test_project_path = os.path.dirname(settings.BASE_DIR) 19 | call_command( 20 | "migrate", 21 | "app_unique_together", 22 | "0002", 23 | database=self.database, 24 | ) 25 | self.addCleanup( 26 | call_command, 27 | "migrate", 28 | "app_unique_together", 29 | database=self.database, 30 | ) 31 | return super().setUp(*args, **kwargs) 32 | 33 | def _test_linter_finds_errors(self, app=None, commit_id=None): 34 | linter = self._launch_linter(app, commit_id) 35 | self.assertTrue(linter.has_errors) 36 | self.assertNotEqual(linter.nb_valid + linter.nb_erroneous, 0) 37 | self.assertGreater(linter.nb_total, 0) 38 | 39 | def _test_linter_finds_no_errors(self, app=None, commit_id=None): 40 | linter = self._launch_linter(app, commit_id) 41 | self.assertFalse(linter.has_errors) 42 | self.assertNotEqual(linter.nb_valid + linter.nb_erroneous, 0) 43 | self.assertGreater(linter.nb_total, 0) 44 | 45 | def _test_linter_linted_no_migration(self, app=None, commit_id=None): 46 | linter = self._launch_linter(app, commit_id) 47 | self.assertEqual(linter.nb_valid, 0) 48 | self.assertEqual(linter.nb_erroneous, 0) 49 | self.assertEqual(linter.nb_total, 0) 50 | 51 | def _launch_linter(self, app=None, commit_id=None): 52 | linter = self._get_linter() 53 | linter.lint_all_migrations(app_label=app, git_commit_id=commit_id) 54 | return linter 55 | 56 | def _get_linter(self): 57 | return MigrationLinter( 58 | self.test_project_path, 59 | database=self.database, 60 | no_cache=True, 61 | ) 62 | 63 | def test_create_table_with_not_null_column(self): 64 | app = fixtures.CREATE_TABLE_WITH_NOT_NULL_COLUMN 65 | self._test_linter_finds_no_errors(app) 66 | 67 | def test_detect_adding_not_null_column(self): 68 | app = fixtures.ADD_NOT_NULL_COLUMN 69 | self._test_linter_finds_errors(app) 70 | 71 | def test_detect_make_column_not_null_with_django_default(self): 72 | app = fixtures.MAKE_NOT_NULL_WITH_DJANGO_DEFAULT 73 | self._test_linter_finds_errors(app) 74 | 75 | def test_detect_make_column_not_null_with_lib_default(self): 76 | app = fixtures.MAKE_NOT_NULL_WITH_LIB_DEFAULT 77 | self._test_linter_finds_no_errors(app) 78 | 79 | def test_detect_drop_column(self): 80 | app = fixtures.DROP_COLUMN 81 | self._test_linter_finds_errors(app) 82 | 83 | def test_detect_drop_table(self): 84 | app = fixtures.DROP_TABLE 85 | self._test_linter_finds_errors(app) 86 | 87 | def test_detect_rename_column(self): 88 | app = fixtures.RENAME_COLUMN 89 | self._test_linter_finds_errors(app) 90 | 91 | def test_detect_rename_table(self): 92 | app = fixtures.RENAME_TABLE 93 | self._test_linter_finds_errors(app) 94 | 95 | def test_ignore_migration(self): 96 | app = fixtures.IGNORE_MIGRATION 97 | self._test_linter_finds_no_errors(app) 98 | 99 | def test_accept_not_null_column_followed_by_adding_default(self): 100 | app = fixtures.ADD_NOT_NULL_COLUMN_FOLLOWED_BY_DEFAULT 101 | self._test_linter_finds_no_errors(app) 102 | 103 | @skipIf(django.VERSION[0] < 5, "db_default was implemented in Django 5.0") 104 | def test_accept_not_null_column_followed_by_adding_db_default(self): 105 | app = fixtures.ADD_NOT_NULL_COLUMN_FOLLOWED_BY_DB_DEFAULT 106 | self._test_linter_finds_no_errors(app) 107 | 108 | def test_detect_alter_column(self): 109 | app = fixtures.ALTER_COLUMN 110 | self._test_linter_finds_no_errors(app) 111 | 112 | def test_drop_unique_together(self): 113 | app = fixtures.DROP_UNIQUE_TOGETHER 114 | self._test_linter_finds_errors(app) 115 | 116 | def test_accept_alter_column_drop_not_null(self): 117 | app = fixtures.ALTER_COLUMN_DROP_NOT_NULL 118 | self._test_linter_finds_no_errors(app) 119 | 120 | def test_accept_adding_manytomany_field(self): 121 | app = fixtures.ADD_MANYTOMANY_FIELD 122 | self._test_linter_finds_no_errors(app) 123 | 124 | def test_with_git_ref(self): 125 | self._test_linter_finds_errors(commit_id="v0.1.4") 126 | 127 | def test_failing_get_sql(self): 128 | call_command("migrate", "app_unique_together", database=self.database) 129 | 130 | linter = MigrationLinter(database=self.database) 131 | with self.assertRaises(ValueError): 132 | linter.get_sql("app_unique_together", "0003") 133 | 134 | def test_custom_named_app(self): 135 | # Folder name is not found. 136 | app = fixtures.CUSTOM_APP_NAME_DIRECTORY 137 | self._test_linter_linted_no_migration(app) 138 | 139 | # Django app name is found. 140 | app = fixtures.CUSTOM_APP_LABEL 141 | self._test_linter_finds_no_errors(app) 142 | 143 | # And with git ref: 144 | app = fixtures.CUSTOM_APP_NAME_DIRECTORY 145 | self._test_linter_linted_no_migration(app, commit_id="v0.1.4") 146 | 147 | app = fixtures.CUSTOM_APP_LABEL 148 | self._test_linter_finds_no_errors(app, commit_id="v0.1.4") 149 | 150 | 151 | class SqliteBackwardCompatibilityDetectionTestCase( 152 | BaseBackwardCompatibilityDetection, unittest.TestCase 153 | ): 154 | databases = ["sqlite"] 155 | 156 | def test_accept_not_null_column_followed_by_adding_default(self): 157 | app = fixtures.ADD_NOT_NULL_COLUMN_FOLLOWED_BY_DEFAULT 158 | self._test_linter_finds_errors(app) 159 | 160 | def test_detect_make_column_not_null_with_django_default(self): 161 | app = fixtures.MAKE_NOT_NULL_WITH_DJANGO_DEFAULT 162 | self._test_linter_finds_errors(app) 163 | 164 | @skipIf(django.VERSION[0] < 5, "db_default was implemented in Django 5.0") 165 | def test_accept_not_null_column_followed_by_adding_db_default(self): 166 | app = fixtures.ADD_NOT_NULL_COLUMN_FOLLOWED_BY_DB_DEFAULT 167 | self._test_linter_finds_errors(app) 168 | 169 | def test_detect_make_column_not_null_with_lib_default(self): 170 | # The 'django-add-default-value' doesn't handle sqlite correctly 171 | app = fixtures.MAKE_NOT_NULL_WITH_LIB_DEFAULT 172 | self._test_linter_finds_errors(app) 173 | 174 | 175 | class MySqlBackwardCompatibilityDetectionTestCase( 176 | BaseBackwardCompatibilityDetection, unittest.TestCase 177 | ): 178 | databases = ["mysql"] 179 | 180 | 181 | class PostgresqlBackwardCompatibilityDetectionTestCase( 182 | BaseBackwardCompatibilityDetection, unittest.TestCase 183 | ): 184 | databases = ["postgresql"] 185 | 186 | def test_detect_alter_column(self): 187 | app = fixtures.ALTER_COLUMN 188 | self._test_linter_finds_errors(app) 189 | 190 | def test_create_index_exclusive(self): 191 | linter = self._launch_linter(fixtures.CREATE_INDEX_EXCLUSIVE) 192 | self.assertFalse(linter.has_errors) 193 | self.assertTrue(linter.nb_warnings) 194 | -------------------------------------------------------------------------------- /tests/test_project/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_manytomany_field/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_manytomany_field/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_manytomany_field/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2019-09-20 20:01 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ) 26 | ], 27 | ), 28 | migrations.CreateModel( 29 | name="B", 30 | fields=[ 31 | ( 32 | "id", 33 | models.AutoField( 34 | auto_created=True, 35 | primary_key=True, 36 | serialize=False, 37 | verbose_name="ID", 38 | ), 39 | ) 40 | ], 41 | ), 42 | ] 43 | -------------------------------------------------------------------------------- /tests/test_project/app_add_manytomany_field/migrations/0002_b_many_to_many.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2019-09-20 20:02 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [("app_add_manytomany_field", "0001_initial")] 10 | 11 | operations = [ 12 | migrations.AddField( 13 | model_name="b", 14 | name="many_to_many", 15 | field=models.ManyToManyField(to="app_add_manytomany_field.A"), 16 | ) 17 | ] 18 | -------------------------------------------------------------------------------- /tests/test_project/app_add_manytomany_field/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_manytomany_field/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_manytomany_field/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | pass 8 | 9 | 10 | class B(models.Model): 11 | many_to_many = models.ManyToManyField(A) 12 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_not_null_column/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column/migrations/0001_create_table.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-19 20:59 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("null_field", models.IntegerField(null=True)), 27 | ], 28 | ) 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column/migrations/0002_add_new_not_null_field.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-19 21:05 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [("app_add_not_null_column", "0001_create_table")] 10 | 11 | operations = [ 12 | migrations.AddField( 13 | model_name="a", 14 | name="new_not_null_field", 15 | field=models.IntegerField(default=1), 16 | preserve_default=False, 17 | ) 18 | ] 19 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_not_null_column/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | null_field = models.IntegerField(null=True) 8 | new_not_null_field = models.IntegerField(null=False) 9 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_db_default/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_not_null_column_followed_by_db_default/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_db_default/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.1 on 2024-02-04 20:07 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field", models.IntegerField()), 28 | ], 29 | ), 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_db_default/migrations/0002_a_not_null_field_db_default.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.1 on 2024-02-04 20:07 2 | 3 | from __future__ import annotations 4 | 5 | import django.db.models.functions.math 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | dependencies = [ 12 | ("app_add_not_null_column_followed_by_db_default", "0001_initial"), 13 | ] 14 | 15 | operations = [ 16 | migrations.AddField( 17 | model_name="a", 18 | name="not_null_field_db_default", 19 | field=models.IntegerField(db_default=django.db.models.functions.math.Pi()), 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_db_default/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_not_null_column_followed_by_db_default/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_db_default/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | from django.db.models.functions import Pi 5 | 6 | 7 | class A(models.Model): 8 | field = models.IntegerField() 9 | not_null_field_db_default = models.IntegerField( 10 | null=False, 11 | db_default=Pi(), 12 | ) 13 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_default/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_not_null_column_followed_by_default/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_default/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:54 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field", models.IntegerField()), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_default/migrations/0002_a_not_null_field.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:55 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | from django_add_default_value import AddDefaultValue 8 | 9 | 10 | class Migration(migrations.Migration): 11 | dependencies = [("app_add_not_null_column_followed_by_default", "0001_initial")] 12 | 13 | operations = [ 14 | migrations.AddField( 15 | model_name="a", name="not_null_field", field=models.IntegerField(default=1) 16 | ), 17 | AddDefaultValue(model_name="a", name="not_null_field", value=1), 18 | ] 19 | -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_default/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_add_not_null_column_followed_by_default/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_add_not_null_column_followed_by_default/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | field = models.IntegerField() 8 | not_null_field = models.IntegerField(null=False, default=1) 9 | -------------------------------------------------------------------------------- /tests/test_project/app_alter_column/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_alter_column/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_alter_column/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:56 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field", models.IntegerField(null=True)), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_alter_column/migrations/0002_auto_20190414_1456.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:56 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | dependencies = [("app_alter_column", "0001_initial")] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name="a", 15 | name="field", 16 | field=models.CharField(max_length=10, null=True), 17 | ) 18 | ] 19 | -------------------------------------------------------------------------------- /tests/test_project/app_alter_column/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_alter_column/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_alter_column/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | field = models.CharField(null=True, max_length=10) 8 | -------------------------------------------------------------------------------- /tests/test_project/app_alter_column_drop_not_null/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_alter_column_drop_not_null/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_alter_column_drop_not_null/migrations/0001_create_table.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-19 20:59 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("not_null_field", models.IntegerField(null=False)), 27 | ], 28 | ) 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_alter_column_drop_not_null/migrations/0002_drop_not_null.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-19 21:05 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [("app_alter_column_drop_not_null", "0001_create_table")] 10 | 11 | operations = [ 12 | migrations.AlterField( 13 | model_name="a", name="not_null_field", field=models.IntegerField(null=True) 14 | ) 15 | ] 16 | -------------------------------------------------------------------------------- /tests/test_project/app_alter_column_drop_not_null/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_alter_column_drop_not_null/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_alter_column_drop_not_null/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | not_null_field = models.IntegerField(null=True) 8 | -------------------------------------------------------------------------------- /tests/test_project/app_correct/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_correct/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_correct/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-19 21:08 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("null_field", models.IntegerField(null=True)), 27 | ], 28 | ) 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_correct/migrations/0002_foo.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-19 21:08 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [("app_correct", "0001_initial")] 10 | 11 | operations = [ 12 | migrations.AddField( 13 | model_name="a", name="new_null_field", field=models.IntegerField(null=True) 14 | ) 15 | ] 16 | -------------------------------------------------------------------------------- /tests/test_project/app_correct/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_correct/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_correct/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | null_field = models.IntegerField(null=True) 8 | new_null_field = models.IntegerField(null=True) 9 | -------------------------------------------------------------------------------- /tests/test_project/app_create_index_exclusive/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_create_index_exclusive/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_create_index_exclusive/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.7 on 2023-03-09 21:46 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="User", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("name", models.TextField()), 27 | ], 28 | ), 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_create_index_exclusive/migrations/0002_user_email.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.7 on 2023-03-09 21:47 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [ 10 | ("app_create_index_exclusive", "0001_initial"), 11 | ] 12 | 13 | operations = [ 14 | migrations.AddField( 15 | model_name="user", 16 | name="email", 17 | field=models.EmailField(db_index=True, max_length=254, null=True), 18 | ), 19 | ] 20 | -------------------------------------------------------------------------------- /tests/test_project/app_create_index_exclusive/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_create_index_exclusive/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_create_index_exclusive/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class User(models.Model): 7 | name = models.TextField() 8 | email = models.EmailField(db_index=True, null=True) 9 | -------------------------------------------------------------------------------- /tests/test_project/app_create_table_with_not_null_column/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_create_table_with_not_null_column/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_create_table_with_not_null_column/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:59 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field", models.CharField(max_length=150)), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_create_table_with_not_null_column/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_create_table_with_not_null_column/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_create_table_with_not_null_column/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | field = models.CharField(max_length=150, null=False) 8 | -------------------------------------------------------------------------------- /tests/test_project/app_data_migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_data_migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_data_migrations/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-01-26 17:43 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="MyModel", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("myfield", models.IntegerField()), 27 | ], 28 | ) 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_data_migrations/migrations/0002_missing_reverse.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-01-26 17:43 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations 6 | 7 | 8 | def update_things(apps, schema_editor): 9 | pass 10 | 11 | 12 | class Migration(migrations.Migration): 13 | dependencies = [("app_data_migrations", "0001_initial")] 14 | 15 | operations = [migrations.RunPython(update_things)] 16 | -------------------------------------------------------------------------------- /tests/test_project/app_data_migrations/migrations/0003_incorrect_arguments.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-01-26 17:47 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations 6 | 7 | 8 | def backward_weirdly_named(david, test): 9 | pass 10 | 11 | 12 | def forward_weird_name(arg1, arg2): 13 | pass 14 | 15 | 16 | class Migration(migrations.Migration): 17 | dependencies = [("app_data_migrations", "0002_missing_reverse")] 18 | 19 | operations = [migrations.RunPython(forward_weird_name, backward_weirdly_named)] 20 | -------------------------------------------------------------------------------- /tests/test_project/app_data_migrations/migrations/0004_partial_function.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-01-27 17:47 2 | 3 | from __future__ import annotations 4 | 5 | import functools 6 | 7 | from django.db import migrations 8 | 9 | 10 | def backward_op(c, david, test): 11 | pass 12 | 13 | 14 | def forward_op(const, arg1, arg2): 15 | pass 16 | 17 | 18 | class Migration(migrations.Migration): 19 | dependencies = [("app_data_migrations", "0003_incorrect_arguments")] 20 | 21 | operations = [ 22 | migrations.RunPython( 23 | functools.partial(forward_op, "constant"), 24 | functools.partial(backward_op, "constant"), 25 | ) 26 | ] 27 | -------------------------------------------------------------------------------- /tests/test_project/app_data_migrations/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_data_migrations/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_data_migrations/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class MyModel(models.Model): 7 | myfield = models.IntegerField() 8 | -------------------------------------------------------------------------------- /tests/test_project/app_drop_column/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_drop_column/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_drop_column/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:59 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field_a", models.IntegerField()), 28 | ("field_b", models.CharField(max_length=10)), 29 | ], 30 | ) 31 | ] 32 | -------------------------------------------------------------------------------- /tests/test_project/app_drop_column/migrations/0002_remove_a_field_b.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:59 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations 7 | 8 | 9 | class Migration(migrations.Migration): 10 | dependencies = [("app_drop_column", "0001_initial")] 11 | 12 | operations = [migrations.RemoveField(model_name="a", name="field_b")] 13 | -------------------------------------------------------------------------------- /tests/test_project/app_drop_column/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_drop_column/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_drop_column/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | field_a = models.IntegerField() 8 | -------------------------------------------------------------------------------- /tests/test_project/app_drop_table/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_drop_table/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_drop_table/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 14:59 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field_a", models.IntegerField()), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_drop_table/migrations/0002_delete_a.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.10 on 2019-07-19 09:50 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [("app_drop_table", "0001_initial")] 10 | 11 | operations = [migrations.DeleteModel(name="A")] 12 | -------------------------------------------------------------------------------- /tests/test_project/app_drop_table/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_drop_table/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_drop_table/models.py: -------------------------------------------------------------------------------- 1 | # from django.db import models 2 | 3 | # class A(models.Model): 4 | # field_a = models.IntegerField() 5 | -------------------------------------------------------------------------------- /tests/test_project/app_ignore_migration/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_ignore_migration/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_ignore_migration/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-21 20:40 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="B", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("null_field", models.IntegerField()), 27 | ], 28 | ) 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_ignore_migration/migrations/0002_ignore_migration.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.4 on 2019-03-21 20:41 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | import django_migration_linter as linter 8 | 9 | 10 | class Migration(migrations.Migration): 11 | dependencies = [("app_ignore_migration", "0001_initial")] 12 | 13 | operations = [ 14 | linter.IgnoreMigration(), 15 | migrations.AddField( 16 | model_name="b", 17 | name="null_field_real", 18 | field=models.IntegerField(default=1), 19 | preserve_default=False, 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /tests/test_project/app_ignore_migration/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_ignore_migration/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_ignore_migration/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class B(models.Model): 7 | null_field = models.IntegerField() 8 | null_field_real = models.IntegerField(null=False) 9 | -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_django_default/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_make_not_null_with_django_default/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_django_default/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-06-20 15:17 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("col", models.CharField(max_length=10, null=True)), 27 | ], 28 | ), 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_django_default/migrations/0002_make_not_null_with_django_default.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-06-20 15:17 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [ 10 | ("app_make_not_null_with_django_default", "0001_initial"), 11 | ] 12 | 13 | operations = [ 14 | migrations.AlterField( 15 | model_name="a", 16 | name="col", 17 | field=models.CharField(default="empty", max_length=10), 18 | ), 19 | ] 20 | -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_django_default/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_make_not_null_with_django_default/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_django_default/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | col = models.CharField(max_length=10, null=False, default="empty") 8 | -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_lib_default/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_make_not_null_with_lib_default/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_lib_default/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-06-20 15:23 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("col", models.CharField(max_length=10, null=True)), 27 | ], 28 | ), 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_lib_default/migrations/0002_make_not_null_with_lib_default.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-06-20 15:23 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | from django_add_default_value import AddDefaultValue 7 | 8 | 9 | class Migration(migrations.Migration): 10 | dependencies = [ 11 | ("app_make_not_null_with_lib_default", "0001_initial"), 12 | ] 13 | 14 | operations = [ 15 | migrations.AlterField( 16 | model_name="a", 17 | name="col", 18 | field=models.CharField(default="avalue", max_length=10), 19 | ), 20 | AddDefaultValue(model_name="a", name="col", value="avalue"), 21 | ] 22 | -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_lib_default/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_make_not_null_with_lib_default/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_make_not_null_with_lib_default/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | col = models.CharField(max_length=10, null=False, default="avalue") 8 | -------------------------------------------------------------------------------- /tests/test_project/app_rename_column/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_rename_column/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_rename_column/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 15:02 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field", models.IntegerField()), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_rename_column/migrations/0002_auto_20190414_1502.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 15:02 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations 7 | 8 | 9 | class Migration(migrations.Migration): 10 | dependencies = [("app_rename_column", "0001_initial")] 11 | 12 | operations = [ 13 | migrations.RenameField(model_name="a", old_name="field", new_name="renamed") 14 | ] 15 | -------------------------------------------------------------------------------- /tests/test_project/app_rename_column/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_rename_column/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_rename_column/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | renamed = models.IntegerField() 8 | -------------------------------------------------------------------------------- /tests/test_project/app_rename_table/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_rename_table/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_rename_table/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 15:00 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="A", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ("field", models.IntegerField()), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_rename_table/migrations/0002_auto_20190414_1500.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 1.11.18 on 2019-04-14 15:00 2 | 3 | 4 | from __future__ import annotations 5 | 6 | from django.db import migrations 7 | 8 | 9 | class Migration(migrations.Migration): 10 | dependencies = [("app_rename_table", "0001_initial")] 11 | 12 | operations = [migrations.RenameModel(old_name="A", new_name="B")] 13 | -------------------------------------------------------------------------------- /tests/test_project/app_rename_table/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_rename_table/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_rename_table/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class B(models.Model): 7 | field = models.IntegerField() 8 | -------------------------------------------------------------------------------- /tests/test_project/app_unique_together/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_unique_together/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_unique_together/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2019-07-29 21:21 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("int_field", models.IntegerField()), 27 | ("char_field", models.CharField(max_length=255)), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_unique_together/migrations/0002_auto_20190729_2122.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2019-07-29 21:22 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [("app_unique_together", "0001_initial")] 10 | 11 | operations = [ 12 | migrations.AlterUniqueTogether( 13 | name="a", unique_together={("int_field", "char_field")} 14 | ) 15 | ] 16 | -------------------------------------------------------------------------------- /tests/test_project/app_unique_together/migrations/0003_auto_20190729_2122.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2019-07-29 21:22 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [("app_unique_together", "0002_auto_20190729_2122")] 10 | 11 | operations = [migrations.AlterUniqueTogether(name="a", unique_together=set())] 12 | -------------------------------------------------------------------------------- /tests/test_project/app_unique_together/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_unique_together/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_unique_together/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | int_field = models.IntegerField() 8 | char_field = models.CharField(max_length=255) 9 | 10 | # class Meta: 11 | # unique_together = (("int_field", "char_field"),) 12 | -------------------------------------------------------------------------------- /tests/test_project/app_with_custom_name/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_with_custom_name/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_with_custom_name/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class DefaultConfig(AppConfig): 7 | name = "tests.test_project.app_with_custom_name" 8 | label = "my_custom_name" 9 | -------------------------------------------------------------------------------- /tests/test_project/app_with_custom_name/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2019-07-29 21:21 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("int_field", models.IntegerField()), 27 | ("char_field", models.CharField(max_length=255)), 28 | ], 29 | ) 30 | ] 31 | -------------------------------------------------------------------------------- /tests/test_project/app_with_custom_name/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/app_with_custom_name/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/app_with_custom_name/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | int_field = models.IntegerField() 8 | char_field = models.CharField(max_length=255) 9 | -------------------------------------------------------------------------------- /tests/test_project/makemigrations_backward_incompatible_migration_missing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/makemigrations_backward_incompatible_migration_missing/__init__.py -------------------------------------------------------------------------------- /tests/test_project/makemigrations_backward_incompatible_migration_missing/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-06-26 17:49 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("x", models.IntegerField()), 27 | ], 28 | ), 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/makemigrations_backward_incompatible_migration_missing/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/makemigrations_backward_incompatible_migration_missing/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/makemigrations_backward_incompatible_migration_missing/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | x = models.IntegerField() 8 | new_field = models.CharField(null=False, default="empty", max_length=255) 9 | -------------------------------------------------------------------------------- /tests/test_project/makemigrations_correct_migration_missing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/makemigrations_correct_migration_missing/__init__.py -------------------------------------------------------------------------------- /tests/test_project/makemigrations_correct_migration_missing/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2020-06-26 15:57 2 | 3 | from __future__ import annotations 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="A", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("x", models.IntegerField()), 27 | ], 28 | ), 29 | ] 30 | -------------------------------------------------------------------------------- /tests/test_project/makemigrations_correct_migration_missing/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/test_project/makemigrations_correct_migration_missing/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_project/makemigrations_correct_migration_missing/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from django.db import models 4 | 5 | 6 | class A(models.Model): 7 | x = models.IntegerField() 8 | new_field = models.CharField(null=True, max_length=255) 9 | -------------------------------------------------------------------------------- /tests/test_project/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for test_project project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | from __future__ import annotations 14 | 15 | import os 16 | 17 | import django 18 | 19 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 20 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 21 | 22 | 23 | # Quick-start development settings - unsuitable for production 24 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 25 | 26 | # SECURITY WARNING: keep the secret key used in production secret! 27 | SECRET_KEY = "dummy" 28 | 29 | # SECURITY WARNING: don't run with debug turned on in production! 30 | DEBUG = True 31 | 32 | ALLOWED_HOSTS = [] 33 | 34 | 35 | # Application definition 36 | 37 | INSTALLED_APPS = [ 38 | "django.contrib.admin", 39 | "django.contrib.auth", 40 | "django.contrib.contenttypes", 41 | "django.contrib.sessions", 42 | "django.contrib.messages", 43 | "django.contrib.staticfiles", 44 | "django_migration_linter", 45 | "tests.test_project.app_add_manytomany_field", 46 | "tests.test_project.app_add_not_null_column", 47 | "tests.test_project.app_add_not_null_column_followed_by_default", 48 | "tests.test_project.app_alter_column", 49 | "tests.test_project.app_alter_column_drop_not_null", 50 | "tests.test_project.app_correct", 51 | "tests.test_project.app_create_table_with_not_null_column", 52 | "tests.test_project.app_drop_column", 53 | "tests.test_project.app_drop_table", 54 | "tests.test_project.app_ignore_migration", 55 | "tests.test_project.app_rename_column", 56 | "tests.test_project.app_rename_table", 57 | "tests.test_project.app_unique_together", 58 | "tests.test_project.app_data_migrations", 59 | "tests.test_project.app_make_not_null_with_django_default", 60 | "tests.test_project.app_make_not_null_with_lib_default", 61 | "tests.test_project.app_create_index_exclusive", 62 | "tests.test_project.app_with_custom_name.apps.DefaultConfig", 63 | ] 64 | 65 | if django.VERSION[0] >= 5: 66 | # db_default attribute was only added in Django 5.0 67 | INSTALLED_APPS.append( 68 | "tests.test_project.app_add_not_null_column_followed_by_db_default" 69 | ) 70 | 71 | MIDDLEWARE = [ 72 | "django.middleware.security.SecurityMiddleware", 73 | "django.contrib.sessions.middleware.SessionMiddleware", 74 | "django.middleware.common.CommonMiddleware", 75 | "django.middleware.csrf.CsrfViewMiddleware", 76 | "django.contrib.auth.middleware.AuthenticationMiddleware", 77 | "django.contrib.messages.middleware.MessageMiddleware", 78 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 79 | ] 80 | 81 | ROOT_URLCONF = "tests.test_project.urls" 82 | 83 | TEMPLATES = [ 84 | { 85 | "BACKEND": "django.template.backends.django.DjangoTemplates", 86 | "DIRS": [], 87 | "APP_DIRS": True, 88 | "OPTIONS": { 89 | "context_processors": [ 90 | "django.template.context_processors.debug", 91 | "django.template.context_processors.request", 92 | "django.contrib.auth.context_processors.auth", 93 | "django.contrib.messages.context_processors.messages", 94 | ] 95 | }, 96 | } 97 | ] 98 | 99 | WSGI_APPLICATION = "tests.test_project.wsgi.application" 100 | 101 | 102 | DATABASES = { 103 | "default": { 104 | "ENGINE": "django.db.backends.sqlite3", 105 | "NAME": os.path.join(BASE_DIR, "db.sqlite3"), 106 | "TEST": {"DEPENDENCIES": []}, 107 | }, 108 | "sqlite": { 109 | "ENGINE": "django.db.backends.sqlite3", 110 | "NAME": "sqlite3", 111 | "TEST": {"DEPENDENCIES": []}, 112 | }, 113 | "postgresql": { 114 | "ENGINE": "django.db.backends.postgresql", 115 | "NAME": "django_migration_linter_test_project", 116 | "USER": "postgres", 117 | "PASSWORD": "postgres", 118 | "HOST": "127.0.0.1", 119 | "TEST": {"DEPENDENCIES": []}, 120 | }, 121 | "mysql": { 122 | "ENGINE": "django.db.backends.mysql", 123 | "NAME": "django_migration_linter_test_project", 124 | "USER": "root", 125 | "PASSWORD": "", 126 | "HOST": "127.0.0.1", 127 | "TEST": {"DEPENDENCIES": []}, 128 | }, 129 | } 130 | 131 | 132 | # Password validation 133 | 134 | AUTH_PASSWORD_VALIDATORS = [ 135 | { 136 | "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" 137 | }, 138 | {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, 139 | {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, 140 | {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, 141 | ] 142 | 143 | 144 | # Internationalization 145 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 146 | 147 | LANGUAGE_CODE = "en-us" 148 | 149 | TIME_ZONE = "UTC" 150 | 151 | USE_I18N = True 152 | 153 | USE_L10N = True 154 | 155 | USE_TZ = True 156 | 157 | 158 | # Static files (CSS, JavaScript, Images) 159 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 160 | 161 | STATIC_URL = "/static/" 162 | 163 | DEFAULT_AUTO_FIELD = "django.db.models.AutoField" 164 | -------------------------------------------------------------------------------- /tests/test_project/urls.py: -------------------------------------------------------------------------------- 1 | """test_project URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | 17 | from __future__ import annotations 18 | 19 | from django.contrib import admin 20 | from django.urls import path 21 | 22 | urlpatterns = [path("admin/", admin.site.urls)] 23 | -------------------------------------------------------------------------------- /tests/test_project/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for test_project project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | from __future__ import annotations 11 | 12 | import os 13 | 14 | from django.core.wsgi import get_wsgi_application 15 | 16 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") 17 | 18 | application = get_wsgi_application() 19 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-migration-linter/e85076f12bd5a766b92e939d46f1fc5fd74907b5/tests/unit/__init__.py -------------------------------------------------------------------------------- /tests/unit/test_linter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import tempfile 4 | import unittest 5 | from unittest.mock import patch 6 | 7 | from django.db import ProgrammingError 8 | from django.db.migrations import Migration 9 | 10 | from django_migration_linter import MigrationLinter 11 | 12 | 13 | class LinterFunctionsTestCase(unittest.TestCase): 14 | def test_get_sql(self): 15 | linter = MigrationLinter() 16 | sql_statements = linter.get_sql("app_add_not_null_column", "0001") 17 | self.assertEqual(len(sql_statements), 6) 18 | self.assertEqual(sql_statements[0], "BEGIN;") 19 | self.assertEqual(sql_statements[-1], "COMMIT;") 20 | 21 | def test_has_errors(self): 22 | linter = MigrationLinter(database="mysql") 23 | self.assertFalse(linter.has_errors) 24 | 25 | m = Migration("0001_create_table", "app_add_not_null_column") 26 | linter.lint_migration(m) 27 | self.assertFalse(linter.has_errors) 28 | 29 | m = Migration("0002_add_new_not_null_field", "app_add_not_null_column") 30 | linter.lint_migration(m) 31 | self.assertTrue(linter.has_errors) 32 | 33 | m = Migration("0001_create_table", "app_add_not_null_column") 34 | linter.lint_migration(m) 35 | self.assertTrue(linter.has_errors) 36 | 37 | def test_ignore_migration_include_apps(self): 38 | linter = MigrationLinter(include_apps=("app_add_not_null_column",)) 39 | self.assertTrue(linter.should_ignore_migration("app_correct", "0001")) 40 | self.assertTrue(linter.should_ignore_migration("app_correct", "0002")) 41 | self.assertFalse( 42 | linter.should_ignore_migration("app_add_not_null_column", "0001") 43 | ) 44 | 45 | def test_ignore_migration_exclude_apps(self): 46 | linter = MigrationLinter(exclude_apps=("app_add_not_null_column",)) 47 | self.assertFalse(linter.should_ignore_migration("app_correct", "0001")) 48 | self.assertFalse(linter.should_ignore_migration("app_correct", "0002")) 49 | self.assertTrue( 50 | linter.should_ignore_migration("app_add_not_null_column", "0001") 51 | ) 52 | 53 | def test_ignore_migration_name_contains(self): 54 | linter = MigrationLinter(ignore_name_contains="foo") 55 | self.assertFalse(linter.should_ignore_migration("app_correct", "0001_initial")) 56 | self.assertTrue(linter.should_ignore_migration("app_correct", "0002_foo")) 57 | 58 | def test_ignore_migration_full_name(self): 59 | linter = MigrationLinter(ignore_name=("0002_foo",)) 60 | self.assertFalse(linter.should_ignore_migration("app_correct", "0001_initial")) 61 | self.assertTrue(linter.should_ignore_migration("app_correct", "0002_foo")) 62 | 63 | def test_include_migration_name_contains(self): 64 | linter = MigrationLinter(include_name_contains="foo") 65 | self.assertTrue(linter.should_ignore_migration("app_correct", "0001_initial")) 66 | self.assertFalse(linter.should_ignore_migration("app_correct", "0002_foo")) 67 | 68 | def test_include_migration_full_name(self): 69 | linter = MigrationLinter(include_name=("0002_foo",)) 70 | self.assertTrue(linter.should_ignore_migration("app_correct", "0001_initial")) 71 | self.assertFalse(linter.should_ignore_migration("app_correct", "0002_foo")) 72 | 73 | def test_include_migration_multiple_names(self): 74 | linter = MigrationLinter(include_name=("0002_foo", "0003_bar")) 75 | self.assertTrue(linter.should_ignore_migration("app_correct", "0001_initial")) 76 | self.assertFalse(linter.should_ignore_migration("app_correct", "0002_foo")) 77 | self.assertFalse(linter.should_ignore_migration("app_correct", "0003_bar")) 78 | 79 | def test_gather_all_migrations(self): 80 | linter = MigrationLinter() 81 | migrations = linter._gather_all_migrations() 82 | self.assertGreater(len(list(migrations)), 1) 83 | 84 | def test_ignore_unapplied_migrations(self): 85 | linter = MigrationLinter(only_applied_migrations=True) 86 | linter.migration_loader.applied_migrations = {("app_correct", "0002_foo")} 87 | 88 | self.assertTrue(linter.should_ignore_migration("app_correct", "0001_initial")) 89 | self.assertFalse(linter.should_ignore_migration("app_correct", "0002_foo")) 90 | 91 | def test_ignore_applied_migrations(self): 92 | linter = MigrationLinter(only_unapplied_migrations=True) 93 | linter.migration_loader.applied_migrations = {("app_correct", "0002_foo")} 94 | 95 | self.assertFalse(linter.should_ignore_migration("app_correct", "0001_initial")) 96 | self.assertTrue(linter.should_ignore_migration("app_correct", "0002_foo")) 97 | 98 | def test_exclude_migration_tests(self): 99 | m = Migration("0002_add_new_not_null_field", "app_add_not_null_column") 100 | 101 | linter = MigrationLinter(exclude_migration_tests=[], database="mysql") 102 | linter.lint_migration(m) 103 | self.assertTrue(linter.has_errors) 104 | 105 | linter = MigrationLinter(exclude_migration_tests=["NOT_NULL"], database="mysql") 106 | linter.lint_migration(m) 107 | self.assertFalse(linter.has_errors) 108 | 109 | def test_read_migrations_unknown_file(self): 110 | file_path = "unknown_file" 111 | with self.assertRaises(Exception): 112 | MigrationLinter.read_migrations_list(file_path) 113 | 114 | @patch( 115 | "django_migration_linter.migration_linter.call_command", 116 | side_effect=ProgrammingError, 117 | ) 118 | def test_raise_exception_on_sqlmigrate_error(self, call_command_mock): 119 | linter = MigrationLinter( 120 | exclude_migration_tests=[], database="mysql", ignore_sqlmigrate_errors=False 121 | ) 122 | with self.assertRaises(ProgrammingError): 123 | linter.get_sql("app_correct", "0002_foo") 124 | 125 | @patch( 126 | "django_migration_linter.migration_linter.call_command", 127 | side_effect=ProgrammingError, 128 | ) 129 | def test_ignore_exception_on_sqlmigrate_error(self, call_command_mock): 130 | linter = MigrationLinter( 131 | exclude_migration_tests=[], database="mysql", ignore_sqlmigrate_errors=True 132 | ) 133 | sql_result = linter.get_sql("app_correct", "0002_foo") 134 | self.assertEqual([], sql_result) 135 | 136 | def test_read_migrations_no_file(self): 137 | migration_list = MigrationLinter.read_migrations_list(None) 138 | self.assertIsNone(migration_list) 139 | 140 | def test_read_migrations_empty_file(self): 141 | with tempfile.NamedTemporaryFile() as tmp: 142 | migration_list = MigrationLinter.read_migrations_list(tmp.name) 143 | self.assertEqual([], migration_list) 144 | 145 | def test_read_migrations_from_file(self): 146 | tmp = tempfile.NamedTemporaryFile(mode="w", delete=False) 147 | tmp.write( 148 | "test_project/app_add_not_null_column/migrations/0001_create_table.py\n" 149 | ) 150 | tmp.write("unknown\n") 151 | tmp.write( 152 | "test_project/app_add_not_null_column/migrations/0002_add_new_not_null_field.py\n" 153 | ) 154 | tmp.close() 155 | migration_list = MigrationLinter.read_migrations_list(tmp.name) 156 | self.assertEqual( 157 | [ 158 | ("app_add_not_null_column", "0001_create_table"), 159 | ("app_add_not_null_column", "0002_add_new_not_null_field"), 160 | ], 161 | migration_list, 162 | ) 163 | 164 | def test_gather_migrations_with_list(self): 165 | linter = MigrationLinter() 166 | migrations = linter._gather_all_migrations( 167 | migrations_list=[ 168 | ("app_add_not_null_column", "0001_create_table"), 169 | ("app_add_not_null_column", "0002_add_new_not_null_field"), 170 | ] 171 | ) 172 | self.assertEqual(2, len(list(migrations))) 173 | 174 | def test_ignore_initial_migrations(self): 175 | linter = MigrationLinter(ignore_initial_migrations=True) 176 | 177 | self.assertTrue( 178 | linter.should_ignore_migration( 179 | "app_correct", "0001_initial", is_initial=True 180 | ) 181 | ) 182 | self.assertFalse( 183 | linter.should_ignore_migration("app_correct", "0002_foo", is_initial=False) 184 | ) 185 | -------------------------------------------------------------------------------- /tests/unit/test_utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import unittest 4 | 5 | from django_migration_linter.utils import split_migration_path, split_path 6 | 7 | 8 | class SplitPathTestCase(unittest.TestCase): 9 | def test_split_path(self): 10 | split = split_path("foo/bar/fuz.py") 11 | self.assertEqual(split, ["foo", "bar", "fuz.py"]) 12 | 13 | def test_split_full_path(self): 14 | split = split_path("/foo/bar/fuz.py") 15 | self.assertEqual(split, ["/", "foo", "bar", "fuz.py"]) 16 | 17 | def test_split_folder_path(self): 18 | split = split_path("/foo/bar") 19 | self.assertEqual(split, ["/", "foo", "bar"]) 20 | 21 | def test_split_folder_path_trailing_slash(self): 22 | split = split_path("/foo/bar/") 23 | self.assertEqual(split, ["/", "foo", "bar"]) 24 | 25 | def test_split_folder_path_trailing_slashes(self): 26 | split = split_path("/foo/bar///") 27 | self.assertEqual(split, ["/", "foo", "bar"]) 28 | 29 | def test_split_migration_long_path(self): 30 | input_path = "apps/the_app/migrations/0001_stuff.py" 31 | app, mig = split_migration_path(input_path) 32 | self.assertEqual(app, "the_app") 33 | self.assertEqual(mig, "0001_stuff") 34 | 35 | def test_split_migration_path(self): 36 | input_path = "the_app/migrations/0001_stuff.py" 37 | app, mig = split_migration_path(input_path) 38 | self.assertEqual(app, "the_app") 39 | self.assertEqual(mig, "0001_stuff") 40 | 41 | def test_split_migration_full_path(self): 42 | input_path = "/home/user/djangostuff/apps/the_app/migrations/0001_stuff.py" 43 | app, mig = split_migration_path(input_path) 44 | self.assertEqual(app, "the_app") 45 | self.assertEqual(mig, "0001_stuff") 46 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py{39,310}-django32 4 | py{39,310}-django40 5 | py{39,310,311,312}-django41 6 | py{39,310,311,312}-django42 7 | py{310,311,312}-django50 8 | py{310,311,312,313}-django51 9 | py{310,311,312,313}-django52 10 | lint 11 | coverage 12 | 13 | [gh-actions] 14 | python = 15 | 3.9: py39 16 | 3.10: py310 17 | 3.11: py311 18 | 3.12: py312 19 | 3.13: py313 20 | 21 | [testenv] 22 | allowlist_externals = ./manage.py 23 | commands = ./manage.py test --no-input {posargs} 24 | extras = test 25 | pip_pre = true 26 | deps = 27 | django22: django>=2.2,<2.3 28 | django32: django>=3.2,<3.3 29 | django40: django>=4.0,<4.1 30 | django41: django>=4.1,<4.2 31 | django42: django>=4.2,<4.3 32 | django50: django>=5.0,<5.1 33 | django51: django>=5.1,<5.2 34 | django52: django>=5.2,<5.3 35 | 36 | [testenv:lint] 37 | basepython = python3.12 38 | deps = pre-commit 39 | commands = pre-commit run --all-files --show-diff-on-failure 40 | 41 | [testenv:coverage] 42 | commands = 43 | coverage run manage.py test --no-input {posargs} 44 | coverage xml -i 45 | extras = test 46 | pip_pre = true 47 | 48 | [flake8] 49 | max-line-length=88 50 | ignore=E203,W503 51 | --------------------------------------------------------------------------------