pg-migration-lint 0.1.0__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ .mypy_cache/
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Initial release.
6
+ - 10 rules (MIG001–MIG010) for unsafe PostgreSQL operations.
7
+ - Alembic offline-mode integration (`pgmlint alembic`).
8
+ - Output formats: text, JSON, SARIF, GitHub annotations.
9
+ - Inline suppression, `[tool.pgmlint]` config, `--fail-on`.
10
+ - pre-commit hook and GitHub Action.
@@ -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.
@@ -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,271 @@
1
+ # MigrationLint
2
+ ![CI](https://github.com/adsetsuko0/pg-migration-lint/actions/workflows/ci.yml/badge.svg)
3
+
4
+
5
+ **A static linter for potentially unsafe PostgreSQL migrations.**
6
+
7
+ MigrationLint analyzes PostgreSQL SQL migrations and detects operations that may cause long locks, table rewrites, or application compatibility problems.
8
+
9
+ It supports plain SQL files and Alembic migrations through offline SQL generation.
10
+
11
+ MigrationLint does not connect to a database or execute migrations.
12
+
13
+ ## Features
14
+
15
+ - Detect potentially unsafe PostgreSQL schema changes.
16
+ - Analyze individual SQL files or entire directories.
17
+ - Analyze Alembic migrations in offline mode.
18
+ - Explain why an operation may be dangerous.
19
+ - Suggest safer migration alternatives.
20
+ - Suppress individual rules.
21
+ - Configure disabled rules in `pyproject.toml`.
22
+ - Export reports as text, JSON, SARIF, and GitHub Actions annotations.
23
+ - Integrate with pre-commit and GitHub Actions.
24
+
25
+ ## Usage
26
+
27
+ ### Lint SQL files
28
+
29
+ ```bash
30
+ pgmlint lint examples/bad.sql
31
+ ```
32
+
33
+ Analyze all SQL files in a directory:
34
+
35
+ ```bash
36
+ pgmlint lint examples
37
+ ```
38
+
39
+ ### Lint Alembic migrations
40
+
41
+ ```bash
42
+ pgmlint alembic
43
+ ```
44
+
45
+ Specify a revision range:
46
+
47
+ ```bash
48
+ pgmlint alembic --range base:head
49
+ ```
50
+
51
+ MigrationLint generates SQL using Alembic offline mode and analyzes it without connecting to a database or executing migrations.
52
+
53
+ ## Rules
54
+
55
+ MigrationLint currently provides 10 detection rules.
56
+
57
+ | ID | Severity | What it detects | Safer alternative |
58
+ |---|---|---|---|
59
+ | MIG001 | error | `CREATE INDEX` without `CONCURRENTLY` | Use `CREATE INDEX CONCURRENTLY` inside an Alembic `autocommit_block()`. |
60
+ | MIG002 | error | Adding a column with a volatile `DEFAULT` | Add the column without a default, backfill in batches, then set the default separately. |
61
+ | MIG003 | error | `ALTER COLUMN SET NOT NULL` | Add a `CHECK ... NOT VALID` constraint, validate it, then set `NOT NULL`. |
62
+ | MIG004 | error | Adding a foreign key without `NOT VALID` | Add the foreign key using `NOT VALID`, then run `VALIDATE CONSTRAINT`. |
63
+ | MIG005 | error | Adding a `CHECK` constraint without `NOT VALID` | Add it using `NOT VALID`, then validate it separately. |
64
+ | MIG006 | warning | Potentially expensive column type changes | Consider an expand-and-contract migration with a new column and batched data migration. |
65
+ | MIG007 | error | Adding a `UNIQUE` or `PRIMARY KEY` constraint directly | Build a unique index concurrently and attach it as a constraint where supported. |
66
+ | MIG008 | warning | Dropping a column | Stop using the column first, then drop it in a later migration. |
67
+ | MIG009 | warning | Renaming a table or column | Use an expand-and-contract migration to maintain application compatibility. |
68
+ | MIG010 | warning | Missing `lock_timeout` | Set a reasonable `lock_timeout` at the beginning of the migration. |
69
+
70
+ 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.
71
+
72
+ ## Output formats
73
+
74
+ MigrationLint supports four output formats:
75
+
76
+ | Format | Description |
77
+ |---|---|
78
+ | `text` | Human-readable terminal output |
79
+ | `json` | Machine-readable JSON |
80
+ | `sarif` | SARIF 2.1.0 report for code scanning |
81
+ | `github` | GitHub Actions workflow annotations |
82
+
83
+ Examples:
84
+
85
+ ```bash
86
+ pgmlint lint examples/bad.sql --format text
87
+ pgmlint lint examples/bad.sql --format json
88
+ pgmlint lint examples/bad.sql --format sarif
89
+ pgmlint lint examples/bad.sql --format github
90
+ ```
91
+
92
+ Save a report to a file:
93
+
94
+ ```bash
95
+ pgmlint lint examples/bad.sql --format sarif --output results.sarif
96
+ ```
97
+
98
+ ### Exit codes and `--fail-on`
99
+
100
+ Control when MigrationLint exits with code `1`:
101
+
102
+ ```bash
103
+ pgmlint lint examples --fail-on error
104
+ pgmlint lint examples --fail-on warning
105
+ pgmlint lint examples --fail-on never
106
+ ```
107
+
108
+ | Value | Behavior |
109
+ |---|---|
110
+ | `error` | Exit with code 1 if at least one error is found. |
111
+ | `warning` | Exit with code 1 if any finding is found, including warnings. |
112
+ | `never` | Always exit with code 0, regardless of findings. |
113
+
114
+ The default is `--fail-on error`.
115
+
116
+ ## Configuration
117
+
118
+ Configure MigrationLint in `pyproject.toml`:
119
+
120
+ ```toml
121
+ [tool.pgmlint]
122
+ disable = ["MIG001", "MIG009"]
123
+ ```
124
+
125
+ Disabled rules are skipped during analysis.
126
+
127
+ ## Suppressing rules
128
+
129
+ You can suppress individual findings when an operation has been reviewed and is intentionally used.
130
+
131
+ ### SQL files
132
+
133
+ Add a comment immediately above the SQL statement:
134
+
135
+ ```sql
136
+ -- pgmlint: disable=MIG001
137
+ CREATE INDEX idx_users_email ON users (email);
138
+ ```
139
+
140
+ ### Alembic migrations
141
+
142
+ Add a Python comment immediately above the operation:
143
+
144
+ ```python
145
+ # pgmlint: disable=MIG001
146
+ op.create_index("idx_users_email", "users", ["email"])
147
+ ```
148
+
149
+ Suppressions should be used sparingly and only when the operation has been reviewed.
150
+
151
+ ## pre-commit
152
+
153
+ Add MigrationLint to your `.pre-commit-config.yaml`:
154
+
155
+ ```yaml
156
+ repos:
157
+ - repo: https://github.com/adsetsuko0/pg-migration-lint
158
+ rev: v0.1.0
159
+ hooks:
160
+ - id: pgmlint
161
+ ```
162
+
163
+ The SQL hook checks `.sql` files before each commit.
164
+
165
+ To test the hook locally:
166
+
167
+ ```bash
168
+ pre-commit try-repo . pgmlint --files examples/bad.sql
169
+ ```
170
+
171
+ ### Alembic pre-commit hook
172
+
173
+ The repository also provides `pgmlint-alembic` for checking Alembic migrations:
174
+
175
+ ```yaml
176
+ repos:
177
+ - repo: https://github.com/adsetsuko0/pg-migration-lint
178
+ rev: v0.1.0
179
+ hooks:
180
+ - id: pgmlint-alembic
181
+ ```
182
+
183
+ This hook uses the system environment. Make sure `pgmlint`, Alembic, and the project's migration dependencies are installed and available in that environment.
184
+
185
+ ## GitHub Actions
186
+
187
+ MigrationLint provides a composite GitHub Action.
188
+
189
+ Add the following step to your workflow:
190
+
191
+ ```yaml
192
+ - uses: actions/checkout@v4
193
+
194
+ - name: Lint PostgreSQL migrations
195
+ uses: adsetsuko0/pg-migration-lint@main
196
+ with:
197
+ paths: "migrations/"
198
+ format: "github"
199
+ fail-on: "error"
200
+ ```
201
+
202
+ The `paths` input accepts space-separated SQL files or directories.
203
+
204
+ ### SARIF and GitHub Code Scanning
205
+
206
+ Generate a SARIF report and upload it to GitHub Code Scanning:
207
+
208
+ ```yaml
209
+ name: Migration lint
210
+
211
+ on:
212
+ pull_request:
213
+
214
+ permissions:
215
+ contents: read
216
+ security-events: write
217
+
218
+ jobs:
219
+ lint:
220
+ runs-on: ubuntu-latest
221
+
222
+ steps:
223
+ - uses: actions/checkout@v4
224
+
225
+ - name: Generate SARIF report
226
+ uses: adsetsuko0/pg-migration-lint@main
227
+ with:
228
+ paths: "migrations/"
229
+ format: "sarif"
230
+ output: "results.sarif"
231
+ fail-on: "never"
232
+
233
+ - name: Upload SARIF
234
+ uses: github/codeql-action/upload-sarif@v3
235
+ with:
236
+ sarif_file: results.sarif
237
+ ```
238
+
239
+ Using `fail-on: never` allows the SARIF upload step to run even when findings are present. The report still contains the detected issues.
240
+
241
+ ## Known limitations
242
+
243
+ - **Static analysis only.** MigrationLint does not connect to PostgreSQL, execute migrations, measure actual lock duration, or inspect table sizes.
244
+ - **MIG006 may produce false positives.** Some column type changes are safe or inexpensive, but the static analyzer cannot determine every case from SQL alone.
245
+ - **Alembic source line numbers are unavailable.** Findings identify the migration file, but generated SQL is not currently mapped back to exact Python source lines.
246
+ - **Full Alembic history analysis.** The default `base:head` range analyzes the complete migration history, which may take longer in projects with many revisions.
247
+ - **Context matters.** The safety of an operation depends on PostgreSQL version, table structure, data, workload, and deployment strategy.
248
+
249
+ ## Development
250
+
251
+ Set up the project:
252
+
253
+ ```bash
254
+ uv sync
255
+ ```
256
+
257
+ Run tests:
258
+
259
+ ```bash
260
+ uv run pytest -v
261
+ ```
262
+
263
+ Run Ruff:
264
+
265
+ ```bash
266
+ uv run ruff check .
267
+ ```
268
+
269
+ ## License
270
+
271
+ See the repository for license information.
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "pg-migration-lint"
3
+ version = "0.1.0"
4
+ description = "Static analyzer that detects unsafe PostgreSQL migrations in Alembic projects"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Anna Ermak" }]
10
+ keywords = ["postgresql", "alembic", "migrations", "linter", "sarif", "static-analysis"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Environment :: Console",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Database",
17
+ "Topic :: Software Development :: Quality Assurance",
18
+ ]
19
+ dependencies = ["pglast>=7", "typer>=0.12", "rich>=13"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/adsetsuko0/pg-migration-lint"
23
+ Repository = "https://github.com/adsetsuko0/pg-migration-lint"
24
+ Issues = "https://github.com/adsetsuko0/pg-migration-lint/issues"
25
+ Changelog = "https://github.com/adsetsuko0/pg-migration-lint/blob/main/CHANGELOG.md"
26
+
27
+ [project.scripts]
28
+ pgmlint = "pg_migration_lint.cli:app"
29
+
30
+ [build-system]
31
+ requires = ["hatchling>=1.27"]
32
+ build-backend = "hatchling.build"
33
+
34
+ [tool.hatch.build.targets.sdist]
35
+ include = ["src", "tests", "README.md", "LICENSE", "CHANGELOG.md", "pyproject.toml"]
36
+
37
+ [dependency-groups]
38
+ dev = [
39
+ "pytest>=8",
40
+ "ruff>=0.6",
41
+ "mypy>=1.10",
42
+ "alembic>=1.20.1",
43
+ ]
44
+
45
+ [tool.ruff]
46
+ line-length = 100
47
+
48
+ [tool.pytest.ini_options]
49
+ testpaths = ["tests"]
@@ -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 ревизии