@subodh001/pg-safe-migrate 2.4.0 → 2.6.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 ADDED
@@ -0,0 +1,43 @@
1
+ # Changelog
2
+
3
+ ## [2.6.0]
4
+
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).
8
+
9
+ ## [2.5.0] - 2026-11-20
10
+
11
+
12
+
13
+ ### Added
14
+
15
+ - Configurable CI migration safety gates.
16
+
17
+ - Reviewed migration risk baselines to distinguish new, existing, and resolved findings.
18
+
19
+ - Production-aware migration recommendations using optional workload and table-size estimates.
20
+
21
+ - GitHub Actions pull-request safety reporting.
22
+
23
+ - Improved onboarding, examples, and adoption documentation.
24
+
25
+
26
+
27
+ ### Improved
28
+
29
+ - JSON reporting for risk baselines, production context, and policy decisions.
30
+
31
+ - Migration safety guidance for deployment planning.
32
+
33
+ - Release-readiness verification and regression coverage.
34
+
35
+
36
+
37
+ ### Notes
38
+
39
+ - Production context uses supplied estimates, not live database measurements.
40
+
41
+ - Static analysis does not guarantee zero downtime.
42
+
43
+ - Existing migration safety rules remain available.
@@ -0,0 +1,3 @@
1
+ # Contributing
2
+
3
+ Fork the repository and create a focused branch. Install dependencies with `npm ci`. Add regression tests for rule changes and preserve stable diagnostic IDs. Run `npm run test:release` and `git diff --check`. For extension changes run `npm run build:standalone` and `npm run verify:standalone` in `vscode-extension`. Document limitations and include sanitized SQL reproductions. Do not commit secrets, generated VSIX files or local logs. Open a pull request describing the change and test results. Security reports should follow SECURITY.md.
package/README.md CHANGED
@@ -1,16 +1,14 @@
1
- > **Development candidate:** v2.1.0. See [MILESTONES.md](MILESTONES.md) for implemented features and explicitly unfinished v2.2/v3.0 work.
2
-
3
- > **Current release: v2.0.0.** Static migration risk detection is advisory, not a zero-downtime guarantee. See [UPGRADE-NOTES.md](UPGRADE-NOTES.md) for upgrade details and limitations.
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.
4
2
 
5
3
  # pg-safe-migrate
6
4
 
7
5
  **Catch risky PostgreSQL migrations before they reach production.**
8
6
 
9
- An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, and raw SQL**.
7
+ An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, Flyway, and raw SQL**.
10
8
 
11
9
  Detect risky PostgreSQL DDL patterns and provide additional framework-specific migration advisories.
12
10
 
13
- **Features:** PostgreSQL AST parsing · PG001–PG017 identifiers (see rule coverage below) · Git-diff mode · JSON/SARIF · configurable severity · optional advisor · GitHub Actions
11
+ **Features:** PostgreSQL AST parsing · migration risk diagnostics (see rule coverage below) · Git-diff mode · JSON/SARIF · configurable severity · optional advisor · GitHub Actions
14
12
 
15
13
  > **Important:** This tool identifies configured migration risks. It does not guarantee zero downtime.
16
14
 
@@ -18,7 +16,7 @@ Detect risky PostgreSQL DDL patterns and provide additional framework-specific m
18
16
 
19
17
  See how `pg-safe-migrate` catches an unsafe PostgreSQL migration and suggests a safer alternative.
20
18
 
21
- ![pg-safe-migrate CLI demonstration](assets/pg-safe-migrate-demo.gif)
19
+ ![pg-safe-migrate CLI demonstration](https://raw.githubusercontent.com/subodhsingh001/pg-safe-migrate/main/assets/pg-safe-migrate-demo.gif)
22
20
 
23
21
  ### Example
24
22
 
@@ -46,6 +44,27 @@ CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
46
44
 
47
45
  `CREATE INDEX CONCURRENTLY` must run outside a transaction block.
48
46
 
47
+
48
+ ## Week 3: opt-in CI policy gate
49
+
50
+ Run a deterministic, policy-driven static lint check in CI:
51
+
52
+ ```bash
53
+ node bin/cli.js db/migrations --gate-policy examples/week3-gate-policy.json --fail-on none
54
+ ```
55
+
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)
65
+
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
+
49
68
  ## Installation
50
69
 
51
70
  Install as a development dependency:
@@ -57,7 +76,7 @@ npm install --save-dev @subodh001/pg-safe-migrate
57
76
  Or execute the published package without installing it in your project:
58
77
 
59
78
  ```bash
60
- npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
79
+ npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --help
61
80
  ```
62
81
 
63
82
  ## Quick start
@@ -74,6 +93,9 @@ The CLI searches these directories:
74
93
  - `drizzle`
75
94
  - `migrations`
76
95
  - `db/migrations`
96
+ - `db/migration`
97
+ - `sql/migrations`
98
+ - `sql`
77
99
 
78
100
  ### Prisma
79
101
 
@@ -111,31 +133,37 @@ For pull requests, fetch the base branch first. Use `fetch-depth: 0` in GitHub A
111
133
 
112
134
  ## PostgreSQL migration rules
113
135
 
114
- | Rule | Detected pattern | Potential risk |
115
- |---|---|---|
116
- | **PG001** | CREATE INDEX without CONCURRENTLY | Blocks writes during index creation |
117
- | **PG002** | DROP COLUMN | Breaks older application versions |
118
- | **PG003** | ALTER COLUMN TYPE | Strong locks and possible table rewrites |
119
- | **PG004** | ADD COLUMN NOT NULL without DEFAULT | Backfill and compatibility risks |
120
- | **PG005** | ADD FOREIGN KEY without NOT VALID | Validation may block writes |
121
- | **PG006** | RENAME | Breaks applications expecting old names |
122
-
123
- Additional rule IDs in v2.0.0:
124
-
125
- | Rule | Detected pattern | Interpretation |
126
- |---|---|---|
127
- | **PG007** | DROP INDEX without CONCURRENTLY | Potential blocking |
128
- | **PG008** | CONCURRENTLY inside an explicit SQL transaction | PostgreSQL rejects this operation |
129
- | **PG010** | ADD UNIQUE constraint | Potential blocking index build |
130
- | **PG011** | DROP TABLE | Destructive change |
131
- | **PG012** | Validated CHECK constraint | May scan existing rows |
132
- | **PG013** | SET NOT NULL | Strong lock and potential scan |
133
- | **PG014** | ADD COLUMN with DEFAULT on PostgreSQL 10 | Version-specific rewrite risk |
134
- | **PG015** | Prisma CONCURRENTLY | Advisory: use a standalone migration; verified with Prisma 6.19.x `migrate deploy` |
135
- | **PG016** | Drizzle CONCURRENTLY | Advisory: tested Drizzle 0.44.x node-postgres migrator wraps migrations in a transaction, preventing this operation |
136
- | **PG017** | Cross-file rename/drop dependency | Heuristic advisory |
137
-
138
- PG009 is not implemented; rule identifiers are not contiguous. PG015–PG017 default to warnings, including when the standard global severity is `error`. Override an individual advisory with `rules.PG015`, `rules.PG016`, or `rules.PG017` in the configuration. `--fail-on error` only determines the CLI exit threshold, not rule classification.
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.
139
+
140
+ | ID | Diagnostic | Default | Guidance |
141
+ |---|---|---|---|
142
+ | PG001 | Non-concurrent index creation | error | Use CREATE INDEX CONCURRENTLY outside a transaction. |
143
+ | PG002 | Dropping a column | error | Deprecate consumers before removing the column. |
144
+ | PG003 | Changing a column type | error | Check binary compatibility; consider expand/backfill/contract. |
145
+ | PG004 | Adding NOT NULL column without default | error | Add nullable, backfill, then enforce NOT NULL. |
146
+ | PG005 | Adding validated foreign key | error | Add NOT VALID then VALIDATE CONSTRAINT separately. |
147
+ | PG006 | Renaming an object | error | Use an expand/contract deployment. |
148
+ | PG007 | Dropping index without CONCURRENTLY | error | Use DROP INDEX CONCURRENTLY where supported. |
149
+ | PG008 | Concurrent index operation inside transaction | error | Run outside BEGIN/COMMIT. |
150
+ | PG010 | Adding UNIQUE constraint | error | Consider a concurrent unique index and attach it where applicable. |
151
+ | PG011 | Dropping a table | error | Verify retention and application dependencies. |
152
+ | PG012 | Adding validated CHECK constraint | error | Add NOT VALID and validate separately. |
153
+ | PG013 | Legacy SET NOT NULL diagnostic (superseded by PG025) | error | Validate an equivalent CHECK constraint first. |
154
+ | PG014 | Adding column with default on PostgreSQL 10 | error | Use controlled backfill or evaluate upgrading PostgreSQL. |
155
+ | PG015 | Prisma concurrent index migration | warning | Use a separately managed nontransactional migration. |
156
+ | PG016 | Drizzle concurrent index migration | warning | Use a separately managed nontransactional migration. |
157
+ | PG017 | Potential cross-file dependency or Flyway transaction advisory | warning | Review migration order; this is a heuristic. |
158
+ | PG019 | MERGE requires PostgreSQL 15+ | error | Use a compatible INSERT ... ON CONFLICT pattern where applicable. |
159
+ | PG020 | UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+ | error | Use a version-compatible uniqueness strategy. |
160
+ | PG021 | Volatile default may rewrite table | error | Add column, backfill in batches, then set default. |
161
+ | PG022 | SET LOGGED rewrites table | error | Schedule controlled maintenance and evaluate alternatives. |
162
+ | PG023 | TRUNCATE removes table rows | error | Confirm retention, backups and downstream dependencies. |
163
+ | PG024 | Dropping a constraint | error | Review dependent queries and data-integrity requirements. |
164
+ | PG025 | SET NOT NULL may scan table | error | Backfill and validate a CHECK constraint first where appropriate. |
165
+
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.
139
167
 
140
168
  Example configuration (`pg-safe-migrate.config.json`):
141
169
 
@@ -148,7 +176,7 @@ Example configuration (`pg-safe-migrate.config.json`):
148
176
  }
149
177
  ```
150
178
 
151
- Report options: `--format text|json|sarif`, `--output <file>`, `--advisor`, `--postgres-version <major>`, and `--fail-on warning|error|none`.
179
+ Report options: `--format text|json|sarif|markdown`, `--output <file>`, `--advisor`, `--postgres-version <major>`, and `--fail-on warning|error|none`.
152
180
 
153
181
  Each finding includes a description of the risk and a suggested safer migration approach.
154
182
 
@@ -168,12 +196,12 @@ The workflow checks changed SQL migrations so teams can adopt the linter without
168
196
 
169
197
  For reproducible builds, pin the package to a reviewed version and upgrade deliberately.
170
198
 
171
- ## Verify the published CLI
199
+ ## Verify CLI v2.6.0 after publication
172
200
 
173
201
  From a clean directory, run:
174
202
 
175
203
  ```bash
176
- npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
204
+ npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --help
177
205
  ```
178
206
 
179
207
  Create a file named `unsafe.sql`:
@@ -185,7 +213,7 @@ CREATE INDEX idx_users_email ON users(email);
185
213
  Then execute:
186
214
 
187
215
  ```bash
188
- npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate unsafe.sql
216
+ npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate unsafe.sql
189
217
  ```
190
218
 
191
219
  Expected behavior: PG001 is reported and the CLI exits with code `1`.
@@ -216,7 +244,7 @@ npm test
216
244
  Test the rule engine:
217
245
 
218
246
  ```bash
219
- node bin/cli.js test/unsafe_migration.sql
247
+ node bin/cli.js examples/unsafe.sql
220
248
  ```
221
249
 
222
250
  Check the npm package:
@@ -225,9 +253,9 @@ Check the npm package:
225
253
  npm pack --dry-run
226
254
  ```
227
255
 
228
- ## Current release
256
+ ## CLI v2.6.0
229
257
 
230
- **v2.0.0**
258
+ Version v2.6.0 adds improved SQL positions, transaction tracking and rule catalog metadata. See [CHANGELOG.md](CHANGELOG.md).
231
259
 
232
260
  - Expanded PostgreSQL migration risk checks and framework advisories
233
261
  - PostgreSQL AST-based parsing
@@ -242,20 +270,42 @@ npm pack --dry-run
242
270
 
243
271
  ## Limitations
244
272
 
245
- `pg-safe-migrate` is a static AST-based linter, not a migration execution simulator.
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.
246
285
 
247
- It does not:
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.
248
287
 
249
- - Connect to your production database
250
- - Estimate actual lock waiting times
251
- - Validate rollback procedures
252
- - Inspect live database schemas
253
- - Guarantee zero downtime
254
- - Analyze SQL embedded inside changed JavaScript or TypeScript files
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.
255
301
 
256
302
  Some flagged operations may be acceptable under controlled conditions. Some unflagged operations may still cause downtime.
257
303
 
258
- Always consider PostgreSQL version, table size, transaction behavior, lock timeouts, long-running transactions, and application deployment sequencing.
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.
259
309
 
260
310
  ## Validation and real ORM runners
261
311
 
@@ -337,7 +387,7 @@ The directory mode processes only top-level `.sql` files (maximum 100); nested O
337
387
 
338
388
  ## Consolidated experimental development capabilities
339
389
 
340
- 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/` is a local VS Code extension prototype; team policy is a local JSON configuration, **not** a hosted team management service.
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.
341
391
 
342
392
  ## Markdown migration report (Week 2 Day 6)
343
393
 
package/SECURITY.md ADDED
@@ -0,0 +1,13 @@
1
+ # Security policy
2
+
3
+ ## Reporting
4
+
5
+ Use the repository [private vulnerability reporting page](https://github.com/subodhsingh001/pg-safe-migrate/security/advisories/new) if enabled. If unavailable, request a private reporting channel through a public issue without disclosing exploit details, credentials or customer SQL. Include affected version, environment and a minimal sanitized reproduction.
6
+
7
+ ## Safety boundaries
8
+
9
+ Static linting does not execute migrations or guarantee downtime avoidance. Optional Docker simulation executes trusted SQL in disposable containers and is not a hostile-code sandbox. Database inspection requires least-privilege credentials. Do not submit secrets or production data. The extension file size and output limits are not hard process memory limits.
10
+
11
+ ## Support
12
+
13
+ No formal support lifetime or response SLA is promised. Use the latest reviewed release and report reproducible security issues.
package/bin/cli.js CHANGED
@@ -17,7 +17,9 @@ import { toJson, toSarif, toMarkdownReport } from '../src/reports.js';
17
17
  import { inspectDatabaseUrl } from '../src/db-inspect.js';
18
18
  import { simulateSqlFile } from '../src/simulator.js';
19
19
  import { combinedAssessment } from '../src/combined.js';
20
- import { loadTeamPolicy, assessTeamPolicy } from '../src/team-policy.js';
20
+ import { loadTeamPolicy, assessTeamPolicy, assessLintPolicy } from '../src/team-policy.js';
21
+ import { loadProductionContext, productionAssessment } from '../src/production-context.js';
22
+ import { createRiskBaseline, loadRiskBaseline, compareRiskBaseline, writeRiskBaseline } from '../src/risk-baseline.js';
21
23
 
22
24
  program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk linter (not a downtime guarantee)').version(version)
23
25
  .argument('[target]', 'SQL file or migrations directory')
@@ -32,9 +34,13 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
32
34
  .option('--github', 'Emit GitHub workflow annotations')
33
35
  .option('--summary <file>', 'Write Markdown PR summary')
34
36
  .option('--risk', 'Include heuristic risk score in text output')
37
+ .option('--production-context <file>', 'Optional read-only JSON production estimates for advisory output')
35
38
  .option('--assess', 'Combine static linting with disposable PostgreSQL simulation')
36
39
  .option('--verify-sql <file>', 'Run post-migration SQL assertions (SQL errors or exceptions fail verification)')
37
40
  .option('--team-policy <file>', 'Local JSON team policy for combined assessment')
41
+ .option('--gate-policy <file>', 'Opt-in static CI gate policy (JSON); blocks matching risks')
42
+ .option('--write-risk-baseline <file>', 'Write baseline of current static findings (review before committing)')
43
+ .option('--risk-baseline <file>', 'Compare findings with a previously reviewed baseline')
38
44
  .option('--simulate <sqlFile>', 'Execute one SQL file against a disposable Docker PostgreSQL container')
39
45
  .option('--baseline <sqlFile>', 'Apply baseline SQL before simulation')
40
46
  .option('--migrations-dir <directory>', 'Simulate top-level SQL migrations in filename order')
@@ -52,6 +58,7 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
52
58
  if (!Number.isInteger(version)||version<10||version>99) throw new Error('postgres-version must be an integer >= 10');
53
59
  config.postgresVersion=version;
54
60
  }
61
+ 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');
55
62
  if (opts.assess) {
56
63
  const policy = opts.teamPolicy ? loadTeamPolicy(opts.teamPolicy) : null;
57
64
  const assessment = await combinedAssessment({ file: opts.simulate, migrationsDir: opts.migrationsDir, baseline: opts.baseline, verifySql: opts.verifySql, postgresVersion: String(opts.postgresVersion ?? '16'), config });
@@ -72,9 +79,19 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
72
79
  console.log(JSON.stringify(snapshot, null, 2));
73
80
  return;
74
81
  }
82
+ const gatePolicy = opts.gatePolicy ? loadTeamPolicy(opts.gatePolicy) : null;
83
+ if (gatePolicy?.requireSimulation) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
75
84
  const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
76
85
  const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
77
86
  const findings=await analyzeFiles(entries,config,{advisor:opts.advisor});
87
+ const production = opts.productionContext ? productionAssessment(findings, loadProductionContext(opts.productionContext)) : null;
88
+ if (opts.writeRiskBaseline && opts.riskBaseline) throw new Error('Cannot combine --write-risk-baseline and --risk-baseline');
89
+ 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;
91
+ // In baseline mode, only newly introduced findings are subject to the opt-in gate.
92
+ 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));
78
95
  if (opts.github) process.stdout.write(toGitHubAnnotations(findings));
79
96
  if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length));}
80
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}):[
@@ -82,9 +99,14 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
82
99
  ...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(findings))}`]:[]),
83
100
  `Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
84
101
  ].join('\n');
85
- if(opts.output) {fs.mkdirSync(path.dirname(path.resolve(opts.output)),{recursive:true});fs.writeFileSync(opts.output,report+'\n');}
86
- else console.log(opts.format==='text'?(findings.length?chalk.yellow(report):chalk.green(report)):report);
87
- process.exitCode=opts.failOn==='warning'?Number(findings.length>0):opts.failOn==='error'?Number(findings.some(f=>f.severity==='error')):0;
102
+ 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;
103
+ if(opts.output) {fs.mkdirSync(path.dirname(path.resolve(opts.output)),{recursive:true});fs.writeFileSync(opts.output,gateReport+'\n');}
104
+ else console.log(opts.format==='text'?(findings.length?chalk.yellow(gateReport):chalk.green(gateReport)):gateReport);
105
+ 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
+ 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.`);
108
+ if (gate) console.error(`[PG Safe Migrate gate] ${gate.passed ? 'PASS' : 'BLOCK'} (${gate.name})${gate.reasons.length ? ': '+gate.reasons.join('; ') : ''}. ${gate.note}`);
109
+ process.exitCode=(gate && !gate.passed) || (opts.failOn==='warning' && gateFindings.length>0) || (opts.failOn==='error' && gateFindings.some(f=>f.severity==='error')) ? 1 : 0;
88
110
  }catch(e){console.error(`Error: ${e.message}`);process.exitCode=2;}
89
111
  });
90
112
  program.parse();
package/docs/RULES.md ADDED
@@ -0,0 +1,31 @@
1
+ # Rule reference (development branch)
2
+
3
+ 23 catalog identifiers, including legacy PG013; PG009 and PG018 are unused. PG013 is suppressed when PG025 is emitted. PG019 and PG020 require a target version below 15; PG014 targets PostgreSQL 10. Defaults below describe CLI reporting, not raw engine metadata. Catalog `defaultSeverity` preserves raw rule metadata; `defaultCliSeverity` describes default CLI reporting. PG024 and PG025 are raw warnings but CLI errors by default.
4
+
5
+ | ID | Diagnostic | Default | Guidance |
6
+ |---|---|---|---|
7
+ | PG001 | Non-concurrent index creation | error | Use CREATE INDEX CONCURRENTLY outside a transaction. |
8
+ | PG002 | Dropping a column | error | Deprecate consumers before removing the column. |
9
+ | PG003 | Changing a column type | error | Check binary compatibility; consider expand/backfill/contract. |
10
+ | PG004 | Adding NOT NULL column without default | error | Add nullable, backfill, then enforce NOT NULL. |
11
+ | PG005 | Adding validated foreign key | error | Add NOT VALID then VALIDATE CONSTRAINT separately. |
12
+ | PG006 | Renaming an object | error | Use an expand/contract deployment. |
13
+ | PG007 | Dropping index without CONCURRENTLY | error | Use DROP INDEX CONCURRENTLY where supported. |
14
+ | PG008 | Concurrent index operation inside transaction | error | Run outside BEGIN/COMMIT. |
15
+ | PG010 | Adding UNIQUE constraint | error | Consider a concurrent unique index and attach it where applicable. |
16
+ | PG011 | Dropping a table | error | Verify retention and application dependencies. |
17
+ | PG012 | Adding validated CHECK constraint | error | Add NOT VALID and validate separately. |
18
+ | PG013 | Legacy SET NOT NULL diagnostic (superseded by PG025) | error | Validate an equivalent CHECK constraint first. |
19
+ | PG014 | Adding column with default on PostgreSQL 10 | error | Use controlled backfill or evaluate upgrading PostgreSQL. |
20
+ | PG015 | Prisma concurrent index migration | warning | Use a separately managed nontransactional migration. |
21
+ | PG016 | Drizzle concurrent index migration | warning | Use a separately managed nontransactional migration. |
22
+ | PG017 | Potential cross-file dependency or Flyway transaction advisory | warning | Review migration order; this is a heuristic. |
23
+ | PG019 | MERGE requires PostgreSQL 15+ | error | Use a compatible INSERT ... ON CONFLICT pattern where applicable. |
24
+ | PG020 | UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+ | error | Use a version-compatible uniqueness strategy. |
25
+ | PG021 | Volatile default may rewrite table | error | Add column, backfill in batches, then set default. |
26
+ | PG022 | SET LOGGED rewrites table | error | Schedule controlled maintenance and evaluate alternatives. |
27
+ | PG023 | TRUNCATE removes table rows | error | Confirm retention, backups and downstream dependencies. |
28
+ | PG024 | Dropping a constraint | error | Review dependent queries and data-integrity requirements. |
29
+ | PG025 | SET NOT NULL may scan table | error | Backfill and validate a CHECK constraint first where appropriate. |
30
+
31
+ PG017 also covers Flyway nontransactional execution advice. Rules are configurable using `rules` with `off`, `warning`, or `error`. Static findings are not a downtime guarantee.
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "tool": "pg-safe-migrate",
4
+ "fingerprints": [
5
+ "ee03806a2ea992dae01c0042f8e7498f84ca5fe65f54d7b2dd58177e49cc565c"
6
+ ]
7
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "pull-request-static-gate",
3
+ "blockedRules": ["PG001", "PG002", "PG003"],
4
+ "maxWarnings": 5,
5
+ "maxRiskScore": 60
6
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "tables": [
4
+ { "schema": "public", "table": "users", "estimatedRows": 1200000, "bytes": 2147483648, "writeQueriesPerSecond": 25 }
5
+ ],
6
+ "lockTimeoutMs": 2000,
7
+ "statementTimeoutMs": 300000
8
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@subodh001/pg-safe-migrate",
3
- "version": "2.4.0",
4
- "description": "PostgreSQL AST migration risk linter for Prisma, Drizzle and SQL",
3
+ "version": "2.6.0",
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": {
7
7
  "pg-safe-migrate": "bin/cli.js"
@@ -22,7 +22,15 @@
22
22
  "prisma",
23
23
  "drizzle",
24
24
  "zero-downtime",
25
- "ast"
25
+ "ast",
26
+ "database-migration",
27
+ "migration-linter",
28
+ "schema-migration",
29
+ "migration-safety",
30
+ "database-safety",
31
+ "postgres-locks",
32
+ "flyway",
33
+ "sarif"
26
34
  ],
27
35
  "license": "MIT",
28
36
  "dependencies": {
@@ -44,7 +52,11 @@
44
52
  "scripts/orm-runner/package.json",
45
53
  "scripts/orm-runner/package-lock.json",
46
54
  "scripts/orm-runner/README.md",
47
- "ALL-MILESTONES-TESTING.md"
55
+ "ALL-MILESTONES-TESTING.md",
56
+ "CHANGELOG.md",
57
+ "SECURITY.md",
58
+ "CONTRIBUTING.md",
59
+ "docs/RULES.md"
48
60
  ],
49
61
  "repository": {
50
62
  "type": "git",
package/src/analysis.js CHANGED
@@ -1,4 +1,3 @@
1
-
2
1
  import { parseSqlFile } from './parser.js';
3
2
  import { lintStatements } from './engine.js';
4
3
  import { advise } from './advisor.js';
@@ -26,6 +25,46 @@ export function position(sql, offset = 0) {
26
25
  };
27
26
  }
28
27
 
28
+
29
+ function createPositionTracker(sql) {
30
+ const source = String(sql ?? '');
31
+
32
+ let cursor = 0;
33
+ let line = 1;
34
+ let lineStart = 0;
35
+
36
+ return function locate(offset = 0) {
37
+ const numericOffset = Number(offset);
38
+
39
+ const safeOffset = Number.isFinite(numericOffset)
40
+ ? Math.min(
41
+ source.length,
42
+ Math.max(0, Math.floor(numericOffset))
43
+ )
44
+ : 0;
45
+
46
+ // Preserve correctness if offsets arrive out of order.
47
+ if (safeOffset < cursor) {
48
+ return position(source, safeOffset);
49
+ }
50
+
51
+ while (cursor < safeOffset) {
52
+ if (source.charCodeAt(cursor) === 10) {
53
+ line++;
54
+ lineStart = cursor + 1;
55
+ }
56
+
57
+ cursor++;
58
+ }
59
+
60
+ return {
61
+ line,
62
+ column: safeOffset - lineStart + 1
63
+ };
64
+ };
65
+ }
66
+
67
+
29
68
  export function frameworkFor(file) {
30
69
  const p = file.replaceAll('\\', '/').toLowerCase();
31
70
 
@@ -57,7 +96,6 @@ function txType(stmt) {
57
96
  if ([
58
97
  'TRANS_STMT_COMMIT',
59
98
  'TRANS_STMT_ROLLBACK',
60
- 'TRANS_STMT_ROLLBACK_TO',
61
99
  'TRANS_STMT_PREPARE'
62
100
  ].includes(kind)) {
63
101
  return 'end';
@@ -185,11 +223,12 @@ export async function analyzeFiles(
185
223
  });
186
224
 
187
225
  const framework = frameworkFor(file);
226
+ const locate = createPositionTracker(sql);
188
227
 
189
228
  let inTransaction = false;
190
229
 
191
230
  for (const { stmt, offset } of parsed) {
192
- const loc = position(sql, offset);
231
+ const loc = locate(offset);
193
232
  const transaction = txType(stmt);
194
233
 
195
234
  // Track explicit transaction boundaries.
@@ -339,7 +378,7 @@ export async function analyzeFiles(
339
378
 
340
379
  // Close the explicit transaction after processing.
341
380
  if (transaction === 'end') {
342
- inTransaction = false;
381
+ inTransaction = Boolean(stmt.TransactionStmt?.chain);
343
382
  }
344
383
  }
345
384
  }
package/src/locks.js CHANGED
@@ -1,18 +1,134 @@
1
- // Conservative PostgreSQL table-lock inventory. These are planning hints, not
2
- // predictions of wait time, lock duration, or production downtime.
1
+
2
+ // PostgreSQL table-lock planning hints.
3
+ // These are not predictions of wait time, duration, or downtime.
4
+
3
5
  function assessment(mode, impact, note, confidence = 'heuristic') {
4
6
  return { mode, confidence, impact, note };
5
7
  }
6
8
 
9
+ function alterTableLock(alter) {
10
+ const commands = (alter.cmds || [])
11
+ .map(wrapper => wrapper.AlterTableCmd)
12
+ .filter(Boolean);
13
+
14
+ // A statement may contain multiple subcommands.
15
+ // Do not classify a mixed statement using only its weakest lock.
16
+ if (commands.length === 0) {
17
+ return assessment(
18
+ 'ACCESS EXCLUSIVE',
19
+ 'reads-and-writes',
20
+ 'ALTER TABLE lock requirements depend on its subcommands.'
21
+ );
22
+ }
23
+
24
+ const modes = commands.map(cmd => {
25
+ if (
26
+ cmd.subtype === 'AT_AddConstraint' &&
27
+ cmd.def?.Constraint?.contype === 'CONSTR_FOREIGN'
28
+ ) {
29
+ return 'SHARE ROW EXCLUSIVE';
30
+ }
31
+
32
+ if (cmd.subtype === 'AT_ValidateConstraint') {
33
+ return 'SHARE UPDATE EXCLUSIVE';
34
+ }
35
+
36
+ return 'ACCESS EXCLUSIVE';
37
+ });
38
+
39
+ if (modes.every(mode => mode === 'SHARE ROW EXCLUSIVE')) {
40
+ return assessment(
41
+ 'SHARE ROW EXCLUSIVE',
42
+ 'writes',
43
+ 'ADD FOREIGN KEY acquires SHARE ROW EXCLUSIVE on both referencing and referenced tables. NOT VALID avoids the initial scan but not the lock.',
44
+ 'documented'
45
+ );
46
+ }
47
+
48
+ if (modes.every(mode => mode === 'SHARE UPDATE EXCLUSIVE')) {
49
+ return assessment(
50
+ 'SHARE UPDATE EXCLUSIVE',
51
+ 'ddl-and-maintenance',
52
+ 'VALIDATE CONSTRAINT generally uses SHARE UPDATE EXCLUSIVE on the altered table. Foreign-key validation can also lock the referenced table.',
53
+ 'documented'
54
+ );
55
+ }
56
+
57
+ return assessment(
58
+ 'ACCESS EXCLUSIVE',
59
+ 'reads-and-writes',
60
+ 'ALTER TABLE contains a subcommand requiring ACCESS EXCLUSIVE, or a subcommand whose lock has not been specifically classified.'
61
+ );
62
+ }
63
+
7
64
  export function lockFor(stmt) {
8
- if (stmt.TruncateStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'TRUNCATE acquires ACCESS EXCLUSIVE on affected tables and can block readers and writers.', 'documented');
9
- if (stmt.AlterTableStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'ALTER TABLE generally acquires ACCESS EXCLUSIVE; some subcommands use weaker locks. Check the specific operation.');
10
- if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'DROP TABLE requires ACCESS EXCLUSIVE on the target table.', 'documented');
11
- if (stmt.RenameStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'Rename operations can require strong locks; verify the specific object and operation.');
12
- if (stmt.IndexStmt) return stmt.IndexStmt.concurrent
13
- ? assessment('SHARE UPDATE EXCLUSIVE', 'ddl-and-maintenance', 'CREATE INDEX CONCURRENTLY permits ordinary writes but can wait for transactions and conflicts with some maintenance.', 'documented')
14
- : assessment('SHARE', 'writes', 'CREATE INDEX without CONCURRENTLY can block writes while the index is built.', 'documented');
15
- if (stmt.VacuumStmt) return assessment('SHARE UPDATE EXCLUSIVE', 'ddl-and-maintenance', 'Ordinary VACUUM uses SHARE UPDATE EXCLUSIVE; VACUUM FULL uses ACCESS EXCLUSIVE. Verify the options.');
16
- if (stmt.UpdateStmt || stmt.DeleteStmt || stmt.InsertStmt) return assessment('ROW EXCLUSIVE', 'conflicting-writers-and-ddl', 'DML acquires ROW EXCLUSIVE table locks; row-level contention and execution time are not assessed.', 'documented');
17
- return assessment('unknown', 'unknown', 'Lock mode not classified; do not assume this operation is lock-free.', 'unknown');
65
+ if (stmt.TruncateStmt) {
66
+ return assessment(
67
+ 'ACCESS EXCLUSIVE',
68
+ 'reads-and-writes',
69
+ 'TRUNCATE acquires ACCESS EXCLUSIVE on affected tables and can block readers and writers.',
70
+ 'documented'
71
+ );
72
+ }
73
+
74
+ if (stmt.AlterTableStmt) {
75
+ return alterTableLock(stmt.AlterTableStmt);
76
+ }
77
+
78
+ if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') {
79
+ return assessment(
80
+ 'ACCESS EXCLUSIVE',
81
+ 'reads-and-writes',
82
+ 'DROP TABLE requires ACCESS EXCLUSIVE on the target table.',
83
+ 'documented'
84
+ );
85
+ }
86
+
87
+ if (stmt.RenameStmt) {
88
+ return assessment(
89
+ 'ACCESS EXCLUSIVE',
90
+ 'reads-and-writes',
91
+ 'Rename operations can require strong locks; verify the specific object and operation.'
92
+ );
93
+ }
94
+
95
+ if (stmt.IndexStmt) {
96
+ return stmt.IndexStmt.concurrent
97
+ ? assessment(
98
+ 'SHARE UPDATE EXCLUSIVE',
99
+ 'ddl-and-maintenance',
100
+ 'CREATE INDEX CONCURRENTLY permits ordinary writes but can wait for transactions and conflict with some maintenance.',
101
+ 'documented'
102
+ )
103
+ : assessment(
104
+ 'SHARE',
105
+ 'writes',
106
+ 'CREATE INDEX without CONCURRENTLY can block writes while the index is built.',
107
+ 'documented'
108
+ );
109
+ }
110
+
111
+ if (stmt.VacuumStmt) {
112
+ return assessment(
113
+ 'SHARE UPDATE EXCLUSIVE',
114
+ 'ddl-and-maintenance',
115
+ 'Ordinary VACUUM uses SHARE UPDATE EXCLUSIVE; VACUUM FULL uses ACCESS EXCLUSIVE. Verify the options.'
116
+ );
117
+ }
118
+
119
+ if (stmt.UpdateStmt || stmt.DeleteStmt || stmt.InsertStmt) {
120
+ return assessment(
121
+ 'ROW EXCLUSIVE',
122
+ 'conflicting-writers-and-ddl',
123
+ 'DML acquires ROW EXCLUSIVE table locks; row-level contention and execution time are not assessed.',
124
+ 'documented'
125
+ );
126
+ }
127
+
128
+ return assessment(
129
+ 'unknown',
130
+ 'unknown',
131
+ 'Lock mode not classified; do not assume this operation is lock-free.',
132
+ 'unknown'
133
+ );
18
134
  }
package/src/parser.js CHANGED
@@ -1,4 +1,3 @@
1
-
2
1
  import pgQuery from 'libpg-query';
3
2
 
4
3
  export async function parseSqlFile(sqlContent, options = {}) {
@@ -16,6 +15,22 @@ export async function parseSqlFile(sqlContent, options = {}) {
16
15
 
17
16
  const source = String(sqlContent);
18
17
 
18
+ // Convert ordered PostgreSQL UTF-8 byte locations to UTF-16 offsets.
19
+ const byteLength = Buffer.byteLength(source);
20
+ let byteCursor = 0;
21
+ let charCursor = 0;
22
+ function locateByte(target) {
23
+ if (target < byteCursor) { byteCursor = 0; charCursor = 0; }
24
+ while (byteCursor < target && charCursor < source.length) {
25
+ const cp = source.codePointAt(charCursor);
26
+ const width = cp <= 0x7f ? 1 : cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4;
27
+ if (byteCursor + width > target) break;
28
+ byteCursor += width;
29
+ charCursor += cp > 0xffff ? 2 : 1;
30
+ }
31
+ return charCursor;
32
+ }
33
+
19
34
  return statements.map(s => {
20
35
  let offset =
21
36
  typeof s.stmt_location === 'number'
@@ -24,17 +39,38 @@ export async function parseSqlFile(sqlContent, options = {}) {
24
39
 
25
40
  offset = Math.max(
26
41
  0,
27
- Math.min(offset, source.length)
42
+ Math.min(offset, byteLength)
28
43
  );
29
44
 
30
- // PostgreSQL may report the beginning of the
31
- // statement span before leading whitespace.
32
- // Advance to the first non-whitespace character.
33
- while (
34
- offset < source.length &&
35
- /\s/.test(source[offset])
36
- ) {
37
- offset++;
45
+ offset = locateByte(offset);
46
+
47
+ // Skip only leading SQL trivia, never statement contents.
48
+ while (offset < source.length) {
49
+ if (/[ \t\r\n\f\v]/.test(source[offset])) {
50
+ offset++;
51
+ } else if (source.startsWith('--', offset)) {
52
+ offset += 2;
53
+ while (offset < source.length &&
54
+ source[offset] !== '\n' && source[offset] !== '\r') {
55
+ offset++;
56
+ }
57
+ } else if (source.startsWith('/*', offset)) {
58
+ offset += 2;
59
+ let depth = 1;
60
+ while (offset < source.length && depth > 0) {
61
+ if (source.startsWith('/*', offset)) {
62
+ depth++;
63
+ offset += 2;
64
+ } else if (source.startsWith('*/', offset)) {
65
+ depth--;
66
+ offset += 2;
67
+ } else {
68
+ offset++;
69
+ }
70
+ }
71
+ } else {
72
+ break;
73
+ }
38
74
  }
39
75
 
40
76
  return {
@@ -0,0 +1,78 @@
1
+ import fs from 'node:fs';
2
+
3
+ const MAX_BYTES = 1024 * 1024;
4
+ const MAX_TABLES = 200;
5
+ const MAX_ROWS = 1e15;
6
+ const MAX_TABLE_BYTES = 1e18;
7
+ const MAX_MS = 3600000;
8
+ const allowed = new Set(['schema', 'table', 'estimatedRows', 'bytes', 'writeQueriesPerSecond']);
9
+
10
+ function plainObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
11
+ function boundedNumber(value, name, max) {
12
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > max) throw new Error(`${name} must be a finite non-negative number <= ${max}`);
13
+ return value;
14
+ }
15
+ export function validateProductionContext(input) {
16
+ if (!plainObject(input) || input.schemaVersion !== 1 || !Array.isArray(input.tables)) throw new Error('production context requires schemaVersion 1 and a tables array');
17
+ if (input.tables.length > MAX_TABLES) throw new Error(`production context supports at most ${MAX_TABLES} tables`);
18
+ for (const key of Object.keys(input)) if (!['schemaVersion', 'tables', 'lockTimeoutMs', 'statementTimeoutMs'].includes(key)) throw new Error(`Unknown production context field: ${key}`);
19
+ const tables = [];
20
+ const seen = new Set();
21
+ for (const row of input.tables) {
22
+ if (!plainObject(row)) throw new Error('production context table entry must be an object');
23
+ for (const key of Object.keys(row)) if (!allowed.has(key)) throw new Error(`Unknown production table field: ${key}`);
24
+ if (typeof row.schema !== 'string' || !/^[a-zA-Z_][\w$]{0,62}$/.test(row.schema) || typeof row.table !== 'string' || !/^[a-zA-Z_][\w$]{0,62}$/.test(row.table)) throw new Error('production table schema and table must be simple PostgreSQL identifiers');
25
+ const id = `${row.schema.toLowerCase()}.${row.table.toLowerCase()}`;
26
+ if (seen.has(id)) throw new Error(`Duplicate production table: ${id}`);
27
+ seen.add(id);
28
+ const entry = { schema: row.schema, table: row.table };
29
+ if (row.estimatedRows !== undefined) entry.estimatedRows = boundedNumber(row.estimatedRows, 'estimatedRows', MAX_ROWS);
30
+ if (row.bytes !== undefined) entry.bytes = boundedNumber(row.bytes, 'bytes', MAX_TABLE_BYTES);
31
+ if (row.writeQueriesPerSecond !== undefined) entry.writeQueriesPerSecond = boundedNumber(row.writeQueriesPerSecond, 'writeQueriesPerSecond', 1e7);
32
+ tables.push(entry);
33
+ }
34
+ const result = { schemaVersion: 1, tables };
35
+ if (input.lockTimeoutMs !== undefined) result.lockTimeoutMs = boundedNumber(input.lockTimeoutMs, 'lockTimeoutMs', MAX_MS);
36
+ if (input.statementTimeoutMs !== undefined) result.statementTimeoutMs = boundedNumber(input.statementTimeoutMs, 'statementTimeoutMs', MAX_MS);
37
+ return result;
38
+ }
39
+ export function loadProductionContext(file) {
40
+ const stat = fs.statSync(file);
41
+ if (stat.size > MAX_BYTES) throw new Error('production context file exceeds 1 MiB');
42
+ let parsed;
43
+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { throw new Error('Invalid production context JSON'); }
44
+ return validateProductionContext(parsed);
45
+ }
46
+ function tableMention(message) {
47
+ const quoted = String(message).match(/(?:on|table)\s+["']?([a-zA-Z_][\w$]*(?:\.[a-zA-Z_][\w$]*)?)["']?/i);
48
+ return quoted?.[1]?.toLowerCase() || null;
49
+ }
50
+ export function productionAssessment(findings, context) {
51
+ const tables = context.tables;
52
+ const assessments = findings.map(finding => {
53
+ const mention = tableMention(finding.message);
54
+ const matches = mention ? tables.filter(t => `${t.schema}.${t.table}`.toLowerCase() === mention || t.table.toLowerCase() === mention) : [];
55
+ const table = matches.length === 1 ? matches[0] : null;
56
+ const mode = finding.lock?.mode || 'unknown';
57
+ const writesBlocked = ['ACCESS EXCLUSIVE', 'EXCLUSIVE', 'SHARE', 'SHARE ROW EXCLUSIVE'].includes(mode);
58
+ const readsBlocked = mode === 'ACCESS EXCLUSIVE';
59
+ const large = Boolean(table && ((table.estimatedRows ?? 0) >= 1000000 || (table.bytes ?? 0) >= 1073741824));
60
+ const busy = Boolean(table && (table.writeQueriesPerSecond ?? 0) >= 10);
61
+ const factors = [];
62
+ if (mode === 'unknown') factors.push('Lock behavior is unknown; manual review required');
63
+ else factors.push(`Classified lock: ${mode}${readsBlocked ? ' (may block reads and writes)' : writesBlocked ? ' (may block writes)' : ''}`);
64
+ if (large) factors.push('Supplied table estimate is large (>= 1M rows or >= 1 GiB)');
65
+ if (busy) factors.push('Supplied write rate is >= 10 queries/second');
66
+ if (!table) factors.push(matches.length > 1 ? 'Ambiguous table match; production statistics not applied' : 'No matching production table statistics supplied');
67
+ const guidance = [];
68
+ if (finding.ruleId === 'PG001') guidance.push('Consider CREATE INDEX CONCURRENTLY outside a transaction; check framework transaction settings and monitor index progress');
69
+ else if (['PG002', 'PG003', 'PG024', 'PG025'].includes(finding.ruleId)) guidance.push('Consider an expand/backfill/validate/contract rollout with application compatibility checks');
70
+ else if (finding.ruleId === 'PG023') guidance.push('Review data-loss consequences and schedule TRUNCATE with an explicit maintenance plan');
71
+ else guidance.push('Review lock scope, expected execution time, and rollback strategy before deployment');
72
+ if (writesBlocked || readsBlocked) guidance.push('Use a tested lock_timeout and monitor blocking sessions; a timeout does not eliminate lock risk');
73
+ if (context.lockTimeoutMs !== undefined) factors.push(`Provided lock_timeout: ${context.lockTimeoutMs} ms (not verified against server)`);
74
+ if (context.statementTimeoutMs !== undefined) factors.push(`Provided statement_timeout: ${context.statementTimeoutMs} ms (not verified against server)`);
75
+ return { ruleId: finding.ruleId, file: finding.file, line: finding.line, column: finding.column, table: table ? `${table.schema}.${table.table}` : null, lockMode: mode, potentialImpact: readsBlocked ? 'reads-and-writes' : writesBlocked ? 'writes' : 'review-required', attention: large && (writesBlocked || readsBlocked) ? 'elevated' : 'review', factors, guidance };
76
+ });
77
+ return { source: 'user-supplied estimates (not a live database inspection)', confidence: 'limited', assessments, limitations: ['Table statistics and workload rates may be stale or inaccurate', 'SQL table matching is heuristic; schema ambiguity prevents applying estimates', 'No measured lock waits, execution duration, or downtime prediction', 'Existing policy gate decisions are unchanged'] };
78
+ }
@@ -0,0 +1,54 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+
5
+ const sha = value => crypto.createHash('sha256').update(value).digest('hex');
6
+ const normalizedPath = file => String(file).replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/+/g, '/');
7
+ const normalizedSql = sql => String(sql).replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').trim().toLowerCase();
8
+
9
+ // Statement boundaries are derived from the parser's starting positions when available.
10
+ // A conservative text fallback is used for baseline identity; it is not a SQL parser.
11
+ function statementAt(sql, line) {
12
+ const lines = String(sql).split(/\r?\n/);
13
+ const start = Math.max(0, Math.min(lines.length - 1, Number(line || 1) - 1));
14
+ let begin = start;
15
+ while (begin > 0 && !lines[begin - 1].includes(';')) begin--;
16
+ let end = start;
17
+ while (end < lines.length - 1 && !lines[end].includes(';')) end++;
18
+ return normalizedSql(lines.slice(begin, end + 1).join('\n'));
19
+ }
20
+
21
+ export function fingerprint(finding, sqlByFile = new Map()) {
22
+ const file = normalizedPath(finding.file);
23
+ const sql = sqlByFile.get(file);
24
+ const identity = sql === undefined ? String(finding.message || '') : statementAt(sql, finding.line);
25
+ return sha(JSON.stringify([file, finding.ruleId, finding.severity, identity]));
26
+ }
27
+ export function createRiskBaseline(findings, entries) {
28
+ const sqlByFile = new Map(entries.map(e => [normalizedPath(e.file), e.sql]));
29
+ const fingerprints = findings.map(f => fingerprint(f, sqlByFile)).sort();
30
+ return { schemaVersion: 1, tool: 'pg-safe-migrate', fingerprints };
31
+ }
32
+ export function loadRiskBaseline(filename) {
33
+ const obj = JSON.parse(fs.readFileSync(filename, 'utf8'));
34
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj) || obj.schemaVersion !== 1 || obj.tool !== 'pg-safe-migrate' || !Array.isArray(obj.fingerprints) || obj.fingerprints.length > 100000 || obj.fingerprints.some(x => typeof x !== 'string' || !/^[a-f0-9]{64}$/.test(x))) throw new Error('Invalid risk baseline (expected schemaVersion 1 and SHA-256 fingerprints)');
35
+ return obj;
36
+ }
37
+ export function compareRiskBaseline(findings, entries, baseline) {
38
+ const sqlByFile = new Map(entries.map(e => [normalizedPath(e.file), e.sql]));
39
+ const previous = new Map();
40
+ for (const id of baseline.fingerprints) previous.set(id, (previous.get(id) || 0) + 1);
41
+ const newFindings = [], existingFindings = [];
42
+ for (const f of findings) {
43
+ const id = fingerprint(f, sqlByFile);
44
+ if ((previous.get(id) || 0) > 0) { existingFindings.push(f); previous.set(id, previous.get(id) - 1); }
45
+ else newFindings.push(f);
46
+ }
47
+ const resolved = [...previous.values()].reduce((a,b)=>a+b,0);
48
+ return { newFindings, existingFindings, resolvedCount: resolved, newCount: newFindings.length, existingCount: existingFindings.length };
49
+ }
50
+ export function writeRiskBaseline(filename, baseline) {
51
+ const dest = path.resolve(filename);
52
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
53
+ fs.writeFileSync(dest, JSON.stringify(baseline, null, 2) + '\n', { flag: 'w' });
54
+ }
@@ -8,10 +8,14 @@ const definitions = [
8
8
  ['PG006','Renaming an object','compatibility','ERROR',null,'Use an expand/contract deployment.'],
9
9
  ['PG007','Dropping index without CONCURRENTLY','locking','ERROR',null,'Use DROP INDEX CONCURRENTLY where supported.'],
10
10
  ['PG008','Concurrent index operation inside transaction','compatibility','ERROR',null,'Run outside BEGIN/COMMIT.'],
11
+ ['PG010','Adding UNIQUE constraint','locking','ERROR',null,'Consider a concurrent unique index and attach it where applicable.'],
11
12
  ['PG011','Dropping a table','data-loss','ERROR',null,'Verify retention and application dependencies.'],
13
+ ['PG012','Adding validated CHECK constraint','constraint','ERROR',null,'Add NOT VALID and validate separately.'],
14
+ ['PG013','Legacy SET NOT NULL diagnostic (superseded by PG025)','constraint','ERROR',null,'Validate an equivalent CHECK constraint first.'],
15
+ ['PG014','Adding column with default on PostgreSQL 10','rewrite','ERROR',null,'Use controlled backfill or evaluate upgrading PostgreSQL.'],
12
16
  ['PG015','Prisma concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
13
17
  ['PG016','Drizzle concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
14
- ['PG017','Potential cross-file dependency','dependency','WARNING',null,'Review migration order; this is a heuristic.'],
18
+ ['PG017','Potential cross-file dependency or Flyway transaction advisory','dependency','WARNING',null,'Review migration order; this is a heuristic.'],
15
19
  ['PG019','MERGE requires PostgreSQL 15+','version','ERROR',15,'Use a compatible INSERT ... ON CONFLICT pattern where applicable.'],
16
20
  ['PG020','UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+','version','ERROR',15,'Use a version-compatible uniqueness strategy.'],
17
21
  ['PG021','Volatile default may rewrite table','rewrite','ERROR',null,'Add column, backfill in batches, then set default.'],
@@ -21,7 +25,7 @@ const definitions = [
21
25
  ['PG025','SET NOT NULL may scan table','constraint','WARNING',null,'Backfill and validate a CHECK constraint first where appropriate.']
22
26
  ];
23
27
 
24
- export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,minPostgresVersion,recommendation})));
28
+ export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,defaultCliSeverity: ['PG024','PG025'].includes(id) ? 'ERROR' : defaultSeverity,minPostgresVersion,recommendation})));
25
29
 
26
30
  export function getRule(id) {
27
31
  return RULE_CATALOG.find(rule => rule.id === String(id).toUpperCase()) ?? null;
@@ -1,13 +1,16 @@
1
1
  import fs from 'node:fs';
2
+ import { getRule } from './rules/ruleCatalog.js';
2
3
 
3
4
  export function loadTeamPolicy(file) {
4
5
  const policy = JSON.parse(fs.readFileSync(file, 'utf8'));
5
6
  if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new Error('Team policy must be a JSON object');
6
7
  const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation'];
7
8
  for (const key of Object.keys(policy)) if (!allowed.includes(key)) throw new Error(`Unknown team policy key: ${key}`);
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');
8
10
  if (policy.maxRiskScore !== undefined && (!Number.isInteger(policy.maxRiskScore) || policy.maxRiskScore < 0 || policy.maxRiskScore > 100)) throw new Error('maxRiskScore must be 0-100');
9
11
  if (policy.maxWarnings !== undefined && (!Number.isInteger(policy.maxWarnings) || policy.maxWarnings < 0)) throw new Error('maxWarnings must be >= 0');
10
- if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => !/^PG\d{3}$/.test(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' || !getRule(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
13
+ if (policy.blockedRules && new Set(policy.blockedRules).size !== policy.blockedRules.length) throw new Error('blockedRules must not contain duplicates');
11
14
  if (policy.requireSimulation !== undefined && typeof policy.requireSimulation !== 'boolean') throw new Error('requireSimulation must be boolean');
12
15
  return policy;
13
16
  }
@@ -21,3 +24,25 @@ export function assessTeamPolicy(report, policy) {
21
24
  for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
22
25
  return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)] };
23
26
  }
27
+
28
+ // Week 3: static-only CI gate. The existing --assess policy behavior is unchanged.
29
+ export function validateLintPolicy(policy) {
30
+ if (policy.requireSimulation === true) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
31
+ return policy;
32
+ }
33
+
34
+ export function assessLintPolicy(findings, policy, risk = {}) {
35
+ validateLintPolicy(policy);
36
+ // A score is only a heuristic derived from the configured lint findings.
37
+ const reasons = [];
38
+ const warningCount = findings.filter(f => f.severity === 'warning').length;
39
+ if (policy.maxWarnings !== undefined && warningCount > policy.maxWarnings) reasons.push(`Warnings ${warningCount} exceed ${policy.maxWarnings}`);
40
+ if (policy.maxRiskScore !== undefined) {
41
+ const severityScore = Math.min(100, findings.reduce((n, f) => n + (f.severity === 'error' ? 20 : f.severity === 'warning' ? 5 : 0), 0));
42
+ // Actual heuristic is calculated by the caller and passed separately when available.
43
+ const score = risk.score ?? severityScore;
44
+ if (score > policy.maxRiskScore) reasons.push(`Heuristic risk score ${score} exceeds ${policy.maxRiskScore}`);
45
+ }
46
+ for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
47
+ 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
+ }