pg-migration-lint 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,47 @@
1
+ import configparser
2
+ import re
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ RUNNING = re.compile(r"^-- Running upgrade (.*?) -> (\S+)", re.MULTILINE)
8
+
9
+
10
+ def generate_sql(rng: str, config: Path) -> str:
11
+ result = subprocess.run(
12
+ [sys.executable, "-m", "alembic", "-c", str(config), "upgrade", rng, "--sql"],
13
+ capture_output=True,
14
+ text=True,
15
+ encoding="utf-8",
16
+ check=False,
17
+ )
18
+ if result.returncode != 0:
19
+ raise RuntimeError(result.stderr.strip() or "alembic failed")
20
+ return result.stdout
21
+
22
+
23
+ def split_by_revision(sql: str) -> list[tuple[str, str]]:
24
+ """[(revision_id, sql_chunk)]: кусок = текст после маркера до следующего маркера."""
25
+ matches = list(RUNNING.finditer(sql))
26
+ chunks = []
27
+ for i, m in enumerate(matches):
28
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(sql)
29
+ chunks.append((m.group(2).rstrip(","), sql[m.end():end]))
30
+ return chunks
31
+
32
+
33
+ def versions_dir(config: Path) -> Path:
34
+ cp = configparser.ConfigParser(interpolation=None)
35
+ cp.read(config, encoding="utf-8")
36
+ location = cp.get("alembic", "script_location", fallback="alembic")
37
+ location = location.replace("%(here)s", str(config.resolve().parent))
38
+ return Path(location) / "versions"
39
+
40
+
41
+ def find_revision_file(rev: str, versions: Path) -> str:
42
+ pattern = re.compile(
43
+ rf"""^revision\s*(?::\s*str\s*)?=\s*['"]{re.escape(rev)}['"]""", re.MULTILINE)
44
+ for path in versions.glob("*.py"):
45
+ if pattern.search(path.read_text(encoding="utf-8")):
46
+ return str(path)
47
+ return rev # не нашли файл: покажем хотя бы id ревизии
@@ -0,0 +1,158 @@
1
+ from dataclasses import replace
2
+ from enum import Enum
3
+ from pathlib import Path
4
+
5
+ import typer
6
+ from rich.console import Console
7
+ from rich.markup import escape
8
+
9
+ from . import reporters
10
+ from .alembic_support import find_revision_file, generate_sql, split_by_revision, versions_dir
11
+ from .config import load_config
12
+ from .engine import lint_sql, suppressed_ids
13
+ from .models import Finding
14
+ from .rules import ALL_RULES
15
+
16
+ app = typer.Typer(help="Linter for unsafe PostgreSQL migrations.")
17
+ console = Console()
18
+
19
+
20
+ def _version_cb(value: bool):
21
+ if value:
22
+ typer.echo(reporters._version())
23
+ raise typer.Exit()
24
+
25
+
26
+ @app.callback()
27
+ def main(
28
+ version: bool = typer.Option(
29
+ False, "--version", callback=_version_cb, is_eager=True, help="Show version and exit"
30
+ ),
31
+ ):
32
+ """Linter for unsafe PostgreSQL migrations."""
33
+
34
+
35
+ @app.command()
36
+ def explain(rule_id: str = typer.Argument(..., help="Rule id, e.g. MIG001")):
37
+ """Show the details of a rule."""
38
+ rule = next((r for r in ALL_RULES if r.id == rule_id.upper()), None)
39
+ if rule is None:
40
+ console.print(f"[red]Unknown rule:[/] {escape(rule_id)}")
41
+ raise typer.Exit(code=2)
42
+ console.print(f"[bold]{rule.id}[/] {rule.title} ({rule.severity})")
43
+ console.print(f"[yellow]Why:[/] {rule.why}")
44
+ console.print(f"[green]Fix:[/] {rule.fix}")
45
+
46
+
47
+ SKIP_DIRS = {".venv", "venv", "node_modules", ".git", "__pycache__"}
48
+
49
+
50
+ class Format(str, Enum):
51
+ text = "text"
52
+ json = "json"
53
+ sarif = "sarif"
54
+ github = "github"
55
+
56
+
57
+ class FailOn(str, Enum):
58
+ error = "error"
59
+ warning = "warning"
60
+ never = "never"
61
+
62
+
63
+ def _expand(paths: list[Path]) -> list[Path]:
64
+ files: list[Path] = []
65
+ for p in paths:
66
+ if p.is_dir():
67
+ files += sorted(
68
+ f for f in p.rglob("*.sql") if not SKIP_DIRS & set(f.relative_to(p).parts)
69
+ )
70
+ else:
71
+ files.append(p)
72
+ return files
73
+
74
+
75
+ def _print_text(findings: list[Finding]) -> None:
76
+ for f in findings:
77
+ where = f"{f.file}:{f.line}" if f.line else f.file
78
+ color = "red" if f.rule.severity == "error" else "yellow"
79
+ console.print(
80
+ f"{escape(where)} [bold {color}]{f.rule.id}[/] {f.rule.title} "
81
+ f"[dim]({f.rule.severity})[/]"
82
+ )
83
+ if f.snippet:
84
+ console.print(f" [dim]SQL:[/] {escape(f.snippet)}")
85
+ console.print(f" [yellow]Why:[/] {f.rule.why}")
86
+ console.print(f" [green]Fix:[/] {f.rule.fix}\n")
87
+ errors = sum(1 for f in findings if f.rule.severity == "error")
88
+ if findings:
89
+ console.print(
90
+ f"[bold red]{errors} error(s)[/], "
91
+ f"[bold yellow]{len(findings) - errors} warning(s)[/]"
92
+ )
93
+ else:
94
+ console.print("[bold green]No problems found[/]")
95
+
96
+
97
+ def _finish(findings: list[Finding], fmt: Format, output: Path | None, fail_on: FailOn):
98
+ if fmt is Format.text:
99
+ _print_text(findings)
100
+ else:
101
+ render = {
102
+ Format.json: reporters.to_json,
103
+ Format.sarif: reporters.to_sarif,
104
+ Format.github: reporters.to_github,
105
+ }[fmt]
106
+ rendered = render(findings)
107
+ if output:
108
+ output.write_text(rendered, encoding="utf-8")
109
+ else:
110
+ typer.echo(rendered)
111
+ errors = sum(1 for f in findings if f.rule.severity == "error")
112
+ failed = (fail_on is FailOn.error and errors > 0) or (
113
+ fail_on is FailOn.warning and len(findings) > 0
114
+ )
115
+ raise typer.Exit(code=1 if failed else 0)
116
+
117
+
118
+ @app.command()
119
+ def lint(
120
+ paths: list[Path] = typer.Argument(..., exists=True, help="SQL files or directories"), # noqa: B008
121
+ fmt: Format = typer.Option(Format.text, "--format", "-f", help="Output format"), # noqa: B008
122
+ output: Path | None = typer.Option(None, "--output", "-o", help="Write report to file"), # noqa: B008
123
+ fail_on: FailOn = typer.Option(FailOn.error, "--fail-on", help="Exit 1 on: error|warning|never"), # noqa: B008
124
+ ):
125
+ """Lint plain .sql files."""
126
+ cfg = load_config()
127
+ findings: list[Finding] = []
128
+ for path in _expand(paths):
129
+ findings += lint_sql(path.read_text(encoding="utf-8"), str(path), cfg.disable)
130
+ _finish(findings, fmt, output, fail_on)
131
+
132
+
133
+ @app.command("alembic")
134
+ def alembic_cmd(
135
+ rng: str = typer.Option("base:head", "--range", "-r", help="Alembic revision range"),
136
+ config: Path = typer.Option(Path("alembic.ini"), "--config", "-c"), # noqa: B008
137
+ fmt: Format = typer.Option(Format.text, "--format", "-f", help="Output format"), # noqa: B008
138
+ output: Path | None = typer.Option(None, "--output", "-o", help="Write report to file"), # noqa: B008
139
+ fail_on: FailOn = typer.Option(FailOn.error, "--fail-on", help="Exit 1 on: error|warning|never"), # noqa: B008
140
+ ):
141
+ """Run Alembic in offline mode (--sql) and lint the generated SQL."""
142
+ cfg = load_config()
143
+ try:
144
+ sql = generate_sql(rng, config)
145
+ except RuntimeError as e:
146
+ console.print(f"[red]Alembic error:[/] {escape(str(e))}")
147
+ raise typer.Exit(code=2)
148
+
149
+ versions = versions_dir(config)
150
+ findings: list[Finding] = []
151
+ for rev, chunk in split_by_revision(sql):
152
+ path = find_revision_file(rev, versions)
153
+ disabled = set(cfg.disable)
154
+ if Path(path).is_file():
155
+ disabled |= suppressed_ids(Path(path).read_text(encoding="utf-8"))
156
+ findings += [replace(f, line=0) for f in lint_sql(chunk, path, disabled)]
157
+ _finish(findings, fmt, output, fail_on)
158
+
@@ -0,0 +1,20 @@
1
+ import tomllib
2
+ from dataclasses import dataclass, field
3
+ from pathlib import Path
4
+
5
+
6
+ @dataclass
7
+ class Config:
8
+ disable: set[str] = field(default_factory=set)
9
+
10
+
11
+ def load_config(start: Path | None = None) -> Config:
12
+ """Ищет pyproject.toml вверх по дереву от start (по умолчанию cwd)."""
13
+ start = (start or Path.cwd()).resolve()
14
+ for directory in (start, *start.parents):
15
+ path = directory / "pyproject.toml"
16
+ if path.is_file():
17
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
18
+ section = data.get("tool", {}).get("pgmlint", {})
19
+ return Config(disable={s.upper() for s in section.get("disable", [])})
20
+ return Config()
@@ -0,0 +1,75 @@
1
+ import re
2
+
3
+ from pglast import ast, parse_sql
4
+
5
+ from .models import Finding
6
+ from .rules import LOCK_TIMEOUT_RULE, RULES
7
+
8
+ # Комментарий SQL (--) или Python (#). Без \s в классе, чтобы не захватить следующую строку.
9
+ DISABLE_RE = re.compile(r"(?:--|#)\s*pgmlint:\s*disable=([A-Za-z0-9_, \t]+)")
10
+
11
+
12
+ def suppressed_ids(text: str) -> set[str]:
13
+ ids: set[str] = set()
14
+ for m in DISABLE_RE.finditer(text):
15
+ ids |= {s.strip().upper() for s in m.group(1).split(",") if s.strip()}
16
+ return ids
17
+
18
+
19
+ def _first_code_line(text: str) -> tuple[int, str]:
20
+ """Индекс первой строки с кодом (не пустой, не комментарий) и её текст."""
21
+ for i, line in enumerate(text.splitlines()):
22
+ s = line.strip()
23
+ if s and not s.startswith("--"):
24
+ return i, s[:100]
25
+ return 0, ""
26
+
27
+ def _byte_start(sql: str, data: bytes, loc: int) -> int:
28
+ """Смещение начала запроса в байтах (pglast может отдавать и байты, и символы)."""
29
+ if loc <= 0:
30
+ return 0
31
+ if data[loc - 1:loc] == b";": # смещение уже в байтах: перед ним стоит ';'
32
+ return loc
33
+ return len(sql[:loc].encode("utf-8")) # иначе это символы: переводим в байты
34
+
35
+
36
+ def lint_sql(
37
+ sql: str,
38
+ filename: str = "<sql>",
39
+ disabled: frozenset[str] | set[str] = frozenset(),
40
+ ) -> list[Finding]:
41
+ data = sql.encode("utf-8")
42
+ stmts = parse_sql(sql)
43
+
44
+ # у первого запроса берём текст с начала файла, чтобы захватить комментарии над ним
45
+ starts = [0] + [_byte_start(sql, data, s.stmt_location) for s in stmts[1:]]
46
+ ends = starts[1:] + [len(data)]
47
+
48
+ findings: list[Finding] = []
49
+
50
+ for raw, start, end in zip(stmts, starts, ends):
51
+ text = data[start:end].decode("utf-8", errors="replace")
52
+ offset, snippet = _first_code_line(text)
53
+ line = data[:start].count(b"\n") + 1 + offset
54
+ off = disabled | suppressed_ids(text)
55
+
56
+ if "ALL" in off:
57
+ continue
58
+
59
+ for rule in RULES:
60
+ if rule.id not in off and rule.check(raw.stmt):
61
+ findings.append(Finding(rule, filename, line, snippet))
62
+
63
+ has_lock_timeout = any(
64
+ isinstance(r.stmt, ast.VariableSetStmt) and r.stmt.name == "lock_timeout"
65
+ for r in stmts
66
+ )
67
+
68
+ if findings and not has_lock_timeout:
69
+ file_off = disabled | suppressed_ids(sql)
70
+
71
+ if "MIG010" not in file_off and "ALL" not in file_off:
72
+ first_line = min(f.line for f in findings)
73
+ findings.append(Finding(LOCK_TIMEOUT_RULE, filename, first_line, ""))
74
+
75
+ return findings
@@ -0,0 +1,22 @@
1
+ from collections.abc import Callable
2
+ from dataclasses import dataclass
3
+
4
+ from pglast import ast
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Rule:
9
+ id: str
10
+ title: str
11
+ why: str
12
+ fix: str
13
+ check: Callable[[ast.Node], bool]
14
+ severity: str = "error" # "error" | "warning"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Finding:
19
+ rule: Rule
20
+ file: str
21
+ line: int
22
+ snippet: str = ""
@@ -0,0 +1,113 @@
1
+ import json
2
+ from importlib.metadata import PackageNotFoundError, version
3
+ from pathlib import Path
4
+
5
+ from .models import Finding
6
+ from .rules import ALL_RULES
7
+
8
+ REPO_URL = "https://github.com/adsetsuko0/pg-migration-lint"
9
+
10
+
11
+ def _version() -> str:
12
+ try:
13
+ return version("pg-migration-lint")
14
+ except PackageNotFoundError:
15
+ return "0.0.0"
16
+
17
+
18
+ def _uri(file: str) -> str:
19
+ """Путь относительно текущей папки, со слэшами (так ждут GitHub и SARIF)."""
20
+ try:
21
+ return Path(file).resolve().relative_to(Path.cwd()).as_posix()
22
+ except ValueError:
23
+ return Path(file).as_posix()
24
+
25
+
26
+ def _message(f: Finding) -> str:
27
+ return f"{f.rule.title}. {f.rule.why} Fix: {f.rule.fix}"
28
+
29
+
30
+ def to_json(findings: list[Finding]) -> str:
31
+ data = {
32
+ "version": _version(),
33
+ "findings": [
34
+ {
35
+ "rule": f.rule.id,
36
+ "severity": f.rule.severity,
37
+ "title": f.rule.title,
38
+ "file": _uri(f.file),
39
+ "line": f.line,
40
+ "sql": f.snippet,
41
+ "why": f.rule.why,
42
+ "fix": f.rule.fix,
43
+ }
44
+ for f in findings
45
+ ],
46
+ }
47
+ return json.dumps(data, indent=2, ensure_ascii=False)
48
+
49
+
50
+ def to_sarif(findings: list[Finding]) -> str:
51
+ sarif = {
52
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
53
+ "version": "2.1.0",
54
+ "runs": [
55
+ {
56
+ "tool": {
57
+ "driver": {
58
+ "name": "pgmlint",
59
+ "version": _version(),
60
+ "informationUri": REPO_URL,
61
+ "rules": [
62
+ {
63
+ "id": r.id,
64
+ "helpUri": f"{REPO_URL}/blob/main/docs/rules/{r.id}.md",
65
+ "shortDescription": {"text": r.title},
66
+ "fullDescription": {"text": r.why},
67
+ "help": {"text": r.fix},
68
+ "defaultConfiguration": {"level": r.severity},
69
+ }
70
+ for r in ALL_RULES
71
+ ],
72
+ }
73
+ },
74
+ "results": [
75
+ {
76
+ "ruleId": f.rule.id,
77
+ "level": f.rule.severity,
78
+ "message": {"text": _message(f)},
79
+ "locations": [
80
+ {
81
+ "physicalLocation": {
82
+ "artifactLocation": {"uri": _uri(f.file)},
83
+ "region": {"startLine": max(f.line, 1)},
84
+ }
85
+ }
86
+ ],
87
+ }
88
+ for f in findings
89
+ ],
90
+ }
91
+ ],
92
+ }
93
+ return json.dumps(sarif, indent=2, ensure_ascii=False)
94
+
95
+
96
+ def _esc_data(s: str) -> str:
97
+ return s.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
98
+
99
+
100
+ def _esc_prop(s: str) -> str:
101
+ return _esc_data(s).replace(":", "%3A").replace(",", "%2C")
102
+
103
+
104
+ def to_github(findings: list[Finding]) -> str:
105
+ """Аннотации GitHub Actions: ::error file=...,line=...,title=...::message"""
106
+ lines = []
107
+ for f in findings:
108
+ title = _esc_prop(f"{f.rule.id} {f.rule.title}")
109
+ lines.append(
110
+ f"::{f.rule.severity} file={_esc_prop(_uri(f.file))},line={max(f.line, 1)},"
111
+ f"title={title}::{_esc_data(_message(f))}"
112
+ )
113
+ return "\n".join(lines)
@@ -0,0 +1,175 @@
1
+ from pglast import ast
2
+ from pglast.enums import AlterTableType as AT
3
+ from pglast.enums import ConstrType, ObjectType # было: только ConstrType
4
+
5
+ from .models import Rule
6
+
7
+ # Функции с VOLATILE-волатильностью: default вычисляется для каждой строки
8
+ # => на PG11+ это перезапись таблицы. now() сюда НЕ входит (STABLE, безопасно).
9
+ VOLATILE_FUNCS = {"random", "clock_timestamp", "timeofday", "gen_random_uuid", "uuid_generate_v4"}
10
+
11
+
12
+ def _cmds(stmt):
13
+ return (stmt.cmds or ()) if isinstance(stmt, ast.AlterTableStmt) else ()
14
+
15
+
16
+ def _is_volatile(expr) -> bool:
17
+ if isinstance(expr, ast.FuncCall):
18
+ return expr.funcname[-1].sval.lower() in VOLATILE_FUNCS
19
+ if isinstance(expr, ast.TypeCast):
20
+ return _is_volatile(expr.arg)
21
+ return False
22
+
23
+
24
+ def _index_not_concurrent(stmt) -> bool:
25
+ return isinstance(stmt, ast.IndexStmt) and not stmt.concurrent
26
+
27
+
28
+ def _add_column_volatile_default(stmt) -> bool:
29
+ for cmd in _cmds(stmt):
30
+ if cmd.subtype == AT.AT_AddColumn and isinstance(cmd.def_, ast.ColumnDef):
31
+ for c in cmd.def_.constraints or ():
32
+ if c.contype == ConstrType.CONSTR_DEFAULT and _is_volatile(c.raw_expr):
33
+ return True
34
+ return False
35
+
36
+
37
+ def _set_not_null(stmt) -> bool:
38
+ return any(cmd.subtype == AT.AT_SetNotNull for cmd in _cmds(stmt))
39
+
40
+
41
+
42
+ def _add_constraints(stmt):
43
+ for cmd in _cmds(stmt):
44
+ if cmd.subtype == AT.AT_AddConstraint and isinstance(cmd.def_, ast.Constraint):
45
+ yield cmd.def_
46
+
47
+
48
+ def _fk_not_valid_missing(stmt) -> bool:
49
+ return any(c.contype == ConstrType.CONSTR_FOREIGN and not c.skip_validation
50
+ for c in _add_constraints(stmt))
51
+
52
+
53
+ def _check_not_valid_missing(stmt) -> bool:
54
+ return any(c.contype == ConstrType.CONSTR_CHECK and not c.skip_validation
55
+ for c in _add_constraints(stmt))
56
+
57
+
58
+ def _alter_column_type(stmt) -> bool:
59
+ return any(cmd.subtype == AT.AT_AlterColumnType for cmd in _cmds(stmt))
60
+
61
+
62
+ def _add_unique_or_pk(stmt) -> bool:
63
+ # USING INDEX (c.indexname задан) безопасен: индекс уже построен
64
+ return any(c.contype in (ConstrType.CONSTR_UNIQUE, ConstrType.CONSTR_PRIMARY)
65
+ and not c.indexname
66
+ for c in _add_constraints(stmt))
67
+
68
+
69
+ def _drop_column(stmt) -> bool:
70
+ return any(cmd.subtype == AT.AT_DropColumn for cmd in _cmds(stmt))
71
+
72
+
73
+ def _rename(stmt) -> bool:
74
+ return isinstance(stmt, ast.RenameStmt) and stmt.renameType in (
75
+ ObjectType.OBJECT_COLUMN, ObjectType.OBJECT_TABLE)
76
+
77
+
78
+ RULES: list[Rule] = [
79
+ Rule(
80
+ "MIG001",
81
+ "CREATE INDEX without CONCURRENTLY",
82
+ "Takes a SHARE lock: all writes (INSERT/UPDATE/DELETE) to the table are blocked "
83
+ "for the whole index build. Duration grows with table size.",
84
+ "Use CREATE INDEX CONCURRENTLY. In Alembic run it inside "
85
+ "op.get_context().autocommit_block() since it cannot run in a transaction.",
86
+ _index_not_concurrent,
87
+ ),
88
+ Rule(
89
+ "MIG002",
90
+ "ADD COLUMN with volatile DEFAULT",
91
+ "A volatile default (e.g. random(), gen_random_uuid()) forces a full table rewrite "
92
+ "under ACCESS EXCLUSIVE lock: reads and writes are blocked.",
93
+ "Add the column as nullable without default, backfill in batches, "
94
+ "then SET DEFAULT for new rows.",
95
+ _add_column_volatile_default,
96
+ ),
97
+ Rule(
98
+ "MIG003",
99
+ "ALTER COLUMN SET NOT NULL",
100
+ "Scans the whole table to verify no NULLs while holding ACCESS EXCLUSIVE lock.",
101
+ "Add CHECK (col IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT, "
102
+ "then SET NOT NULL (on PG12+ the scan is skipped).",
103
+ _set_not_null,
104
+ ),
105
+
106
+
107
+ Rule(
108
+ "MIG004",
109
+ "ADD FOREIGN KEY without NOT VALID",
110
+ "Validates every existing row while holding SHARE ROW EXCLUSIVE lock on both "
111
+ "tables: writes are blocked for the duration of the scan.",
112
+ "ADD CONSTRAINT ... NOT VALID, then ALTER TABLE ... VALIDATE CONSTRAINT in a "
113
+ "separate step (it only takes a SHARE UPDATE EXCLUSIVE lock).",
114
+ _fk_not_valid_missing,
115
+ ),
116
+ Rule(
117
+ "MIG005",
118
+ "ADD CHECK constraint without NOT VALID",
119
+ "Scans the whole table to validate the constraint under ACCESS EXCLUSIVE lock.",
120
+ "ADD CONSTRAINT ... CHECK (...) NOT VALID, then VALIDATE CONSTRAINT separately.",
121
+ _check_not_valid_missing,
122
+ ),
123
+ Rule(
124
+ "MIG006",
125
+ "ALTER COLUMN TYPE",
126
+ "Most type changes rewrite the whole table and rebuild its indexes under "
127
+ "ACCESS EXCLUSIVE lock. Some changes are safe (e.g. increasing varchar length).",
128
+ "Add a new column, backfill in batches, switch the application over, drop the "
129
+ "old column. If the change is known to be binary-compatible, suppress this rule.",
130
+ _alter_column_type,
131
+ severity="warning",
132
+ ),
133
+ Rule(
134
+ "MIG007",
135
+ "ADD UNIQUE / PRIMARY KEY constraint",
136
+ "Builds a unique index while holding ACCESS EXCLUSIVE lock: reads and writes "
137
+ "are blocked until it finishes.",
138
+ "CREATE UNIQUE INDEX CONCURRENTLY first, then "
139
+ "ADD CONSTRAINT ... UNIQUE USING INDEX <index> (instant).",
140
+ _add_unique_or_pk,
141
+ ),
142
+ Rule(
143
+ "MIG008",
144
+ "DROP COLUMN",
145
+ "The lock itself is short, but application instances that still use the column "
146
+ "start failing as soon as the migration runs.",
147
+ "Expand/contract: stop using the column in code, deploy, and drop it in a "
148
+ "later release.",
149
+ _drop_column,
150
+ severity="warning",
151
+ ),
152
+ Rule(
153
+ "MIG009",
154
+ "RENAME COLUMN / TABLE",
155
+ "Instantly breaks every running application instance that uses the old name.",
156
+ "Expand/contract: add the new name, migrate code and data, drop the old one later.",
157
+ _rename,
158
+ severity="warning",
159
+ ),
160
+
161
+ ]
162
+
163
+ LOCK_TIMEOUT_RULE = Rule(
164
+ "MIG010",
165
+ "Missing lock_timeout",
166
+ "Without lock_timeout, a migration waiting for a lock queues behind a long-running "
167
+ "query, and every query arriving after it queues behind the migration: the table "
168
+ "appears frozen.",
169
+ "Run SET lock_timeout = '5s' (or SET LOCAL inside the transaction) at the start of "
170
+ "the migration and retry on failure.",
171
+ lambda stmt: False, # файловое правило: проверяется в engine.py
172
+ severity="warning",
173
+ )
174
+
175
+ ALL_RULES = [*RULES, LOCK_TIMEOUT_RULE]
@@ -0,0 +1,295 @@
1
+ Metadata-Version: 2.5
2
+ Name: pg-migration-lint
3
+ Version: 0.1.0
4
+ Summary: Static analyzer that detects unsafe PostgreSQL migrations in Alembic projects
5
+ Project-URL: Homepage, https://github.com/adsetsuko0/pg-migration-lint
6
+ Project-URL: Repository, https://github.com/adsetsuko0/pg-migration-lint
7
+ Project-URL: Issues, https://github.com/adsetsuko0/pg-migration-lint/issues
8
+ Project-URL: Changelog, https://github.com/adsetsuko0/pg-migration-lint/blob/main/CHANGELOG.md
9
+ Author: Anna Ermak
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: alembic,linter,migrations,postgresql,sarif,static-analysis
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Database
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: pglast>=7
21
+ Requires-Dist: rich>=13
22
+ Requires-Dist: typer>=0.12
23
+ Description-Content-Type: text/markdown
24
+
25
+ # MigrationLint
26
+ ![CI](https://github.com/adsetsuko0/pg-migration-lint/actions/workflows/ci.yml/badge.svg)
27
+
28
+
29
+ **A static linter for potentially unsafe PostgreSQL migrations.**
30
+
31
+ MigrationLint analyzes PostgreSQL SQL migrations and detects operations that may cause long locks, table rewrites, or application compatibility problems.
32
+
33
+ It supports plain SQL files and Alembic migrations through offline SQL generation.
34
+
35
+ MigrationLint does not connect to a database or execute migrations.
36
+
37
+ ## Features
38
+
39
+ - Detect potentially unsafe PostgreSQL schema changes.
40
+ - Analyze individual SQL files or entire directories.
41
+ - Analyze Alembic migrations in offline mode.
42
+ - Explain why an operation may be dangerous.
43
+ - Suggest safer migration alternatives.
44
+ - Suppress individual rules.
45
+ - Configure disabled rules in `pyproject.toml`.
46
+ - Export reports as text, JSON, SARIF, and GitHub Actions annotations.
47
+ - Integrate with pre-commit and GitHub Actions.
48
+
49
+ ## Usage
50
+
51
+ ### Lint SQL files
52
+
53
+ ```bash
54
+ pgmlint lint examples/bad.sql
55
+ ```
56
+
57
+ Analyze all SQL files in a directory:
58
+
59
+ ```bash
60
+ pgmlint lint examples
61
+ ```
62
+
63
+ ### Lint Alembic migrations
64
+
65
+ ```bash
66
+ pgmlint alembic
67
+ ```
68
+
69
+ Specify a revision range:
70
+
71
+ ```bash
72
+ pgmlint alembic --range base:head
73
+ ```
74
+
75
+ MigrationLint generates SQL using Alembic offline mode and analyzes it without connecting to a database or executing migrations.
76
+
77
+ ## Rules
78
+
79
+ MigrationLint currently provides 10 detection rules.
80
+
81
+ | ID | Severity | What it detects | Safer alternative |
82
+ |---|---|---|---|
83
+ | MIG001 | error | `CREATE INDEX` without `CONCURRENTLY` | Use `CREATE INDEX CONCURRENTLY` inside an Alembic `autocommit_block()`. |
84
+ | MIG002 | error | Adding a column with a volatile `DEFAULT` | Add the column without a default, backfill in batches, then set the default separately. |
85
+ | MIG003 | error | `ALTER COLUMN SET NOT NULL` | Add a `CHECK ... NOT VALID` constraint, validate it, then set `NOT NULL`. |
86
+ | MIG004 | error | Adding a foreign key without `NOT VALID` | Add the foreign key using `NOT VALID`, then run `VALIDATE CONSTRAINT`. |
87
+ | MIG005 | error | Adding a `CHECK` constraint without `NOT VALID` | Add it using `NOT VALID`, then validate it separately. |
88
+ | MIG006 | warning | Potentially expensive column type changes | Consider an expand-and-contract migration with a new column and batched data migration. |
89
+ | MIG007 | error | Adding a `UNIQUE` or `PRIMARY KEY` constraint directly | Build a unique index concurrently and attach it as a constraint where supported. |
90
+ | MIG008 | warning | Dropping a column | Stop using the column first, then drop it in a later migration. |
91
+ | MIG009 | warning | Renaming a table or column | Use an expand-and-contract migration to maintain application compatibility. |
92
+ | MIG010 | warning | Missing `lock_timeout` | Set a reasonable `lock_timeout` at the beginning of the migration. |
93
+
94
+ The severity indicates the default classification of a finding, not a guarantee that an operation will cause an outage. Review findings in the context of your PostgreSQL version, schema, workload, and deployment strategy.
95
+
96
+ ## Output formats
97
+
98
+ MigrationLint supports four output formats:
99
+
100
+ | Format | Description |
101
+ |---|---|
102
+ | `text` | Human-readable terminal output |
103
+ | `json` | Machine-readable JSON |
104
+ | `sarif` | SARIF 2.1.0 report for code scanning |
105
+ | `github` | GitHub Actions workflow annotations |
106
+
107
+ Examples:
108
+
109
+ ```bash
110
+ pgmlint lint examples/bad.sql --format text
111
+ pgmlint lint examples/bad.sql --format json
112
+ pgmlint lint examples/bad.sql --format sarif
113
+ pgmlint lint examples/bad.sql --format github
114
+ ```
115
+
116
+ Save a report to a file:
117
+
118
+ ```bash
119
+ pgmlint lint examples/bad.sql --format sarif --output results.sarif
120
+ ```
121
+
122
+ ### Exit codes and `--fail-on`
123
+
124
+ Control when MigrationLint exits with code `1`:
125
+
126
+ ```bash
127
+ pgmlint lint examples --fail-on error
128
+ pgmlint lint examples --fail-on warning
129
+ pgmlint lint examples --fail-on never
130
+ ```
131
+
132
+ | Value | Behavior |
133
+ |---|---|
134
+ | `error` | Exit with code 1 if at least one error is found. |
135
+ | `warning` | Exit with code 1 if any finding is found, including warnings. |
136
+ | `never` | Always exit with code 0, regardless of findings. |
137
+
138
+ The default is `--fail-on error`.
139
+
140
+ ## Configuration
141
+
142
+ Configure MigrationLint in `pyproject.toml`:
143
+
144
+ ```toml
145
+ [tool.pgmlint]
146
+ disable = ["MIG001", "MIG009"]
147
+ ```
148
+
149
+ Disabled rules are skipped during analysis.
150
+
151
+ ## Suppressing rules
152
+
153
+ You can suppress individual findings when an operation has been reviewed and is intentionally used.
154
+
155
+ ### SQL files
156
+
157
+ Add a comment immediately above the SQL statement:
158
+
159
+ ```sql
160
+ -- pgmlint: disable=MIG001
161
+ CREATE INDEX idx_users_email ON users (email);
162
+ ```
163
+
164
+ ### Alembic migrations
165
+
166
+ Add a Python comment immediately above the operation:
167
+
168
+ ```python
169
+ # pgmlint: disable=MIG001
170
+ op.create_index("idx_users_email", "users", ["email"])
171
+ ```
172
+
173
+ Suppressions should be used sparingly and only when the operation has been reviewed.
174
+
175
+ ## pre-commit
176
+
177
+ Add MigrationLint to your `.pre-commit-config.yaml`:
178
+
179
+ ```yaml
180
+ repos:
181
+ - repo: https://github.com/adsetsuko0/pg-migration-lint
182
+ rev: v0.1.0
183
+ hooks:
184
+ - id: pgmlint
185
+ ```
186
+
187
+ The SQL hook checks `.sql` files before each commit.
188
+
189
+ To test the hook locally:
190
+
191
+ ```bash
192
+ pre-commit try-repo . pgmlint --files examples/bad.sql
193
+ ```
194
+
195
+ ### Alembic pre-commit hook
196
+
197
+ The repository also provides `pgmlint-alembic` for checking Alembic migrations:
198
+
199
+ ```yaml
200
+ repos:
201
+ - repo: https://github.com/adsetsuko0/pg-migration-lint
202
+ rev: v0.1.0
203
+ hooks:
204
+ - id: pgmlint-alembic
205
+ ```
206
+
207
+ This hook uses the system environment. Make sure `pgmlint`, Alembic, and the project's migration dependencies are installed and available in that environment.
208
+
209
+ ## GitHub Actions
210
+
211
+ MigrationLint provides a composite GitHub Action.
212
+
213
+ Add the following step to your workflow:
214
+
215
+ ```yaml
216
+ - uses: actions/checkout@v4
217
+
218
+ - name: Lint PostgreSQL migrations
219
+ uses: adsetsuko0/pg-migration-lint@main
220
+ with:
221
+ paths: "migrations/"
222
+ format: "github"
223
+ fail-on: "error"
224
+ ```
225
+
226
+ The `paths` input accepts space-separated SQL files or directories.
227
+
228
+ ### SARIF and GitHub Code Scanning
229
+
230
+ Generate a SARIF report and upload it to GitHub Code Scanning:
231
+
232
+ ```yaml
233
+ name: Migration lint
234
+
235
+ on:
236
+ pull_request:
237
+
238
+ permissions:
239
+ contents: read
240
+ security-events: write
241
+
242
+ jobs:
243
+ lint:
244
+ runs-on: ubuntu-latest
245
+
246
+ steps:
247
+ - uses: actions/checkout@v4
248
+
249
+ - name: Generate SARIF report
250
+ uses: adsetsuko0/pg-migration-lint@main
251
+ with:
252
+ paths: "migrations/"
253
+ format: "sarif"
254
+ output: "results.sarif"
255
+ fail-on: "never"
256
+
257
+ - name: Upload SARIF
258
+ uses: github/codeql-action/upload-sarif@v3
259
+ with:
260
+ sarif_file: results.sarif
261
+ ```
262
+
263
+ Using `fail-on: never` allows the SARIF upload step to run even when findings are present. The report still contains the detected issues.
264
+
265
+ ## Known limitations
266
+
267
+ - **Static analysis only.** MigrationLint does not connect to PostgreSQL, execute migrations, measure actual lock duration, or inspect table sizes.
268
+ - **MIG006 may produce false positives.** Some column type changes are safe or inexpensive, but the static analyzer cannot determine every case from SQL alone.
269
+ - **Alembic source line numbers are unavailable.** Findings identify the migration file, but generated SQL is not currently mapped back to exact Python source lines.
270
+ - **Full Alembic history analysis.** The default `base:head` range analyzes the complete migration history, which may take longer in projects with many revisions.
271
+ - **Context matters.** The safety of an operation depends on PostgreSQL version, table structure, data, workload, and deployment strategy.
272
+
273
+ ## Development
274
+
275
+ Set up the project:
276
+
277
+ ```bash
278
+ uv sync
279
+ ```
280
+
281
+ Run tests:
282
+
283
+ ```bash
284
+ uv run pytest -v
285
+ ```
286
+
287
+ Run Ruff:
288
+
289
+ ```bash
290
+ uv run ruff check .
291
+ ```
292
+
293
+ ## License
294
+
295
+ See the repository for license information.
@@ -0,0 +1,13 @@
1
+ pg_migration_lint/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ pg_migration_lint/alembic_support.py,sha256=3Rz8eK0LNu8jiFxxUYY6cWtKhQ9MxvoUOfruoztfcZo,1707
3
+ pg_migration_lint/cli.py,sha256=ZVvmFIf4HTpjUFqElUKWsjU7L8YcgowTR48oKUzkva4,5467
4
+ pg_migration_lint/config.py,sha256=K7FBy2ODicyHHbBCvEcCanieGZjIx5Rjx1MJDueAaw4,712
5
+ pg_migration_lint/engine.py,sha256=50b4GBzHc9ysppqJN1QDZM3w5Ksv9mWnDckDgjwiDsE,2802
6
+ pg_migration_lint/models.py,sha256=BS9zWkQ7UlxFFOTgxn7aS77H5QZ_OCWff9-O_Zwz-jw,380
7
+ pg_migration_lint/reporters.py,sha256=8ENA1VWkUb9Zs0rGZ_8Fn6aoR2vkIV8SfigCZPmjW5E,3674
8
+ pg_migration_lint/rules.py,sha256=XJ5K7MgNwaYOGnJKAotHeDRp-B2gsJloCfA9D1RTjfo,6569
9
+ pg_migration_lint-0.1.0.dist-info/METADATA,sha256=Y3zjksdDcqJKZx-2zHREW2vkUvTV7Z2o5FHX0S483tI,8722
10
+ pg_migration_lint-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ pg_migration_lint-0.1.0.dist-info/entry_points.txt,sha256=zz976MKqol3gLbJGl_2rpl2WqEg4tALqw3xbVXfO8pQ,54
12
+ pg_migration_lint-0.1.0.dist-info/licenses/LICENSE,sha256=0SJU1dVe5uk0rKC9g3BKPevyAWTYQxcqVtDVW9ORk5Y,1065
13
+ pg_migration_lint-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pgmlint = pg_migration_lint.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Your Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.