@subodh001/pg-safe-migrate 2.6.0 → 2.7.0

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.
package/CHANGELOG.md CHANGED
@@ -1,43 +1,81 @@
1
1
  # Changelog
2
2
 
3
- ## [2.6.0]
3
+ ## [2.7.0]
4
+
5
+ ### Added
6
+
7
+ - SQL-aware inline rule suppression.
4
8
 
5
- - Unicode-aware SQL positions, leading comment handling and transaction tracking for savepoints and chained transactions.
6
- - Optimized statement position tracking.
7
- - Corrected rule catalog coverage and default severity metadata (no enforcement changes).
9
+ - AST-based suppression targeting for individual SQL statements.
8
10
 
9
- ## [2.5.0] - 2026-11-20
11
+ - Mandatory suppression reasons for auditability.
10
12
 
13
+ - Configurable protected migration safety rules.
11
14
 
15
+ - Suppression audit reporting in terminal, JSON, SARIF and Markdown formats.
12
16
 
13
- ### Added
17
+ - Enterprise suppression policies with configurable limits.
14
18
 
15
- - Configurable CI migration safety gates.
19
+ - Detection of rejected, unused and invalid suppression directives.
16
20
 
17
- - Reviewed migration risk baselines to distinguish new, existing, and resolved findings.
21
+ - Suppression-aware VS Code diagnostics and audit reporting.
22
+
23
+ ### Security
24
+
25
+ - Protected rules cannot be suppressed through ordinary inline directives.
18
26
 
19
- - Production-aware migration recommendations using optional workload and table-size estimates.
27
+ - Enterprise gates reject project exclusions and severity-weakening overrides.
20
28
 
21
- - GitHub Actions pull-request safety reporting.
29
+ - Suppressed findings remain included in enterprise risk calculations.
22
30
 
23
- - Improved onboarding, examples, and adoption documentation.
31
+ - Ambiguous SQL scanning fails closed.
32
+
33
+ ### Verification
34
+
35
+ - 363 automated regression tests passed.
24
36
 
37
+ - Compatibility verified on Node.js 18, 20, 22 and 24.
25
38
 
39
+ - Repeated memory retention testing across 200,000 measured SQL statements.
26
40
 
27
- ### Improved
41
+ - Performance benchmarks covering up to 10,000 SQL statements per workload.
42
+
43
+ ### Compatibility and limitations
44
+
45
+ - Inline suppression is disabled by default.
28
46
 
29
- - JSON reporting for risk baselines, production context, and policy decisions.
47
+ - Enterprise gates now reject configurations that weaken rule severity or exclude files.
30
48
 
31
- - Migration safety guidance for deployment planning.
49
+ - Some combinations of suppression, risk baselines and combined simulation are not supported.
32
50
 
33
- - Release-readiness verification and regression coverage.
51
+ - Enterprise enforcement requires trusted CLI code, configuration, policies and CI workflows.
34
52
 
53
+ - Static migration analysis does not guarantee zero downtime.
54
+
55
+ ## [2.6.0]
35
56
 
57
+ * Unicode-aware SQL positions, leading comment handling and transaction tracking for savepoints and chained transactions.
58
+ * Optimized statement position tracking.
59
+ * Corrected rule catalog coverage and default severity metadata (no enforcement changes).
36
60
 
37
- ### Notes
61
+ ## [2.5.0] - 2026-11-20
62
+
63
+ ### Added
38
64
 
39
- - Production context uses supplied estimates, not live database measurements.
65
+ * Configurable CI migration safety gates.
66
+ * Reviewed migration risk baselines to distinguish new, existing, and resolved findings.
67
+ * Production-aware migration recommendations using optional workload and table-size estimates.
68
+ * GitHub Actions pull-request safety reporting.
69
+ * Improved onboarding, examples, and adoption documentation.
70
+
71
+ ### Improved
40
72
 
41
- - Static analysis does not guarantee zero downtime.
73
+ * JSON reporting for risk baselines, production context, and policy decisions.
74
+ * Migration safety guidance for deployment planning.
75
+ * Release-readiness verification and regression coverage.
76
+
77
+ ### Notes
42
78
 
43
- - Existing migration safety rules remain available.
79
+ * Production context uses supplied estimates, not live database measurements.
80
+ * Static analysis does not guarantee zero downtime.
81
+ * Existing migration safety rules remain available.
package/README.md CHANGED
@@ -1,141 +1,76 @@
1
- > **CLI documentation: v2.6.0.** **VS Code extension documentation: v0.7.0.** Check npm and the Marketplace for available versions. Migration analysis does not guarantee zero downtime.
2
-
3
- # pg-safe-migrate
1
+ # PG Safe Migrate
4
2
 
5
3
  **Catch risky PostgreSQL migrations before they reach production.**
6
4
 
7
- An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, Flyway, and raw SQL**.
8
-
9
- Detect risky PostgreSQL DDL patterns and provide additional framework-specific migration advisories.
10
-
11
- **Features:** PostgreSQL AST parsing · migration risk diagnostics (see rule coverage below) · Git-diff mode · JSON/SARIF · configurable severity · optional advisor · GitHub Actions
12
-
13
- > **Important:** This tool identifies configured migration risks. It does not guarantee zero downtime.
14
-
15
- ## Demo
16
-
17
- See how `pg-safe-migrate` catches an unsafe PostgreSQL migration and suggests a safer alternative.
18
-
19
- ![pg-safe-migrate CLI demonstration](https://raw.githubusercontent.com/subodhsingh001/pg-safe-migrate/main/assets/pg-safe-migrate-demo.gif)
20
-
21
- ### Example
22
-
23
- Unsafe migration:
5
+ Open-source, AST-based migration linting for Prisma, Drizzle, Flyway and raw SQL. Detect destructive changes, locking risks and transaction hazards before deployment.
24
6
 
25
- ```sql
26
- CREATE INDEX idx_users_email ON users(email);
27
- ```
7
+ [![npm version](https://img.shields.io/npm/v/@subodh001/pg-safe-migrate)](https://www.npmjs.com/package/@subodh001/pg-safe-migrate) [![VS Code](https://img.shields.io/visual-studio-marketplace/v/sukoaa.pg-safe-migrate-vscode)](https://marketplace.visualstudio.com/items?itemName=sukoaa.pg-safe-migrate-vscode) [![MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
28
8
 
29
- Detected issue:
30
-
31
- ```text
32
- [PG001] CREATE INDEX on "users" acquires a SHARE lock and blocks writes.
9
+ [Product website](https://www.sukoaa.com/pg-safe-migrate) · [Rule reference](docs/RULES.md) · [VS Code](https://marketplace.visualstudio.com/items?itemName=sukoaa.pg-safe-migrate-vscode) · [Report an issue](https://github.com/subodhsingh001/pg-safe-migrate/issues)
33
10
 
34
- Fix: Use CREATE INDEX CONCURRENTLY and execute outside a transaction block.
11
+ ![CLI demonstration](https://raw.githubusercontent.com/subodhsingh001/pg-safe-migrate/main/assets/pg-safe-migrate-demo.gif)
35
12
 
36
- Found 1 blocking migration issue(s).
37
- ```
38
-
39
- Safer alternative:
40
-
41
- ```sql
42
- CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
43
- ```
44
-
45
- `CREATE INDEX CONCURRENTLY` must run outside a transaction block.
46
-
47
-
48
- ## Week 3: opt-in CI policy gate
13
+ ## Quick start
49
14
 
50
- Run a deterministic, policy-driven static lint check in CI:
15
+ Requires Node.js 18 or later; use a maintained Node.js release for new installations.
51
16
 
52
- ```bash
53
- node bin/cli.js db/migrations --gate-policy examples/week3-gate-policy.json --fail-on none
17
+ ```sh
18
+ npx --yes --package=@subodh001/pg-safe-migrate@2.7.0 pg-safe-migrate
54
19
  ```
55
20
 
56
- The gate can block selected `PGxxx` rules, excessive warnings, and heuristic risk scores. It reports a block to stderr and exits with code `1`; malformed configuration exits `2`. This feature was introduced in CLI v2.5.0. See [Week 3 implementation notes](WEEK3-DAY1-IMPLEMENTED.md).
57
-
58
- [Install from npm](https://www.npmjs.com/package/@subodh001/pg-safe-migrate) · [Install the VS Code extension](https://marketplace.visualstudio.com/items?itemName=sukoaa.pg-safe-migrate-vscode) · [Report an issue](https://github.com/subodhsingh001/pg-safe-migrate/issues)
59
-
60
- ## Adoption and developer resources
61
-
62
- - [Safe onboarding and CI troubleshooting](docs/ADOPTION-GUIDE.md)
63
- - [Short demonstration recording script](docs/DEMO-SCRIPT.md)
64
- - [Proposed npm and VS Code Marketplace copy](docs/MARKETPLACE-COPY.md)
21
+ Or install in your project:
65
22
 
66
- **Release note:** The Week 3 policy, baseline, production-context, and PR reporting features were introduced in npm v2.5.0. Review the policy and baseline before enabling blocking checks; passing a static gate is not a downtime guarantee.
67
-
68
- ## Installation
69
-
70
- Install as a development dependency:
71
-
72
- ```bash
23
+ ```sh
73
24
  npm install --save-dev @subodh001/pg-safe-migrate
25
+ npx --no-install pg-safe-migrate prisma/migrations --advisor
74
26
  ```
75
27
 
76
- Or execute the published package without installing it in your project:
77
-
78
- ```bash
79
- npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --help
80
- ```
81
-
82
- ## Quick start
83
-
84
- ### Automatically detect migrations
85
-
86
- ```bash
87
- npx pg-safe-migrate
88
- ```
89
-
90
- The CLI searches these directories:
91
-
92
- - `prisma/migrations`
93
- - `drizzle`
94
- - `migrations`
95
- - `db/migrations`
96
- - `db/migration`
97
- - `sql/migrations`
98
- - `sql`
28
+ Use `drizzle`, `db/migrations` or a specific SQL file instead of `prisma/migrations`. With no path, the CLI detects common migration directories.
99
29
 
100
- ### Prisma
101
-
102
- ```bash
103
- npx pg-safe-migrate prisma/migrations
104
- ```
105
-
106
- ### Drizzle
30
+ ### Example
107
31
 
108
- ```bash
109
- npx pg-safe-migrate drizzle
32
+ ```sql
33
+ ALTER TABLE users DROP COLUMN email;
110
34
  ```
111
35
 
112
- ### Raw SQL
113
-
114
- ```bash
115
- npx pg-safe-migrate db/migrations
36
+ ```text
37
+ unsafe.sql:1:1 [PG002] error: Dropping column "users.email" can break older application instances.
116
38
  ```
117
39
 
118
- ### Check a specific migration
40
+ Remove application references before dropping the column in a later deployment. A passing lint check is not a guarantee of zero downtime.
119
41
 
120
- ```bash
121
- npx pg-safe-migrate path/to/migration.sql
122
- ```
42
+ ## GitHub Actions
123
43
 
124
- ### Check changed migrations only
44
+ Save as `.github/workflows/migration-lint.yml`:
125
45
 
126
- ```bash
127
- npx pg-safe-migrate --changed origin/main
46
+ ```yaml
47
+ name: PostgreSQL migration safety
48
+ on:
49
+ pull_request:
50
+ paths:
51
+ - '**/*.sql'
52
+ permissions:
53
+ contents: read
54
+ jobs:
55
+ migrations:
56
+ runs-on: ubuntu-latest
57
+ steps:
58
+ - uses: actions/checkout@v4
59
+ with:
60
+ fetch-depth: 0
61
+ persist-credentials: false
62
+ - uses: actions/setup-node@v4
63
+ with:
64
+ node-version: '22'
65
+ - name: Check changed SQL
66
+ env:
67
+ BASE_REF: ${{ github.base_ref }}
68
+ run: npx --yes --package=@subodh001/pg-safe-migrate@2.7.0 pg-safe-migrate --changed "origin/$BASE_REF" --fail-on error
128
69
  ```
129
70
 
130
- Without a base reference, `--changed` checks staged, unstaged, and untracked SQL files. With a base reference, it additionally checks branch changes.
131
-
132
- For pull requests, fetch the base branch first. Use `fetch-depth: 0` in GitHub Actions.
71
+ Start with reporting-only mode (`--fail-on none`) if introducing linting into an existing project. Review findings before enforcing a gate. See the [adoption guide](docs/ADOPTION-GUIDE.md).
133
72
 
134
- ## PostgreSQL migration rules
135
-
136
- The following rule identifiers are documented for CLI v2.6.0.
137
-
138
- 23 catalog identifiers, including legacy PG013; PG009 and PG018 are unused. PG013 is suppressed when PG025 is emitted. PG019 and PG020 are triggered for a configured target version below 15; PG014 targets PostgreSQL 10. Defaults below describe CLI reporting, not raw engine metadata.
73
+ ## What it detects
139
74
 
140
75
  | ID | Diagnostic | Default | Guidance |
141
76
  |---|---|---|---|
@@ -163,7 +98,9 @@ The following rule identifiers are documented for CLI v2.6.0.
163
98
  | PG024 | Dropping a constraint | error | Review dependent queries and data-integrity requirements. |
164
99
  | PG025 | SET NOT NULL may scan table | error | Backfill and validate a CHECK constraint first where appropriate. |
165
100
 
166
- PG017 also covers Flyway nontransactional execution advice. Rules are configurable using `rules` with `off`, `warning`, or `error`. Static findings are not a downtime guarantee.
101
+ See the [full rule reference](docs/RULES.md) for defaults, version constraints and legacy identifiers. PG013 is superseded by PG025; PG009 and PG018 are unused.
102
+
103
+ ## Reporting and configuration
167
104
 
168
105
  Example configuration (`pg-safe-migrate.config.json`):
169
106
 
@@ -182,213 +119,133 @@ Each finding includes a description of the risk and a suggested safer migration
182
119
 
183
120
  A passing result means no configured patterns were detected, not that a migration is guaranteed to be safe.
184
121
 
185
- ## GitHub Actions integration
186
-
187
- Automatically check migration files during pull requests.
188
-
189
- Copy the [example consumer workflow](https://github.com/subodhsingh001/pg-safe-migrate/blob/main/examples/consumer-workflow.yml) into your application's repository:
190
-
191
- ```text
192
- .github/workflows/pg-safe-migrate.yml
193
- ```
194
-
195
- The workflow checks changed SQL migrations so teams can adopt the linter without immediately rewriting historical migrations.
196
-
197
- For reproducible builds, pin the package to a reviewed version and upgrade deliberately.
198
-
199
- ## Verify CLI v2.6.0 after publication
200
-
201
- From a clean directory, run:
202
-
203
- ```bash
204
- npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --help
205
- ```
206
-
207
- Create a file named `unsafe.sql`:
208
-
209
- ```sql
210
- CREATE INDEX idx_users_email ON users(email);
211
- ```
212
-
213
- Then execute:
214
-
215
- ```bash
216
- npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate unsafe.sql
217
- ```
218
-
219
- Expected behavior: PG001 is reported and the CLI exits with code `1`.
220
-
221
- The included `examples/safe.sql` demonstrates concurrent index creation and should pass PG001.
122
+
123
+ ## Inline Rule Suppression
124
+
125
+ Introduced in v2.7.0, inline suppression allows teams to acknowledge reviewed migration risks without disabling an entire safety rule.
126
+
127
+ Suppression is disabled by default.
128
+
129
+ ### Enable suppression
130
+
131
+ Create or update `pg-safe-migrate.config.json`:
132
+
133
+ ```json
134
+ {
135
+ "suppression": {
136
+ "enabled": true,
137
+ "requireReason": true,
138
+ "reportSuppressed": true,
139
+ "protectedRules": ["PG011", "PG023"]
140
+ }
141
+ }
142
+ ```
143
+
144
+ ### Suppress a reviewed finding
145
+
146
+ ```sql
147
+ -- pg-safe-migrate-disable-next-line PG002 -- reason: DBA approved after application compatibility review
148
+ ALTER TABLE users DROP COLUMN legacy_email;
149
+ ```
150
+
151
+ The directive applies only to the immediately following SQL statement.
152
+
153
+ Multiple rule IDs can be specified using commas.
154
+
155
+ ### Built-in safeguards
156
+
157
+ - Mandatory suppression reasons.
158
+ - PostgreSQL AST-based statement targeting.
159
+ - SQL-aware comment scanning.
160
+ - Protected rule enforcement.
161
+ - Unknown rule detection.
162
+ - Rejected and unused directive reporting.
163
+ - Fail-closed handling of ambiguous SQL scanning.
164
+ - Audit reporting in terminal, JSON, SARIF and Markdown.
165
+ - Suppression-aware VS Code diagnostics.
166
+
167
+ ### Generate an audit report
168
+
169
+ ```sh
170
+ npx --no-install pg-safe-migrate migrations \
171
+ --config pg-safe-migrate.config.json \
172
+ --format json \
173
+ --output migration-report.json
174
+ ```
175
+
176
+ Suppressed findings remain available in the audit report.
177
+
178
+ ### Enterprise Migration Governance
179
+
180
+ Teams can enforce additional suppression restrictions using a trusted gate policy.
181
+
182
+ Example `enterprise-policy.json`:
183
+
184
+ ```json
185
+ {
186
+ "name": "Production Migration Safety",
187
+ "maxRiskScore": 60,
188
+ "maxWarnings": 5,
189
+ "blockedRules": ["PG002", "PG011", "PG023"],
190
+ "suppression": {
191
+ "protectedRules": ["PG008", "PG011", "PG023"],
192
+ "maxSuppressedFindings": 2,
193
+ "failOnRejected": true,
194
+ "failOnUnused": true
195
+ }
196
+ }
197
+ ```
198
+
199
+ Run the enterprise gate:
200
+
201
+ ```sh
202
+ npx --no-install pg-safe-migrate migrations \
203
+ --config pg-safe-migrate.config.json \
204
+ --gate-policy enterprise-policy.json \
205
+ --format json \
206
+ --output migration-report.json
207
+ ```
208
+
209
+ Enterprise enforcement:
210
+
211
+ - Prevents suppression of blocked and protected rules.
212
+ - Includes suppressed findings in risk calculations.
213
+ - Enforces suppression limits.
214
+ - Rejects project exclusions and severity-weakening overrides.
215
+ - Can block a migration even when `--fail-on none` is supplied.
216
+
217
+ Use a separate trusted configuration for enterprise gates. Do not reuse ordinary lint configurations containing exclusions or warning/off rule overrides.
218
+
219
+ The CLI, policy, configuration and CI workflow must come from trusted sources.
220
+
221
+ ### VS Code Integration
222
+
223
+ The PG Safe Migrate extension supports inline suppression through workspace configuration.
224
+
225
+ - Suppressed findings are removed from active diagnostics.
226
+ - Protected findings remain visible.
227
+ - Suppression audit counts appear in the PG Safe Migrate Output channel.
228
+ - Disabling suppression restores the original findings.
229
+
230
+ ### Limitations
231
+
232
+ - Suppression is not evidence of migration safety.
233
+ - Some combinations of suppression, risk baselines and combined simulation are not supported.
234
+ - Static analysis cannot guarantee zero downtime.
235
+
236
+ ## Advanced capabilities
237
+
238
+ - [Advanced usage, simulation, database inspection and limitations](docs/advanced.md)
239
+ - [Adoption and CI troubleshooting](docs/ADOPTION-GUIDE.md)
240
+ - [Release history](CHANGELOG.md)
241
+ - [Verification commands](ALL-MILESTONES-TESTING.md)
222
242
 
223
243
  ## Development
224
244
 
225
- Clone the repository:
226
-
227
- ```bash
228
- git clone https://github.com/subodhsingh001/pg-safe-migrate.git
229
- cd pg-safe-migrate
230
- ```
231
-
232
- Install dependencies:
233
-
234
- ```bash
245
+ ```sh
235
246
  npm ci
236
- ```
237
-
238
- Run tests:
239
-
240
- ```bash
241
- npm test
242
- ```
243
-
244
- Test the rule engine:
245
-
246
- ```bash
247
- node bin/cli.js examples/unsafe.sql
248
- ```
249
-
250
- Check the npm package:
251
-
252
- ```bash
247
+ npm run test:release
253
248
  npm pack --dry-run
254
249
  ```
255
250
 
256
- ## CLI v2.6.0
257
-
258
- Version v2.6.0 adds improved SQL positions, transaction tracking and rule catalog metadata. See [CHANGELOG.md](CHANGELOG.md).
259
-
260
- - Expanded PostgreSQL migration risk checks and framework advisories
261
- - PostgreSQL AST-based parsing
262
- - Prisma and Drizzle migration directory detection
263
- - Git-diff mode
264
- - GitHub Actions support
265
- - JSON/SARIF reports and optional advisor
266
- - Configurable severity, exclusions, and PostgreSQL-version guidance
267
- - Actionable migration recommendations
268
-
269
- [View npm package](https://www.npmjs.com/package/@subodh001/pg-safe-migrate) · [View GitHub releases](https://github.com/subodhsingh001/pg-safe-migrate/releases) · [Report an issue](https://github.com/subodhsingh001/pg-safe-migrate/issues)
270
-
271
- ## Limitations
272
-
273
- `pg-safe-migrate` is a static AST-based PostgreSQL migration linter. Static linting is not a migration execution simulator.
274
-
275
- ### Parser and diagnostic capabilities
276
-
277
- Version v2.6.0 includes:
278
-
279
- - Unicode-aware diagnostic positions with UTF-16 editor coordinates.
280
- - Windows CRLF and Unix LF compatibility.
281
- - Single-line and nested block comment handling.
282
- - Dollar-quoted and escaped string handling.
283
- - Explicit transaction tracking, including savepoints and chained transactions.
284
- - PostgreSQL syntax error detection.
285
-
286
- These parser improvements are included in v2.6.0. Large SQL inputs can consume substantial memory; static analysis has no hard process memory cap.
287
-
288
- ### Static analysis boundaries
289
-
290
- Static linting does not:
291
-
292
- - Connect to your production database.
293
- - Estimate actual lock waiting times.
294
- - Validate rollback procedures.
295
- - Inspect live database schemas.
296
- - Comprehensively analyze SQL inside PL/pgSQL functions, stored procedures or anonymous DO blocks.
297
- - Resolve dynamically generated SQL.
298
- - Analyze SQL embedded inside JavaScript or TypeScript files.
299
- - Detect every application-managed or ORM-managed transaction.
300
- - Guarantee zero downtime or production migration safety.
301
-
302
- Some flagged operations may be acceptable under controlled conditions. Some unflagged operations may still cause downtime.
303
-
304
- Optional database inspection and disposable PostgreSQL simulation are separate capabilities with their own limitations.
305
-
306
- Always consider PostgreSQL version, table size, transaction behavior, lock timeouts, long-running transactions and application deployment sequencing.
307
-
308
- Validate migrations against a representative PostgreSQL environment before production deployment.
309
-
310
- ## Validation and real ORM runners
311
-
312
- The repository includes a curated SQL regression suite (`test/real-world-cases.test.js`) and an opt-in integration runner (`scripts/orm-runner/verify.mjs`) using a disposable PostgreSQL database. On 2026-11-17 the maintainer verified that Prisma 6.19.x `migrate deploy` applied a **standalone** `CREATE INDEX CONCURRENTLY` migration; the tested Drizzle ORM 0.44.x node-postgres migrator rejected the same operation inside its transaction with PostgreSQL error `25001`. The runner asserts both outcomes and checks that temporary schemas are cleaned up. See `scripts/orm-runner/README.md` and `RELEASE-VERIFICATION.md`. These observations are version- and runner-specific and do not establish a production false-positive rate.
313
-
314
- ## Contributing
315
-
316
- Contributions, bug reports, PostgreSQL edge cases, and suggestions for additional safety rules are welcome.
317
-
318
- Open an issue or submit a pull request on GitHub.
319
-
320
- ## License
321
-
322
- MIT License.
323
-
324
- ## v2.0 features
325
-
326
- - `--postgres-version 10` enables PostgreSQL-10-specific default-column rewrite warnings; version 11+ does not trigger that rule. This is a targeted version check, not complete PostgreSQL-version simulation.
327
- - `--advisor` gives Prisma/Drizzle/raw-SQL-aware deployment guidance. Recommendations are advisory and do not inspect the live database.
328
- - Cross-file analysis checks files in lexicographic order and warns on selected operations involving tables changed earlier. This is a heuristic, not a dependency graph.
329
- - Transaction analysis uses parsed SQL statements, avoiding comment/string false positives from keyword matching. It cannot know whether an external ORM runner wraps a migration in a transaction.
330
- - JSON and SARIF outputs include source locations when the PostgreSQL parser supplies statement offsets.
331
- - `examples/consumer-workflow.yml` illustrates GitHub code-scanning SARIF upload and policy enforcement. GitHub code-scanning availability and permissions depend on repository settings and plan.
332
-
333
- ### Examples
334
-
335
- ```bash
336
- node bin/cli.js prisma/migrations --postgres-version 16 --advisor
337
- node bin/cli.js db/migrations --format json --output report.json
338
- node bin/cli.js --changed origin/main --format sarif --output report.sarif --fail-on none
339
- ```
340
-
341
- ### Known gaps
342
-
343
- The analyzer does not connect to PostgreSQL, determine real table sizes, model application compatibility, or prove migrations are safe. Prisma and Drizzle transaction behavior depends on the actual runner and configuration. SARIF code-scanning upload is optional and needs GitHub security permissions.
344
-
345
- ### Experimental: read-only database catalog snapshot
346
-
347
- The opt-in `--inspect-db` mode returns PostgreSQL major version, approximate table row counts and table sizes as JSON. It **does not execute migrations** or assess production safety. Install the optional `pg` dependency in your project and provide a least-privilege connection URL:
348
-
349
- ```powershell
350
- npm install pg
351
- $env:DATABASE_URL = 'postgresql://readonly_user:password@127.0.0.1:5432/testdb'
352
- node bin/cli.js --inspect-db
353
- ```
354
-
355
- This mode uses a read-only transaction, catalog queries, a five-second statement timeout and a 50-table default limit. Do not use privileged production credentials. Real-database integration testing remains outstanding.
356
-
357
- ### Experimental disposable PostgreSQL simulation
358
-
359
- To check whether a SQL migration executes against an **empty disposable PostgreSQL database** (requires local Docker and a locally available PostgreSQL image):
360
-
361
- ```sh
362
- node bin/cli.js --simulate examples/safe.sql --postgres-version 16
363
- node bin/cli.js --simulate examples/unsafe.sql --postgres-version 16 --simulate-timeout 60
364
- ```
365
-
366
- The simulator launches a new `postgres:14` through `postgres:18` container, disables its network, limits memory/CPU/processes, does not mount host files or use `DATABASE_URL`, runs SQL via `docker exec -i`, and forcibly removes the container afterward. Docker images may be downloaded automatically. **Do not use it as a sandbox for hostile code:** Docker isolation is not a hardened security boundary. Run only migrations from trusted contributors, preferably on a dedicated CI runner. Simulation against an empty database cannot predict production locks, data-dependent failures, rollback success, or downtime. It never runs against a real database. A nonzero exit code indicates SQL execution failure (1) or a tool/runtime error (2).
367
-
368
- ### Docker simulator with baseline and ordered migrations (experimental)
369
-
370
- The simulator starts a disposable PostgreSQL container without published ports or external networking.
371
- Use a baseline to create tables that a migration expects:
372
-
373
- ```cmd
374
- node bin/cli.js --simulate examples/safe.sql --baseline examples/baseline.sql --postgres-version 16
375
- node bin/cli.js --simulate examples/unsafe.sql --baseline examples/baseline.sql --postgres-version 16
376
- ```
377
-
378
- Run all top-level `.sql` files in a folder in lexicographic filename order:
379
-
380
- ```cmd
381
- node bin/cli.js --migrations-dir path/to/migrations --baseline examples/baseline.sql --postgres-version 16
382
- ```
383
-
384
- Each JSON result contains a `steps` array with distinct `baseline` and `migration` stages. Execution stops on the first failure, and the disposable container is removed. This is a functional smoke test, **not** a guarantee of production safety, downtime, data preservation, or rollback. A successful `unsafe.sql` simulation does not mean the migration is safe.
385
-
386
- The directory mode processes only top-level `.sql` files (maximum 100); nested ORM-specific migration directories are not automatically traversed.
387
-
388
- ## Consolidated experimental development capabilities
389
-
390
- See [ALL-MILESTONES-TESTING.md](ALL-MILESTONES-TESTING.md) for exact commands and verification limitations. `--assess` combines lint findings, lock classifications, heuristic risk score, deployment advice, Docker execution, optional `--verify-sql` assertions, and optional `--team-policy` checks. The Docker matrix script covers PostgreSQL 14–18 when Docker is available. `vscode-extension/` provides a standalone VS Code extension; team policy is a local JSON configuration, **not** a hosted team management service.
391
-
392
- ## Markdown migration report (Week 2 Day 6)
393
-
394
- Run `pg-safe-migrate migrations --format markdown --risk --output migration-report.md` to generate an actionable Markdown report with rule IDs, locations, recommended actions, and an optional heuristic risk breakdown. This does not predict production downtime.
251
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and [SECURITY.md](SECURITY.md). MIT licensed.
package/bin/cli.js CHANGED
@@ -13,11 +13,12 @@ import { findMigrationFiles } from '../src/detector.js';
13
13
  import { getChangedSqlFiles } from '../src/gitDiff.js';
14
14
  import { loadConfig, isExcluded } from '../src/config.js';
15
15
  import { analyzeFiles } from '../src/analysis.js';
16
+ import { suppressionReport, suppressionText, suppressionMarkdown } from '../src/suppression-report.js';
16
17
  import { toJson, toSarif, toMarkdownReport } from '../src/reports.js';
17
18
  import { inspectDatabaseUrl } from '../src/db-inspect.js';
18
19
  import { simulateSqlFile } from '../src/simulator.js';
19
20
  import { combinedAssessment } from '../src/combined.js';
20
- import { loadTeamPolicy, assessTeamPolicy, assessLintPolicy } from '../src/team-policy.js';
21
+ import { loadTeamPolicy, assessTeamPolicy, assessLintPolicy, validateGateConfig, applySuppressionPolicy, enforceSuppressionAudit } from '../src/team-policy.js';
21
22
  import { loadProductionContext, productionAssessment } from '../src/production-context.js';
22
23
  import { createRiskBaseline, loadRiskBaseline, compareRiskBaseline, writeRiskBaseline } from '../src/risk-baseline.js';
23
24
 
@@ -59,8 +60,10 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
59
60
  config.postgresVersion=version;
60
61
  }
61
62
  if ((opts.gatePolicy || opts.riskBaseline || opts.writeRiskBaseline || opts.productionContext) && (opts.assess || opts.simulate || opts.migrationsDir || opts.inspectDb)) throw new Error('--gate-policy is for static lint mode only');
63
+ if (config.suppression?.enabled && (opts.assess || opts.teamPolicy || ((opts.riskBaseline || opts.writeRiskBaseline) && opts.gatePolicy))) throw new Error('Inline suppression is not supported with combined assessment or gate plus risk baseline');
62
64
  if (opts.assess) {
63
65
  const policy = opts.teamPolicy ? loadTeamPolicy(opts.teamPolicy) : null;
66
+ validateGateConfig(config, policy);
64
67
  const assessment = await combinedAssessment({ file: opts.simulate, migrationsDir: opts.migrationsDir, baseline: opts.baseline, verifySql: opts.verifySql, postgresVersion: String(opts.postgresVersion ?? '16'), config });
65
68
  if (policy) assessment.teamPolicy = assessTeamPolicy(assessment, policy);
66
69
  if (opts.output) { fs.mkdirSync(path.dirname(path.resolve(opts.output)), {recursive:true}); fs.writeFileSync(opts.output, JSON.stringify(assessment,null,2)+'\n'); }
@@ -80,23 +83,28 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
80
83
  return;
81
84
  }
82
85
  const gatePolicy = opts.gatePolicy ? loadTeamPolicy(opts.gatePolicy) : null;
86
+ validateGateConfig(config, gatePolicy);
83
87
  if (gatePolicy?.requireSimulation) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
84
88
  const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
85
89
  const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
86
- const findings=await analyzeFiles(entries,config,{advisor:opts.advisor});
87
- const production = opts.productionContext ? productionAssessment(findings, loadProductionContext(opts.productionContext)) : null;
90
+ const suppressionAudit = [];
91
+ const findings=await analyzeFiles(entries,applySuppressionPolicy(config, gatePolicy),{advisor:opts.advisor,suppressionAudit});
92
+ const suppression = config.suppression?.enabled ? suppressionReport(suppressionAudit) : undefined;
93
+ const allFindings = [...findings, ...suppressionAudit.filter(r => r.status === 'suppressed').map(r => r.finding)];
94
+ const production = opts.productionContext ? productionAssessment(allFindings, loadProductionContext(opts.productionContext)) : null;
88
95
  if (opts.writeRiskBaseline && opts.riskBaseline) throw new Error('Cannot combine --write-risk-baseline and --risk-baseline');
89
96
  if (opts.writeRiskBaseline && opts.gatePolicy) throw new Error('Baseline creation cannot be combined with a gate policy');
90
- const baselineComparison = opts.riskBaseline ? compareRiskBaseline(findings, entries, loadRiskBaseline(opts.riskBaseline)) : null;
97
+ const baselineComparison = opts.riskBaseline ? compareRiskBaseline(allFindings, entries, loadRiskBaseline(opts.riskBaseline)) : null;
91
98
  // In baseline mode, only newly introduced findings are subject to the opt-in gate.
92
99
  const gateFindings = baselineComparison ? baselineComparison.newFindings : findings;
93
- const gate = opts.gatePolicy ? assessLintPolicy(gateFindings, gatePolicy, summarizeRisk(gateFindings)) : null;
94
- if (opts.writeRiskBaseline) writeRiskBaseline(opts.writeRiskBaseline, createRiskBaseline(findings, entries));
100
+ const gate = opts.gatePolicy ? enforceSuppressionAudit(assessLintPolicy(suppression ? allFindings : gateFindings, gatePolicy, summarizeRisk(suppression ? allFindings : gateFindings)), gatePolicy, suppression) : null;
101
+ if (opts.writeRiskBaseline) writeRiskBaseline(opts.writeRiskBaseline, createRiskBaseline(allFindings, entries));
95
102
  if (opts.github) process.stdout.write(toGitHubAnnotations(findings));
96
- if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length));}
97
- const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion}):opts.format==='sarif'?toSarif(findings):opts.format==='markdown'?toMarkdownReport(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,risk:opts.risk?summarizeRisk(findings):undefined}):[
103
+ if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length) + (suppression ? suppressionMarkdown(suppression) : ''));}
104
+ const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,...(suppression ? { suppression } : {})}):opts.format==='sarif'?toSarif(findings,suppression):opts.format==='markdown'?toMarkdownReport(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,risk:opts.risk?summarizeRisk(allFindings):undefined,suppression}):[
98
105
  ...findings.flatMap(f=>[`${f.file}:${f.line}:${f.column} [${f.ruleId}] ${f.severity}: ${f.message}`,` Fix: ${f.fix}`,...(f.advisor?f.advisor.steps.map((s,i)=>` ${i+1}. ${s}`):[])]),
99
- ...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(findings))}`]:[]),
106
+ ...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(allFindings))}`]:[]),
107
+ ...(suppression ? [suppressionText(suppression)] : []),
100
108
  `Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
101
109
  ].join('\n');
102
110
  const gateReport = opts.format === 'json' && (gate || baselineComparison || production) ? JSON.stringify({ ...JSON.parse(report), ...(baselineComparison ? { baseline: { newCount: baselineComparison.newCount, existingCount: baselineComparison.existingCount, resolvedCount: baselineComparison.resolvedCount, newFindings: baselineComparison.newFindings } } : {}), ...(production ? { production } : {}), ...(gate ? { gate: { name: gate.name, decision: gate.passed ? 'PASS' : 'BLOCK', passed: gate.passed, reasons: gate.reasons, note: gate.note } } : {}) }, null, 2) : report;
@@ -104,7 +112,7 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
104
112
  else console.log(opts.format==='text'?(findings.length?chalk.yellow(gateReport):chalk.green(gateReport)):gateReport);
105
113
  if (production && opts.format !== 'json') console.error(`[PG Safe Migrate production] Advisory context evaluated for ${production.assessments.length} finding(s). Use --format json for details. No downtime guarantee.`);
106
114
  if (baselineComparison && opts.format !== 'json') console.error(`[PG Safe Migrate baseline] ${baselineComparison.newCount} new, ${baselineComparison.existingCount} existing, ${baselineComparison.resolvedCount} resolved finding(s).`);
107
- if (opts.writeRiskBaseline) console.error(`[PG Safe Migrate baseline] Wrote ${findings.length} finding fingerprint(s) to ${opts.writeRiskBaseline}; review before committing.`);
115
+ if (opts.writeRiskBaseline) console.error(`[PG Safe Migrate baseline] Wrote ${allFindings.length} finding fingerprint(s) to ${opts.writeRiskBaseline}; review before committing.`);
108
116
  if (gate) console.error(`[PG Safe Migrate gate] ${gate.passed ? 'PASS' : 'BLOCK'} (${gate.name})${gate.reasons.length ? ': '+gate.reasons.join('; ') : ''}. ${gate.note}`);
109
117
  process.exitCode=(gate && !gate.passed) || (opts.failOn==='warning' && gateFindings.length>0) || (opts.failOn==='error' && gateFindings.some(f=>f.severity==='error')) ? 1 : 0;
110
118
  }catch(e){console.error(`Error: ${e.message}`);process.exitCode=2;}
@@ -5,7 +5,6 @@ on:
5
5
  - '**/*.sql'
6
6
  permissions:
7
7
  contents: read
8
- security-events: write
9
8
  jobs:
10
9
  migrations:
11
10
  runs-on: ubuntu-latest
@@ -13,23 +12,11 @@ jobs:
13
12
  - uses: actions/checkout@v4
14
13
  with:
15
14
  fetch-depth: 0
15
+ persist-credentials: false
16
16
  - uses: actions/setup-node@v4
17
17
  with:
18
- node-version: '20'
19
- - name: Install pinned migration linter
20
- run: npm install --no-save --package-lock=false @subodh001/pg-safe-migrate@2.0.0-rc.2
21
- - name: Analyze changed migrations and create SARIF
22
- if: github.event_name == 'pull_request'
18
+ node-version: '22'
19
+ - name: Check changed SQL
23
20
  env:
24
21
  BASE_REF: ${{ github.base_ref }}
25
- run: |
26
- npx pg-safe-migrate --changed "origin/$BASE_REF" --format sarif --output pg-safe-migrate.sarif --fail-on none
27
- - name: Upload code scanning report
28
- if: always() && hashFiles('pg-safe-migrate.sarif') != ''
29
- uses: github/codeql-action/upload-sarif@v3
30
- with:
31
- sarif_file: pg-safe-migrate.sarif
32
- - name: Enforce migration policy
33
- env:
34
- BASE_REF: ${{ github.base_ref }}
35
- run: npx pg-safe-migrate --changed "origin/$BASE_REF" --fail-on error
22
+ run: npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --changed "origin/$BASE_REF" --fail-on error
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "reviewed-suppression-policy",
3
+ "blockedRules": ["PG011", "PG023"],
4
+ "maxRiskScore": 60,
5
+ "suppression": {
6
+ "protectedRules": ["PG008"],
7
+ "maxSuppressedFindings": 5,
8
+ "failOnRejected": true,
9
+ "failOnUnused": true
10
+ }
11
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@subodh001/pg-safe-migrate",
3
- "version": "2.6.0",
3
+ "version": "2.7.0",
4
4
  "description": "Detect risky PostgreSQL schema migrations before deployment: SQL linting, lock analysis, risk scoring and CI reports for Prisma, Drizzle and Flyway",
5
5
  "type": "module",
6
6
  "bin": {
package/src/analysis.js CHANGED
@@ -2,6 +2,8 @@ import { parseSqlFile } from './parser.js';
2
2
  import { lintStatements } from './engine.js';
3
3
  import { advise } from './advisor.js';
4
4
  import { lockFor } from './locks.js';
5
+ import { normalizeSuppression } from './config.js';
6
+ import { matchSuppressions } from './suppression-matcher.js';
5
7
 
6
8
  const ADVISORY_RULES = new Set(['PG015', 'PG016', 'PG017']);
7
9
 
@@ -209,6 +211,9 @@ export async function analyzeFiles(
209
211
  options = {}
210
212
  ) {
211
213
  const findings = [];
214
+ const policy = normalizeSuppression(config.suppression);
215
+ const audit = options.suppressionAudit;
216
+ if (policy.enabled && !Array.isArray(audit)) throw new Error('Enabled suppression requires an audit sink');
212
217
  const seen = new Map();
213
218
 
214
219
  const version = config.postgresVersion ?? null;
@@ -222,6 +227,17 @@ export async function analyzeFiles(
222
227
  details: true
223
228
  });
224
229
 
230
+ const candidates = new Map();
231
+ if (policy.enabled) {
232
+ const result = await matchSuppressions(sql, parsed);
233
+ if (result.scanError) audit.push({ file, status: 'scan-error', ...result.scanError });
234
+ for (const rejected of result.rejected) audit.push({ file, status: 'rejected', ...rejected });
235
+ for (const match of result.matches) {
236
+ if (match.ruleIds.some(id => policy.protectedRules.includes(id))) {
237
+ audit.push({ file, status: 'rejected', ...match, message: 'Directive includes a protected rule' });
238
+ } else candidates.set(match.statementOffset, { match, used: new Set() });
239
+ }
240
+ }
225
241
  const framework = frameworkFor(file);
226
242
  const locate = createPositionTracker(sql);
227
243
 
@@ -360,7 +376,7 @@ export async function analyzeFiles(
360
376
  continue;
361
377
  }
362
378
 
363
- findings.push({
379
+ const finding = {
364
380
  ...issue,
365
381
  severity,
366
382
  file,
@@ -373,7 +389,12 @@ export async function analyzeFiles(
373
389
  advisor: advise(issue, framework)
374
390
  }
375
391
  : {})
376
- });
392
+ };
393
+ const candidate = candidates.get(offset);
394
+ if (candidate?.match.ruleIds.includes(issue.ruleId)) {
395
+ candidate.used.add(issue.ruleId);
396
+ audit.push({ file, status: 'suppressed', directiveLine: candidate.match.line, reason: candidate.match.reason, finding });
397
+ } else findings.push(finding);
377
398
  }
378
399
 
379
400
  // Close the explicit transaction after processing.
@@ -381,6 +402,9 @@ export async function analyzeFiles(
381
402
  inTransaction = Boolean(stmt.TransactionStmt?.chain);
382
403
  }
383
404
  }
405
+ for (const { match, used } of candidates.values()) {
406
+ for (const ruleId of match.ruleIds) if (!used.has(ruleId)) audit.push({ file, status: 'unused', ruleId, directiveLine: match.line, reason: match.reason });
407
+ }
384
408
  }
385
409
 
386
410
  return findings;
package/src/config.js CHANGED
@@ -1,5 +1,16 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { getRule } from './rules/ruleCatalog.js';
4
+
5
+ export function normalizeSuppression(value = {}) {
6
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('suppression must be an object');
7
+ for (const key of Object.keys(value)) if (!['enabled','requireReason','reportSuppressed','protectedRules'].includes(key)) throw new Error(`Unknown suppression option: ${key}`);
8
+ if (value.enabled !== undefined && typeof value.enabled !== 'boolean') throw new Error('suppression.enabled must be boolean');
9
+ for (const key of ['requireReason','reportSuppressed']) if (value[key] !== undefined && value[key] !== true) throw new Error(`suppression.${key} must be true in this development version`);
10
+ const protectedRules = value.protectedRules === undefined ? ['PG011','PG023'] : value.protectedRules;
11
+ if (!Array.isArray(protectedRules) || protectedRules.some(id => typeof id !== 'string' || !/^PG\d{3}$/.test(id) || !getRule(id))) throw new Error('suppression.protectedRules must contain known rule IDs');
12
+ return { enabled: value.enabled ?? false, requireReason: true, reportSuppressed: true, protectedRules: [...new Set(protectedRules)] };
13
+ }
3
14
 
4
15
  export const DEFAULT_CONFIG = Object.freeze({ severity: 'error', rules: {}, exclude: [], postgresVersion: null });
5
16
  export function loadConfig(file = 'pg-safe-migrate.config.json') {
@@ -16,7 +27,7 @@ export function loadConfig(file = 'pg-safe-migrate.config.json') {
16
27
  }
17
28
  if (parsed.severity !== undefined && !['warning','error'].includes(parsed.severity)) throw new Error('severity must be warning or error.');
18
29
  if (parsed.postgresVersion != null && (!Number.isInteger(parsed.postgresVersion) || parsed.postgresVersion < 10 || parsed.postgresVersion > 99)) throw new Error('postgresVersion must be an integer >= 10.');
19
- return { ...DEFAULT_CONFIG, ...parsed, rules };
30
+ return { ...DEFAULT_CONFIG, ...parsed, rules, suppression: normalizeSuppression(parsed.suppression) };
20
31
  }
21
32
  export function isExcluded(file, patterns, cwd = process.cwd()) {
22
33
  const rel = path.relative(cwd, path.resolve(file)).replaceAll('\\','/');
package/src/reports.js CHANGED
@@ -1,12 +1,15 @@
1
+ import { suppressionMarkdown } from './suppression-report.js';
1
2
  export function toJson(findings, meta = {}) { return JSON.stringify({ tool: 'pg-safe-migrate', ...meta, findings }, null, 2); }
2
- export function toSarif(findings) {
3
- const ids = [...new Set(findings.map(f => f.ruleId))].sort();
4
- return JSON.stringify({ version: '2.1.0', $schema: 'https://json.schemastore.org/sarif-2.1.0.json', runs: [{ tool: { driver: { name: 'pg-safe-migrate', informationUri: 'https://github.com/subodhsingh001/pg-safe-migrate', rules: ids.map(id => ({ id, shortDescription: { text: id } })) } }, results: findings.map(f => ({ ruleId: f.ruleId, level: f.severity === 'warning' ? 'warning' : 'error', message: { text: `${f.message} Fix: ${f.fix}` }, locations: [{ physicalLocation: { artifactLocation: { uri: f.file.replaceAll('\\','/') }, region: { startLine: Math.max(1, f.line || 1), startColumn: Math.max(1, f.column || 1) } } }] })) }] }, null, 2);
3
+ export function toSarif(findings, audit) {
4
+ const suppressed = audit?.records.filter(r => r.status === 'suppressed') ?? [];
5
+ const all = [...findings, ...suppressed.map(r => r.finding)];
6
+ const ids = [...new Set(all.map(f => f.ruleId))].sort();
7
+ return JSON.stringify({ version: '2.1.0', $schema: 'https://json.schemastore.org/sarif-2.1.0.json', runs: [{ tool: { driver: { name: 'pg-safe-migrate', informationUri: 'https://github.com/subodhsingh001/pg-safe-migrate', rules: ids.map(id => ({ id, shortDescription: { text: id } })) } }, ...(audit ? { properties: { suppression: audit } } : {}), results: all.map((f, i) => ({ ...(i >= findings.length ? { suppressions: [{ kind: 'inSource', justification: suppressed[i - findings.length].reason }] } : {}), ruleId: f.ruleId, level: f.severity === 'warning' ? 'warning' : 'error', message: { text: `${f.message} Fix: ${f.fix}` }, locations: [{ physicalLocation: { artifactLocation: { uri: f.file.replaceAll('\\','/') }, region: { startLine: Math.max(1, f.line || 1), startColumn: Math.max(1, f.column || 1) } } }] })) }] }, null, 2);
5
8
  }
6
9
 
7
10
  // Human-readable report. Escapes Markdown cells and never includes untrusted HTML.
8
11
  const mdCell = value => String(value ?? '').replace(/\r?\n/g, ' ').replace(/\|/g, '\\|').replace(/</g, '&lt;').replace(/>/g, '&gt;');
9
- export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVersion, risk } = {}) {
12
+ export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVersion, risk, suppression } = {}) {
10
13
  const errors = findings.filter(f => f.severity === 'error').length;
11
14
  const warnings = findings.filter(f => f.severity === 'warning').length;
12
15
  const lines = [
@@ -31,5 +34,5 @@ export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVers
31
34
  lines.push('');
32
35
  }
33
36
  lines.push('> Static analysis is advisory. Review locks, data volume, transaction behavior, and production workload before deployment.', '');
34
- return lines.join('\n');
37
+ return lines.join('\n') + (suppression ? suppressionMarkdown(suppression) : '');
35
38
  }
@@ -0,0 +1,24 @@
1
+ import { parseSqlFile } from './parser.js';
2
+ import { scanSuppressions } from './suppression.js';
3
+ import { getRule } from './rules/ruleCatalog.js';
4
+
5
+ // Preview only: no findings are removed and no CLI policy is changed.
6
+ export async function matchSuppressions(sql, parsed) {
7
+ const statements = parsed ?? await parseSqlFile(sql, { details: true });
8
+ const scan = scanSuppressions(sql);
9
+ const matches = [], rejected = [...scan.invalid];
10
+ let index = 0;
11
+ for (const directive of scan.directives) {
12
+ while (index < statements.length && statements[index].offset < directive.endOffset) index++;
13
+ const target = statements[index];
14
+ let message;
15
+ if (!directive.reason) message = 'Suppression reason required';
16
+ else if (directive.ruleIds.some(id => !getRule(id))) message = 'Unknown rule ID';
17
+ else if (!target || !/^[ \t\r\n]*$/.test(sql.slice(directive.endOffset, target.offset))) message = 'No immediately following statement';
18
+ // A comment inside a statement cannot bind across its terminating semicolon:
19
+ // the whitespace-only gap above rejects that semicolon and all SQL tokens.
20
+ if (message) rejected.push({ ...directive, message });
21
+ else matches.push({ ...directive, statementIndex: index, statementOffset: target.offset });
22
+ }
23
+ return { matches, rejected, scanError: scan.scanError };
24
+ }
@@ -0,0 +1,19 @@
1
+ export function suppressionReport(records) {
2
+ const summary = { suppressed: 0, rejected: 0, unused: 0, scanErrors: 0 };
3
+ for (const r of records) {
4
+ const key = r.status === 'scan-error' ? 'scanErrors' : r.status;
5
+ if (!Object.hasOwn(summary, key)) throw new Error('Unknown suppression audit status');
6
+ summary[key]++;
7
+ }
8
+ return { summary, records };
9
+ }
10
+ const safe = value => String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, ' ');
11
+ const cell = value => safe(value).replace(/[&<>\\|`*_~\[\]#!]/g, c => `&#${c.charCodeAt(0)};`);
12
+ export function suppressionText(audit) {
13
+ const s = audit.summary;
14
+ return [`Suppression audit: ${s.suppressed} suppressed, ${s.rejected} rejected, ${s.unused} unused, ${s.scanErrors} scan errors.`, ...audit.records.map(r => ` ${safe(r.status)} ${safe(r.finding?.ruleId ?? r.ruleId ?? r.ruleIds?.join(', '))} ${safe(r.file)}:${r.directiveLine ?? r.line ?? '?'} — ${safe(r.reason)} ${safe(r.message)}`), 'Suppression is not evidence of migration safety.'].join('\n');
15
+ }
16
+ export function suppressionMarkdown(audit) {
17
+ const s = audit.summary;
18
+ return ['','## Suppression audit','',`${s.suppressed} suppressed, ${s.rejected} rejected, ${s.unused} unused, ${s.scanErrors} scan errors.`, '', '| Status | Rule | File | Directive line | Reason | Detail |','|---|---|---|---:|---|---|', ...audit.records.map(r => `| ${cell(r.status)} | ${cell(r.finding?.ruleId ?? r.ruleId ?? r.ruleIds?.join(', '))} | ${cell(r.file)} | ${cell(r.directiveLine ?? r.line)} | ${cell(r.reason)} | ${cell(r.message ?? r.finding?.message)} |`), '', 'Suppression is not evidence of migration safety.', ''].join('\n');
19
+ }
@@ -0,0 +1,78 @@
1
+ // Detection only. Never use these candidates to suppress findings without AST binding.
2
+ const directive = /^\s*pg-safe-migrate-disable-next-line\b(.*)$/i;
3
+ const syntax = /^\s+(PG\d{3}(?:[ \t]*,[ \t]*PG\d{3})*)[ \t]*(?:--[ \t]*reason:[ \t]*(.*))?$/i;
4
+ const identifier = /[a-zA-Z_\u0080-\uffff]/;
5
+ const continuation = /[a-zA-Z_0-9$\u0080-\uffff]/;
6
+
7
+ export function scanSuppressions(sql) {
8
+ if (typeof sql !== 'string') throw new TypeError('SQL must be a string');
9
+ const directives = [], invalid = [];
10
+ let i = 0, line = 1, lineStart = 0;
11
+ function advance(end) {
12
+ while (i < end) {
13
+ if (sql[i] === '\r' || (sql[i] === '\n' && sql[i-1] !== '\r')) line++;
14
+ if (sql[i] === '\r' || sql[i] === '\n') lineStart = i + 1;
15
+ i++;
16
+ }
17
+ }
18
+ function fail(message) { return { directives: [], invalid: [], scanError: { line, offset: i, message } }; }
19
+ while (i < sql.length) {
20
+ const c = sql[i];
21
+ if (sql.startsWith('--', i)) {
22
+ const start = i, startLine = line;
23
+ let end = i + 2;
24
+ while (end < sql.length && !/[\r\n]/.test(sql[end])) end++;
25
+ const match = directive.exec(sql.slice(i+2,end));
26
+ if (match && /^[ \t]*$/.test(sql.slice(lineStart,i))) {
27
+ const parsed = syntax.exec(match[1]);
28
+ const location = { line: startLine, offset: start, endOffset: end };
29
+ if (!parsed) invalid.push({ ...location, message: 'Malformed suppression directive' });
30
+ else directives.push({ ...location, ruleIds: [...new Set(parsed[1].toUpperCase().split(',').map(s=>s.trim()))], reason: (parsed[2] || '').trim() });
31
+ }
32
+ advance(end); continue;
33
+ }
34
+ if (sql.startsWith('/*', i)) {
35
+ let depth = 1; advance(i+2);
36
+ while (i < sql.length && depth) {
37
+ if (sql.startsWith('/*',i)) { depth++; advance(i+2); }
38
+ else if (sql.startsWith('*/',i)) { depth--; advance(i+2); }
39
+ else advance(i+1);
40
+ }
41
+ if (depth) return fail('Unterminated block comment');
42
+ continue;
43
+ }
44
+ const escape = /[eE]/.test(c) && sql[i+1] === "'";
45
+ if (escape || c === "'" || c === '"') {
46
+ const quote = escape ? "'" : c;
47
+ advance(i+(escape?2:1)); let closed = false;
48
+ while (i < sql.length) {
49
+ if (sql[i] === '\\' && quote === "'") {
50
+ if (!escape) return fail('Ambiguous backslash in ordinary string; suppression scan disabled');
51
+ advance(Math.min(i+2,sql.length)); continue;
52
+ }
53
+ if (sql[i] === quote) {
54
+ if (sql[i+1] === quote) { advance(i+2); continue; }
55
+ advance(i+1); closed = true; break;
56
+ }
57
+ advance(i+1);
58
+ }
59
+ if (!closed) return fail('Unterminated quoted token');
60
+ continue;
61
+ }
62
+ if (c === '$') {
63
+ const tag = /^\$(?:[a-zA-Z_\u0080-\uffff][a-zA-Z_0-9\u0080-\uffff]*)?\$/.exec(sql.slice(i));
64
+ if (tag) {
65
+ const end = sql.indexOf(tag[0], i+tag[0].length);
66
+ if (end < 0) return fail('Unterminated dollar quote');
67
+ advance(end+tag[0].length); continue;
68
+ }
69
+ }
70
+ if (identifier.test(c)) {
71
+ let end = i+1;
72
+ while (end < sql.length && continuation.test(sql[end])) end++;
73
+ advance(end); continue;
74
+ }
75
+ advance(i+1);
76
+ }
77
+ return { directives, invalid, scanError: null };
78
+ }
@@ -4,14 +4,22 @@ import { getRule } from './rules/ruleCatalog.js';
4
4
  export function loadTeamPolicy(file) {
5
5
  const policy = JSON.parse(fs.readFileSync(file, 'utf8'));
6
6
  if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new Error('Team policy must be a JSON object');
7
- const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation'];
7
+ const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation', 'suppression'];
8
8
  for (const key of Object.keys(policy)) if (!allowed.includes(key)) throw new Error(`Unknown team policy key: ${key}`);
9
9
  if (policy.name !== undefined && (typeof policy.name !== 'string' || !policy.name.trim() || policy.name.length > 100)) throw new Error('name must be a nonempty string of at most 100 characters');
10
10
  if (policy.maxRiskScore !== undefined && (!Number.isInteger(policy.maxRiskScore) || policy.maxRiskScore < 0 || policy.maxRiskScore > 100)) throw new Error('maxRiskScore must be 0-100');
11
11
  if (policy.maxWarnings !== undefined && (!Number.isInteger(policy.maxWarnings) || policy.maxWarnings < 0)) throw new Error('maxWarnings must be >= 0');
12
- if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => typeof x !== 'string' || !getRule(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
12
+ if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => typeof x !== 'string' || !/^PG\d{3}$/.test(x) || !getRule(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
13
13
  if (policy.blockedRules && new Set(policy.blockedRules).size !== policy.blockedRules.length) throw new Error('blockedRules must not contain duplicates');
14
14
  if (policy.requireSimulation !== undefined && typeof policy.requireSimulation !== 'boolean') throw new Error('requireSimulation must be boolean');
15
+ if (policy.suppression !== undefined) {
16
+ const s = policy.suppression;
17
+ if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('policy.suppression must be an object');
18
+ for (const key of Object.keys(s)) if (!['protectedRules','maxSuppressedFindings','failOnRejected','failOnUnused'].includes(key)) throw new Error(`Unknown policy suppression key: ${key}`);
19
+ if (s.protectedRules !== undefined && (!Array.isArray(s.protectedRules) || s.protectedRules.some(id => typeof id !== 'string' || !/^PG\d{3}$/.test(id) || !getRule(id)))) throw new Error('Invalid policy protectedRules');
20
+ if (s.maxSuppressedFindings !== undefined && (!Number.isSafeInteger(s.maxSuppressedFindings) || s.maxSuppressedFindings < 0)) throw new Error('Invalid maxSuppressedFindings');
21
+ for (const key of ['failOnRejected','failOnUnused']) if (s[key] !== undefined && typeof s[key] !== 'boolean') throw new Error(`Invalid ${key}`);
22
+ }
15
23
  return policy;
16
24
  }
17
25
 
@@ -46,3 +54,31 @@ export function assessLintPolicy(findings, policy, risk = {}) {
46
54
  for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
47
55
  return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)], note: 'Passing a static gate is not a safety guarantee; unknown locks and production workloads still require review.' };
48
56
  }
57
+
58
+ // A static gate always evaluates all configured risks, including suppressed ones.
59
+ export function applySuppressionPolicy(config, policy) {
60
+ if (!config.suppression?.enabled || !policy) return config;
61
+ const protectedRules = [...new Set([...config.suppression.protectedRules, ...['PG011','PG023'], ...(policy.blockedRules ?? []), ...(policy.suppression?.protectedRules ?? [])])];
62
+ return { ...config, suppression: { ...config.suppression, protectedRules } };
63
+ }
64
+ export function enforceSuppressionAudit(gate, policy, audit) {
65
+ if (!audit) return gate;
66
+ const s = audit.summary;
67
+ const limits = policy.suppression ?? {};
68
+ const reasons = [...gate.reasons];
69
+ if (s.suppressed > (limits.maxSuppressedFindings ?? 0)) reasons.push('Suppression limit exceeded');
70
+ if (s.rejected && limits.failOnRejected !== false) reasons.push('Rejected suppression directives');
71
+ if (s.unused && limits.failOnUnused !== false) reasons.push('Unused suppression directives');
72
+ if (s.scanErrors) reasons.push('Suppression scan failed');
73
+ return { ...gate, reasons, passed: reasons.length === 0 };
74
+ }
75
+
76
+ // CI must supply trusted configuration, policy, target and PostgreSQL version.
77
+ export function validateGateConfig(config, policy) {
78
+ if (!policy) return;
79
+ if (config.exclude?.length) throw new Error('Enterprise policy does not allow project exclusions');
80
+ if (config.severity !== 'error') throw new Error('Enterprise policy requires default error severity');
81
+ for (const [id, severity] of Object.entries(config.rules ?? {})) {
82
+ if (severity === 'off' || severity === 'warning') throw new Error(`Enterprise policy does not allow weakening rule ${id}`);
83
+ }
84
+ }