API Reference¶
This page documents the public Python API for django-safe-migrations.
MigrationAnalyzer¶
django_safe_migrations.analyzer.MigrationAnalyzer
¶
Analyzes Django migrations for unsafe operations.
The analyzer checks migrations against a set of rules and returns any issues found. It can analyze individual migrations, all migrations for an app, or all migrations in the project.
Configuration can be provided via Django settings::
SAFE_MIGRATIONS = {
"DISABLED_RULES": ["SM006", "SM008"],
"RULE_SEVERITY": {"SM002": "INFO"},
"EXCLUDED_APPS": ["myapp"],
}
Example
analyzer = MigrationAnalyzer() issues = analyzer.analyze_all() for issue in issues: ... print(issue)
Source code in django_safe_migrations/analyzer.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | |
__init__(rules=None, db_vendor=None, disabled_rules=None, verbose=False, cache=None, check_reverse=False)
¶
Initialize the analyzer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rules
|
Optional[list[BaseRule]]
|
List of rules to check. If None, all rules for the database vendor will be used. |
None
|
db_vendor
|
Optional[str]
|
Database vendor (e.g., 'postgresql'). If None, it will be detected from Django settings. |
None
|
disabled_rules
|
Optional[list[str]]
|
List of rule IDs to disable. If None, uses SAFE_MIGRATIONS["DISABLED_RULES"] from settings. |
None
|
verbose
|
bool
|
If True, print progress information to stderr. |
False
|
cache
|
Optional[Any]
|
Optional |
None
|
check_reverse
|
bool
|
If True, also analyse each migration's rollback path for destructive operations (RV0xx issues). |
False
|
Source code in django_safe_migrations/analyzer.py
analyze_all(exclude_apps=None)
¶
Analyze all migrations in the project.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_apps
|
Optional[list[str]]
|
List of app labels to exclude (e.g., Django's built-in apps). If None, uses SAFE_MIGRATIONS["EXCLUDED_APPS"] from settings. |
None
|
Returns:
| Type | Description |
|---|---|
list[Issue]
|
A list of Issue objects found in all migrations. |
Source code in django_safe_migrations/analyzer.py
analyze_app(app_label, loader=None)
¶
Analyze all migrations for a Django app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
str
|
The app label (e.g., 'myapp'). |
required |
loader
|
Any
|
Optional pre-built |
None
|
Returns:
| Type | Description |
|---|---|
list[Issue]
|
A list of Issue objects found in the app's migrations. |
Source code in django_safe_migrations/analyzer.py
analyze_migration(migration, app_label=None, migration_name=None, loader=None)
¶
Analyze a single migration for issues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
migration
|
Migration
|
The Django migration to analyze. |
required |
app_label
|
Optional[str]
|
Optional app label override. |
None
|
migration_name
|
Optional[str]
|
Optional migration name override. |
None
|
loader
|
Optional[Any]
|
Optional pre-built |
None
|
Returns:
| Type | Description |
|---|---|
list[Issue]
|
A list of Issue objects found in the migration. |
Source code in django_safe_migrations/analyzer.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
analyze_new_migrations(app_label=None, exclude_apps=None)
¶
Analyze only unapplied (new) migrations.
This is useful for CI/CD pipelines to only check migrations that haven't been applied yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
Optional[str]
|
Optional app label to filter by. |
None
|
exclude_apps
|
Optional[list[str]]
|
List of app labels to exclude (e.g., Django's built-in apps). If None, uses SAFE_MIGRATIONS["EXCLUDED_APPS"] from settings. |
None
|
Returns:
| Type | Description |
|---|---|
list[Issue]
|
A list of Issue objects found in unapplied migrations. |
Source code in django_safe_migrations/analyzer.py
get_summary(issues)
staticmethod
¶
Get a summary of the issues found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
issues
|
list[Issue]
|
List of issues to summarize. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with counts by severity and rule. |
Source code in django_safe_migrations/analyzer.py
options: show_root_heading: true show_source: false members: - init - analyze_migration - analyze_app - analyze_all - analyze_new_migrations - get_summary
Basic Usage¶
from django_safe_migrations import MigrationAnalyzer
# Create analyzer
analyzer = MigrationAnalyzer()
# Analyze all migrations
issues = analyzer.analyze_all()
# Analyze specific app
issues = analyzer.analyze_app('myapp')
# Analyze only unapplied migrations
issues = analyzer.analyze_new_migrations()
# Get summary
summary = analyzer.get_summary(issues)
print(f"Found {summary['total']} issues")
print(f"Errors: {summary['by_severity']['error']}")
print(f"Warnings: {summary['by_severity']['warning']}")
Custom Configuration¶
from django_safe_migrations import MigrationAnalyzer
# Disable specific rules
analyzer = MigrationAnalyzer(disabled_rules=["SM006", "SM008"])
# Target specific database
analyzer = MigrationAnalyzer(db_vendor="postgresql")
# Use custom rules
from django_safe_migrations.rules import get_all_rules
custom_rules = [r for r in get_all_rules() if r.rule_id.startswith("SM01")]
analyzer = MigrationAnalyzer(rules=custom_rules)
Issue¶
django_safe_migrations.rules.base.Issue
dataclass
¶
Represents an issue found in a migration.
Attributes:
| Name | Type | Description |
|---|---|---|
rule_id |
str
|
Unique identifier for the rule (e.g., 'SM001'). |
severity |
Severity
|
How serious the issue is. |
operation |
str
|
String representation of the problematic operation. |
message |
str
|
Human-readable description of the issue. |
suggestion |
Optional[str]
|
Optional fix suggestion. |
file_path |
Optional[str]
|
Path to the migration file. |
line_number |
Optional[int]
|
Line number in the migration file. |
app_label |
Optional[str]
|
The Django app label. |
migration_name |
Optional[str]
|
The migration name (e.g., '0002_add_field'). |
operation_index |
Optional[int]
|
Index of the operation within the migration's
|
Source code in django_safe_migrations/rules/base.py
__str__()
¶
Return a string representation of the issue.
Source code in django_safe_migrations/rules/base.py
from_dict(data)
classmethod
¶
Reconstruct an Issue from its :meth:to_dict representation.
Used by the analysis cache to round-trip issues to/from disk. The
severity value is mapped back to the :class:Severity enum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
A dict produced by :meth: |
required |
Returns:
| Type | Description |
|---|---|
'Issue'
|
The reconstructed :class: |
Source code in django_safe_migrations/rules/base.py
to_dict()
¶
Convert the issue to a dictionary for JSON serialization.
Source code in django_safe_migrations/rules/base.py
options: show_root_heading: true show_source: false
Working with Issues¶
from django_safe_migrations import MigrationAnalyzer, Severity
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
for issue in issues:
# Access issue properties
print(f"Rule: {issue.rule_id}")
print(f"Severity: {issue.severity.value}")
print(f"Message: {issue.message}")
print(f"File: {issue.file_path}:{issue.line_number}")
print(f"Suggestion: {issue.suggestion}")
print()
# Convert to dict (for JSON serialization)
issue_dict = issue.to_dict()
# Filter by severity
errors = [i for i in issues if i.severity == Severity.ERROR]
warnings = [i for i in issues if i.severity == Severity.WARNING]
Severity¶
django_safe_migrations.rules.base.Severity
¶
Bases: Enum
Severity levels for migration issues.
Source code in django_safe_migrations/rules/base.py
options: show_root_heading: true show_source: false
Severity Levels¶
| Level | Value | Description |
|---|---|---|
ERROR |
"error" |
Will likely break production |
WARNING |
"warning" |
Might cause issues under load |
INFO |
"info" |
Best practice recommendation |
from django_safe_migrations import Severity
# Compare severities
if issue.severity == Severity.ERROR:
print("Critical issue!")
# Get string value
print(issue.severity.value) # "error", "warning", or "info"
Reporters¶
ConsoleReporter¶
Outputs colorized, human-readable reports to the terminal.
from django_safe_migrations import MigrationAnalyzer
from django_safe_migrations.reporters import ConsoleReporter
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
reporter = ConsoleReporter(show_suggestions=True)
reporter.report(issues)
JsonReporter¶
Outputs machine-readable JSON for CI/CD pipelines.
from django_safe_migrations import MigrationAnalyzer
from django_safe_migrations.reporters import JsonReporter
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
reporter = JsonReporter()
reporter.report(issues) # Prints JSON to stdout
Output format:
{
"issues": [
{
"rule_id": "SM001",
"severity": "error",
"operation": "AddField(user.email)",
"message": "Adding NOT NULL field 'email' without a default",
"suggestion": "Add as nullable first, backfill, then add NOT NULL",
"file_path": "myapp/migrations/0002_add_email.py",
"line_number": 15,
"app_label": "myapp",
"migration_name": "0002_add_email"
}
],
"summary": {
"total": 1,
"errors": 1,
"warnings": 0,
"info": 0
}
}
GithubReporter¶
Outputs GitHub Actions workflow commands for inline PR annotations.
from django_safe_migrations import MigrationAnalyzer
from django_safe_migrations.reporters import GithubReporter
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
reporter = GithubReporter()
reporter.report(issues)
Output format:
::error file=myapp/migrations/0002_add_email.py,line=15::[SM001] Adding NOT NULL field 'email' without a default
GitLabReporter¶
Outputs issues in GitLab Code Quality JSON format for merge request integration.
from django_safe_migrations import MigrationAnalyzer
from django_safe_migrations.reporters.gitlab import GitLabReporter
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
reporter = GitLabReporter()
reporter.report(issues)
SarifReporter¶
Outputs issues in SARIF 2.1.0 format for GitHub Code Scanning.
from django_safe_migrations import MigrationAnalyzer
from django_safe_migrations.reporters.sarif import SarifReporter
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
reporter = SarifReporter()
reporter.report(issues)
GitHubPRReporter¶
Outputs a Markdown summary (grouped by migration file) suitable for posting as a
single pull-request comment. It performs no network I/O — a CI step posts the
rendered body, e.g. gh pr comment "$PR" --body-file comment.md.
from django_safe_migrations import MigrationAnalyzer
from django_safe_migrations.reporters.github_pr import GitHubPRReporter
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
reporter = GitHubPRReporter()
reporter.report(issues)
Using get_reporter()¶
from django_safe_migrations.reporters import get_reporter
# Get reporter by name
reporter = get_reporter("console", show_suggestions=True)
reporter = get_reporter("json")
reporter = get_reporter("github")
reporter = get_reporter("github-pr")
reporter = get_reporter("gitlab")
reporter = get_reporter("sarif")
Creating Custom Rules¶
You can create custom rules by extending BaseRule:
from typing import Optional
from django.db import migrations
from django_safe_migrations.rules.base import BaseRule, Issue, Severity
class NoRawSqlRule(BaseRule):
"""Detect raw SQL that might be dangerous."""
rule_id = "CUSTOM001"
severity = Severity.WARNING
description = "Raw SQL detected in migration"
def check(self, operation, migration, **kwargs) -> Optional[Issue]:
if not isinstance(operation, migrations.RunSQL):
return None
sql = operation.sql if isinstance(operation.sql, str) else str(operation.sql)
# Check for dangerous patterns
dangerous = ["DROP", "TRUNCATE", "DELETE FROM"]
for pattern in dangerous:
if pattern in sql.upper():
return self.create_issue(
operation=operation,
message=f"Dangerous SQL pattern detected: {pattern}",
migration=migration,
)
return None
def get_suggestion(self, operation) -> str:
return "Review this SQL carefully and add reverse_sql for safety."
# Use custom rule
from django_safe_migrations import MigrationAnalyzer
from django_safe_migrations.rules import get_all_rules
rules = get_all_rules() + [NoRawSqlRule()]
analyzer = MigrationAnalyzer(rules=rules)
Module Exports¶
The main module exports these public names:
from django_safe_migrations import (
MigrationAnalyzer, # Main analyzer class
Issue, # Issue dataclass
Severity, # Severity enum
__version__, # Package version string
)
Baseline, Diff, and Interactive APIs¶
Baseline¶
from django_safe_migrations.baseline import (
generate_baseline,
load_baseline,
filter_baselined_issues,
)
# Generate a baseline file from current issues
analyzer = MigrationAnalyzer()
issues = analyzer.analyze_all()
count = generate_baseline(issues, ".migration-baseline.json")
# Load and filter against baseline
baseline = load_baseline(".migration-baseline.json")
new_issues = filter_baselined_issues(issues, baseline)
Diff Mode¶
from django_safe_migrations.diff import (
get_changed_migration_files,
get_changed_apps_and_migrations,
)
# Get migration files changed since a branch
files = get_changed_migration_files("main")
# Get (app_label, migration_name) pairs
changed = get_changed_apps_and_migrations("main")