@subodh001/pg-safe-migrate 1.1.2 → 2.2.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.
@@ -0,0 +1,41 @@
1
+ # Consolidated development build — testing guide
2
+
3
+ This is a development candidate, **not** a verified production release. Package version stays at 2.1.0.
4
+
5
+ ## Combined report (Windows CMD, Docker running)
6
+
7
+ ```cmd
8
+ npm ci
9
+ npm test
10
+ node bin/cli.js --assess --migrations-dir examples/migrations --baseline examples/baseline.sql --verify-sql examples/verify.sql --postgres-version 16 --team-policy examples/team-policy.json --output assessment.json
11
+ ```
12
+
13
+ The `assessment.json` contains execution steps, static lint findings, heuristic locks, advice, risk scoring, and local team-policy outcome. A migration that executes successfully may still fail static lint or policy. `--verify-sql` runs after migrations; write assertions that raise PostgreSQL errors on unexpected state.
14
+
15
+ ## PostgreSQL 14–18 matrix
16
+
17
+ ```cmd
18
+ node scripts/test-pg-matrix.cjs
19
+ ```
20
+
21
+ This starts five separate disposable Docker containers in sequence. Requires local Docker images or permission to pull them. A passing matrix on one computer does not guarantee performance or production safety on all server versions.
22
+
23
+ ## Failure case
24
+
25
+ Create a migration with invalid SQL or a post-migration assertion that raises an exception. Expect nonzero exit status and a failed `execution` stage. Docker container cleanup should be verified with `docker ps -a --filter name=pg-safe-sim`.
26
+
27
+ ## VS Code extension (local development)
28
+
29
+ The `vscode-extension/` folder is an **unpackaged local prototype**. Open it as a VS Code extension development project and run an Extension Development Host; open the pg-safe-migrate project folder in that host, open a `.sql` file, and run **PG Safe Migrate: Lint Current SQL File** from the Command Palette. It calls the project's local CLI and shows diagnostics. It does not yet include VSIX packaging, automated extension-host tests, marketplace publication, or remote CLI discovery.
30
+
31
+ ## Team policies
32
+
33
+ `examples/team-policy.json` shows supported local constraints: `maxRiskScore`, `maxWarnings`, `blockedRules`, `requireSimulation`. These are file-based policies, not centralized administration, authentication, dashboards, or multi-tenant reporting.
34
+
35
+ ## Verification status
36
+
37
+ - 10 simulator/policy focused tests passed in the build environment.
38
+ - JavaScript syntax and npm pack dry run passed.
39
+ - Full suite could not run here because `libpg-query` tarball was unavailable offline.
40
+ - PostgreSQL 14–18 Docker matrix not executed here.
41
+ - VS Code extension host not executed here.
package/README.md CHANGED
@@ -1,66 +1,340 @@
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.
4
+
1
5
  # pg-safe-migrate
2
6
 
3
- An AST-based PostgreSQL migration **risk** linter for Prisma, Drizzle, and raw SQL. It flags six common migration patterns that may cause blocking locks or application compatibility failures. **It does not guarantee zero downtime.**
7
+ **Catch risky PostgreSQL migrations before they reach production.**
4
8
 
5
- ## Quick start
9
+ An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, and raw SQL**.
6
10
 
7
- ```sh
8
- npx --yes --package=@subodh001/pg-safe-migrate@1.1.1 pg-safe-migrate --help
11
+ Detect risky PostgreSQL DDL patterns and provide additional framework-specific migration advisories.
12
+
13
+ **Features:** PostgreSQL AST parsing · PG001–PG017 identifiers (see rule coverage below) · Git-diff mode · JSON/SARIF · configurable severity · optional advisor · GitHub Actions
14
+
15
+ > **Important:** This tool identifies configured migration risks. It does not guarantee zero downtime.
16
+
17
+ ## Demo
18
+
19
+ See how `pg-safe-migrate` catches an unsafe PostgreSQL migration and suggests a safer alternative.
20
+
21
+ ![pg-safe-migrate CLI demonstration](assets/pg-safe-migrate-demo.gif)
22
+
23
+ ### Example
24
+
25
+ Unsafe migration:
26
+
27
+ ```sql
28
+ CREATE INDEX idx_users_email ON users(email);
29
+ ```
30
+
31
+ Detected issue:
32
+
33
+ ```text
34
+ [PG001] CREATE INDEX on "users" acquires a SHARE lock and blocks writes.
35
+
36
+ Fix: Use CREATE INDEX CONCURRENTLY and execute outside a transaction block.
37
+
38
+ Found 1 blocking migration issue(s).
39
+ ```
40
+
41
+ Safer alternative:
42
+
43
+ ```sql
44
+ CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
45
+ ```
46
+
47
+ `CREATE INDEX CONCURRENTLY` must run outside a transaction block.
48
+
49
+ ## Installation
50
+
51
+ Install as a development dependency:
52
+
53
+ ```bash
9
54
  npm install --save-dev @subodh001/pg-safe-migrate
55
+ ```
56
+
57
+ Or execute the published package without installing it in your project:
58
+
59
+ ```bash
60
+ npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
61
+ ```
62
+
63
+ ## Quick start
64
+
65
+ ### Automatically detect migrations
66
+
67
+ ```bash
68
+ npx pg-safe-migrate
69
+ ```
70
+
71
+ The CLI searches these directories:
72
+
73
+ - `prisma/migrations`
74
+ - `drizzle`
75
+ - `migrations`
76
+ - `db/migrations`
77
+
78
+ ### Prisma
79
+
80
+ ```bash
10
81
  npx pg-safe-migrate prisma/migrations
82
+ ```
83
+
84
+ ### Drizzle
85
+
86
+ ```bash
11
87
  npx pg-safe-migrate drizzle
88
+ ```
89
+
90
+ ### Raw SQL
91
+
92
+ ```bash
12
93
  npx pg-safe-migrate db/migrations
94
+ ```
95
+
96
+ ### Check a specific migration
97
+
98
+ ```bash
99
+ npx pg-safe-migrate path/to/migration.sql
100
+ ```
101
+
102
+ ### Check changed migrations only
103
+
104
+ ```bash
13
105
  npx pg-safe-migrate --changed origin/main
14
106
  ```
15
107
 
16
- The default scan searches `prisma/migrations`, `drizzle`, `migrations`, and `db/migrations`. For any other directory, provide its path. `--changed` without a base checks staged, unstaged and untracked SQL; with a base, it additionally checks branch changes. For pull requests, fetch the base branch first (`fetch-depth: 0` in GitHub Actions).
108
+ Without a base reference, `--changed` checks staged, unstaged, and untracked SQL files. With a base reference, it additionally checks branch changes.
109
+
110
+ For pull requests, fetch the base branch first. Use `fetch-depth: 0` in GitHub Actions.
111
+
112
+ ## PostgreSQL migration rules
113
+
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.
139
+
140
+ Example configuration (`pg-safe-migrate.config.json`):
141
+
142
+ ```json
143
+ {
144
+ "severity": "error",
145
+ "postgresVersion": 16,
146
+ "rules": { "PG015": "warning", "PG016": "warning" },
147
+ "exclude": ["archive"]
148
+ }
149
+ ```
150
+
151
+ Report options: `--format text|json|sarif`, `--output <file>`, `--advisor`, `--postgres-version <major>`, and `--fail-on warning|error|none`.
152
+
153
+ Each finding includes a description of the risk and a suggested safer migration approach.
154
+
155
+ A passing result means no configured patterns were detected, not that a migration is guaranteed to be safe.
156
+
157
+ ## GitHub Actions integration
17
158
 
18
- ## Rules
159
+ Automatically check migration files during pull requests.
19
160
 
20
- | Rule | Flagged pattern | Reason |
21
- | --- | --- | --- |
22
- | PG001 | CREATE INDEX without CONCURRENTLY | Blocks writes during index build |
23
- | PG002 | DROP COLUMN | May break old app versions |
24
- | PG003 | ALTER COLUMN TYPE | Strong lock and possible rewrite |
25
- | PG004 | ADD COLUMN NOT NULL without DEFAULT | Backfill/compatibility risk |
26
- | PG005 | ADD FOREIGN KEY without NOT VALID | Validation can block writes |
27
- | PG006 | RENAME | May break old app versions |
161
+ Copy the [example consumer workflow](https://github.com/subodhsingh001/pg-safe-migrate/blob/main/examples/consumer-workflow.yml) into your application's repository:
28
162
 
29
- A passing result means **no configured patterns were found**, not that a migration is production-safe. Evaluate PostgreSQL version, lock timeout, data volume, long-running transactions, ORM transaction wrapping, and deployment sequencing separately.
163
+ ```text
164
+ .github/workflows/pg-safe-migrate.yml
165
+ ```
30
166
 
31
- ## GitHub Actions
167
+ The workflow checks changed SQL migrations so teams can adopt the linter without immediately rewriting historical migrations.
32
168
 
33
- Copy [`examples/consumer-workflow.yml`](examples/consumer-workflow.yml) into your application's `.github/workflows/pg-safe-migrate.yml`. It checks SQL files changed in a PR and doesn't require fixing historical migrations. Pin the package to an audited version, and upgrade deliberately.
169
+ For reproducible builds, pin the package to a reviewed version and upgrade deliberately.
34
170
 
35
171
  ## Verify the published CLI
36
172
 
37
- From a clean directory:
173
+ From a clean directory, run:
38
174
 
39
- ```sh
40
- npx --yes --package=@subodh001/pg-safe-migrate@1.1.1 pg-safe-migrate --help
175
+ ```bash
176
+ npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
41
177
  ```
42
178
 
43
- Create `unsafe.sql` containing `CREATE INDEX idx_users_email ON users(email);`, then run:
179
+ Create a file named `unsafe.sql`:
44
180
 
45
- ```sh
46
- npx --yes --package=@subodh001/pg-safe-migrate@1.1.1 pg-safe-migrate unsafe.sql
181
+ ```sql
182
+ CREATE INDEX idx_users_email ON users(email);
183
+ ```
184
+
185
+ Then execute:
186
+
187
+ ```bash
188
+ npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate unsafe.sql
47
189
  ```
48
190
 
49
- Expect `PG001` and exit code 1. The sample `examples/safe.sql` uses `CONCURRENTLY` and should pass PG001; it must run outside a transaction.
191
+ Expected behavior: PG001 is reported and the CLI exits with code `1`.
192
+
193
+ The included `examples/safe.sql` demonstrates concurrent index creation and should pass PG001.
50
194
 
51
195
  ## Development
52
196
 
53
- ```sh
54
- npm install
197
+ Clone the repository:
198
+
199
+ ```bash
200
+ git clone https://github.com/subodhsingh001/pg-safe-migrate.git
201
+ cd pg-safe-migrate
202
+ ```
203
+
204
+ Install dependencies:
205
+
206
+ ```bash
207
+ npm ci
208
+ ```
209
+
210
+ Run tests:
211
+
212
+ ```bash
55
213
  npm test
214
+ ```
215
+
216
+ Test the rule engine:
217
+
218
+ ```bash
56
219
  node bin/cli.js test/unsafe_migration.sql
220
+ ```
221
+
222
+ Check the npm package:
223
+
224
+ ```bash
57
225
  npm pack --dry-run
58
226
  ```
59
227
 
60
- For reproducible CI, commit the generated `package-lock.json` and replace `npm install` in the project's CI with `npm ci`.
228
+ ## Current release
229
+
230
+ **v2.0.0**
231
+
232
+ - Expanded PostgreSQL migration risk checks and framework advisories
233
+ - PostgreSQL AST-based parsing
234
+ - Prisma and Drizzle migration directory detection
235
+ - Git-diff mode
236
+ - GitHub Actions support
237
+ - JSON/SARIF reports and optional advisor
238
+ - Configurable severity, exclusions, and PostgreSQL-version guidance
239
+ - Actionable migration recommendations
240
+
241
+ [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)
61
242
 
62
243
  ## Limitations
63
244
 
64
- This is a static AST linter, not a database execution simulator. It does not connect to production, estimate lock wait time, validate migration rollback, or understand the live schema. `--changed` checks changed SQL files, not SQL inside changed JavaScript/TypeScript files. Some flagged operations can be acceptable under controlled conditions, and some unflagged operations can still cause downtime.
245
+ `pg-safe-migrate` is a static AST-based linter, not a migration execution simulator.
246
+
247
+ It does not:
248
+
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
255
+
256
+ Some flagged operations may be acceptable under controlled conditions. Some unflagged operations may still cause downtime.
257
+
258
+ Always consider PostgreSQL version, table size, transaction behavior, lock timeouts, long-running transactions, and application deployment sequencing.
259
+
260
+ ## Validation and real ORM runners
261
+
262
+ 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.
263
+
264
+ ## Contributing
265
+
266
+ Contributions, bug reports, PostgreSQL edge cases, and suggestions for additional safety rules are welcome.
267
+
268
+ Open an issue or submit a pull request on GitHub.
269
+
270
+ ## License
271
+
272
+ MIT License.
273
+
274
+ ## v2.0 features
275
+
276
+ - `--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.
277
+ - `--advisor` gives Prisma/Drizzle/raw-SQL-aware deployment guidance. Recommendations are advisory and do not inspect the live database.
278
+ - 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.
279
+ - 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.
280
+ - JSON and SARIF outputs include source locations when the PostgreSQL parser supplies statement offsets.
281
+ - `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.
282
+
283
+ ### Examples
284
+
285
+ ```bash
286
+ node bin/cli.js prisma/migrations --postgres-version 16 --advisor
287
+ node bin/cli.js db/migrations --format json --output report.json
288
+ node bin/cli.js --changed origin/main --format sarif --output report.sarif --fail-on none
289
+ ```
290
+
291
+ ### Known gaps
292
+
293
+ 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.
294
+
295
+ ### Experimental: read-only database catalog snapshot
296
+
297
+ 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:
298
+
299
+ ```powershell
300
+ npm install pg
301
+ $env:DATABASE_URL = 'postgresql://readonly_user:password@127.0.0.1:5432/testdb'
302
+ node bin/cli.js --inspect-db
303
+ ```
304
+
305
+ 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.
306
+
307
+ ### Experimental disposable PostgreSQL simulation
308
+
309
+ To check whether a SQL migration executes against an **empty disposable PostgreSQL database** (requires local Docker and a locally available PostgreSQL image):
310
+
311
+ ```sh
312
+ node bin/cli.js --simulate examples/safe.sql --postgres-version 16
313
+ node bin/cli.js --simulate examples/unsafe.sql --postgres-version 16 --simulate-timeout 60
314
+ ```
315
+
316
+ 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).
317
+
318
+ ### Docker simulator with baseline and ordered migrations (experimental)
319
+
320
+ The simulator starts a disposable PostgreSQL container without published ports or external networking.
321
+ Use a baseline to create tables that a migration expects:
322
+
323
+ ```cmd
324
+ node bin/cli.js --simulate examples/safe.sql --baseline examples/baseline.sql --postgres-version 16
325
+ node bin/cli.js --simulate examples/unsafe.sql --baseline examples/baseline.sql --postgres-version 16
326
+ ```
327
+
328
+ Run all top-level `.sql` files in a folder in lexicographic filename order:
329
+
330
+ ```cmd
331
+ node bin/cli.js --migrations-dir path/to/migrations --baseline examples/baseline.sql --postgres-version 16
332
+ ```
333
+
334
+ 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.
335
+
336
+ The directory mode processes only top-level `.sql` files (maximum 100); nested ORM-specific migration directories are not automatically traversed.
337
+
338
+ ## Consolidated experimental development capabilities
65
339
 
66
- MIT licensed. Issues and edge-case reproductions welcome.
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.
package/bin/cli.js CHANGED
@@ -1,61 +1,90 @@
1
1
  #!/usr/bin/env node
2
- import fs from 'fs';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
3
4
  import { program } from 'commander';
4
5
  import chalk from 'chalk';
5
- import { parseSqlFile } from '../src/parser.js';
6
- import { lintStatements } from '../src/engine.js';
6
+ import { createRequire } from 'node:module';
7
+ import { toGitHubAnnotations, toMarkdownSummary } from '../src/github.js';
8
+ import { summarizeRisk } from '../src/risk.js';
9
+ import { getPreset } from '../src/presets.js';
10
+ const require = createRequire(import.meta.url);
11
+ const { version } = require('../package.json');
7
12
  import { findMigrationFiles } from '../src/detector.js';
8
13
  import { getChangedSqlFiles } from '../src/gitDiff.js';
14
+ import { loadConfig, isExcluded } from '../src/config.js';
15
+ import { analyzeFiles } from '../src/analysis.js';
16
+ import { toJson, toSarif } from '../src/reports.js';
17
+ import { inspectDatabaseUrl } from '../src/db-inspect.js';
18
+ import { simulateSqlFile } from '../src/simulator.js';
19
+ import { combinedAssessment } from '../src/combined.js';
20
+ import { loadTeamPolicy, assessTeamPolicy } from '../src/team-policy.js';
9
21
 
10
- program
11
- .name('pg-safe-migrate')
12
- .description('Deterministic AST linter for zero-downtime PostgreSQL migrations')
13
- .version('1.1.2')
14
- .argument('[target]', 'Path to a .sql file or migrations directory')
15
- .option('-c, --changed [baseBranch]', 'Lint changed SQL files (optionally compare with a base ref)')
16
- .action(async (target, options) => {
17
- try {
18
- let files = [];
19
-
20
- if (options.changed) {
21
- const baseBranch = typeof options.changed === 'string' ? options.changed : undefined;
22
- files = getChangedSqlFiles(baseBranch);
23
- if (files.length === 0) {
24
- console.log(chalk.green('✔ No changed .sql files found.'));
25
- process.exit(0);
26
- }
27
- } else {
28
- files = findMigrationFiles(target);
29
- }
30
-
31
- let totalIssues = 0;
32
-
33
- for (const file of files) {
34
- const sql = fs.readFileSync(file, 'utf-8');
35
- const stmts = await parseSqlFile(sql);
36
- const issues = lintStatements(stmts);
37
-
38
- if (issues.length > 0) {
39
- totalIssues += issues.length;
40
- console.log(chalk.bold.underline(`\nFile: ${file}`));
41
- for (const issue of issues) {
42
- console.log(chalk.red(` ✖ [${issue.ruleId}] ${issue.message}`));
43
- console.log(chalk.yellow(` Fix: ${issue.fix}\n`));
44
- }
45
- }
46
- }
47
-
48
- if (totalIssues === 0) {
49
- console.log(chalk.green(`✔ Checked ${files.length} migration file(s). No configured migration risks detected (not a downtime guarantee).`));
50
- process.exit(0);
51
- } else {
52
- console.log(chalk.red.bold(`Found ${totalIssues} blocking migration issue(s).`));
53
- process.exit(1);
54
- }
55
- } catch (err) {
56
- console.error(chalk.red(`Error: ${err.message}`));
57
- process.exit(1);
58
- }
59
- });
60
-
22
+ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk linter (not a downtime guarantee)').version(version)
23
+ .argument('[target]', 'SQL file or migrations directory')
24
+ .option('-c, --changed [baseBranch]', 'Lint changed SQL files')
25
+ .option('--format <format>', 'text, json or sarif', 'text')
26
+ .option('--output <file>', 'Write report to file')
27
+ .option('--config <file>', 'JSON configuration file', 'pg-safe-migrate.config.json')
28
+ .option('--postgres-version <version>', 'Target PostgreSQL major version')
29
+ .option('--fail-on <severity>', 'warning, error or none', 'error')
30
+ .option('--advisor', 'Include deployment guidance')
31
+ .option('--preset <name>', 'recommended or strict', 'recommended')
32
+ .option('--github', 'Emit GitHub workflow annotations')
33
+ .option('--summary <file>', 'Write Markdown PR summary')
34
+ .option('--risk', 'Include heuristic risk score in text output')
35
+ .option('--assess', 'Combine static linting with disposable PostgreSQL simulation')
36
+ .option('--verify-sql <file>', 'Run post-migration SQL assertions (SQL errors or exceptions fail verification)')
37
+ .option('--team-policy <file>', 'Local JSON team policy for combined assessment')
38
+ .option('--simulate <sqlFile>', 'Execute one SQL file against a disposable Docker PostgreSQL container')
39
+ .option('--baseline <sqlFile>', 'Apply baseline SQL before simulation')
40
+ .option('--migrations-dir <directory>', 'Simulate top-level SQL migrations in filename order')
41
+ .option('--simulate-timeout <seconds>', 'Simulation execution timeout (10-300 seconds)', '60')
42
+ .option('--inspect-db', 'Inspect database catalog (requires DATABASE_URL and optional pg dependency)')
43
+ .action(async (target,opts)=>{
44
+ try {
45
+ if (!['text','json','sarif'].includes(opts.format)) throw new Error('format must be text, json or sarif');
46
+ if (!['none','warning','error'].includes(opts.failOn)) throw new Error('fail-on must be none, warning or error');
47
+ const preset = getPreset(opts.preset);
48
+ const userConfig = loadConfig(opts.config);
49
+ const config = { ...preset, ...userConfig, rules: { ...preset.rules, ...userConfig.rules } };
50
+ if(opts.postgresVersion!==undefined) {
51
+ const version=Number(opts.postgresVersion);
52
+ if (!Number.isInteger(version)||version<10||version>99) throw new Error('postgres-version must be an integer >= 10');
53
+ config.postgresVersion=version;
54
+ }
55
+ if (opts.assess) {
56
+ const policy = opts.teamPolicy ? loadTeamPolicy(opts.teamPolicy) : null;
57
+ const assessment = await combinedAssessment({ file: opts.simulate, migrationsDir: opts.migrationsDir, baseline: opts.baseline, verifySql: opts.verifySql, postgresVersion: String(opts.postgresVersion ?? '16'), config });
58
+ if (policy) assessment.teamPolicy = assessTeamPolicy(assessment, policy);
59
+ if (opts.output) { fs.mkdirSync(path.dirname(path.resolve(opts.output)), {recursive:true}); fs.writeFileSync(opts.output, JSON.stringify(assessment,null,2)+'\n'); }
60
+ else console.log(JSON.stringify(assessment,null,2));
61
+ process.exitCode = assessment.passed && (!assessment.teamPolicy || assessment.teamPolicy.passed) ? 0 : 1;
62
+ return;
63
+ }
64
+ if (opts.simulate || opts.migrationsDir) {
65
+ const result = simulateSqlFile(opts.simulate, { baseline: opts.baseline, migrationsDir: opts.migrationsDir, postgresVersion: String(opts.postgresVersion ?? '16'), timeoutSeconds: Number(opts.simulateTimeout), verifySql: opts.verifySql });
66
+ console.log(JSON.stringify(result, null, 2));
67
+ process.exitCode = result.passed ? 0 : 1;
68
+ return;
69
+ }
70
+ if (opts.inspectDb) {
71
+ const snapshot = await inspectDatabaseUrl(process.env.DATABASE_URL);
72
+ console.log(JSON.stringify(snapshot, null, 2));
73
+ return;
74
+ }
75
+ const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
76
+ const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
77
+ const findings=await analyzeFiles(entries,config,{advisor:opts.advisor});
78
+ if (opts.github) process.stdout.write(toGitHubAnnotations(findings));
79
+ if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length));}
80
+ const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion}):opts.format==='sarif'?toSarif(findings):[
81
+ ...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}`):[])]),
82
+ ...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(findings))}`]:[]),
83
+ `Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
84
+ ].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;
88
+ }catch(e){console.error(`Error: ${e.message}`);process.exitCode=2;}
89
+ });
61
90
  program.parse();
@@ -0,0 +1,7 @@
1
+ -- Example schema expected by examples/safe.sql and examples/unsafe.sql.
2
+ CREATE TABLE users (
3
+ id bigint PRIMARY KEY,
4
+ email text,
5
+ name text
6
+ );
7
+ INSERT INTO users (id, email, name) VALUES (1, 'example@example.com', 'Example');
@@ -0,0 +1,35 @@
1
+ name: PostgreSQL migration safety
2
+ on:
3
+ pull_request:
4
+ paths:
5
+ - '**/*.sql'
6
+ permissions:
7
+ contents: read
8
+ security-events: write
9
+ jobs:
10
+ migrations:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ with:
15
+ fetch-depth: 0
16
+ - uses: actions/setup-node@v4
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'
23
+ env:
24
+ 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
@@ -0,0 +1 @@
1
+ ALTER TABLE users ADD COLUMN phone TEXT;
@@ -0,0 +1 @@
1
+ CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
@@ -0,0 +1,2 @@
1
+ -- This avoids PG001; execute outside a transaction.
2
+ CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "example-team",
3
+ "maxRiskScore": 80,
4
+ "maxWarnings": 10,
5
+ "blockedRules": ["PG001", "PG002"],
6
+ "requireSimulation": true
7
+ }
@@ -0,0 +1 @@
1
+ DROP TABLE users;
@@ -0,0 +1,2 @@
1
+ -- Expected: PG001. This file is a demonstration, not a production migration.
2
+ CREATE INDEX idx_users_email ON users(email);
@@ -0,0 +1,8 @@
1
+ DO $$ BEGIN
2
+ IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='phone') THEN
3
+ RAISE EXCEPTION 'users.phone missing';
4
+ END IF;
5
+ IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname='idx_users_email') THEN
6
+ RAISE EXCEPTION 'email index missing';
7
+ END IF;
8
+ END $$;