@subodh001/pg-safe-migrate 2.0.0 → 2.3.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/ALL-MILESTONES-TESTING.md +41 -0
- package/README.md +94 -11
- package/bin/cli.js +49 -2
- package/examples/baseline.sql +7 -0
- package/examples/consumer-workflow.yml +35 -0
- package/examples/migrations/001_add_phone.sql +1 -0
- package/examples/migrations/002_add_email_index.sql +1 -0
- package/examples/safe.sql +2 -0
- package/examples/team-policy.json +7 -0
- package/examples/test-unsafe.sql +1 -0
- package/examples/unsafe.sql +2 -0
- package/examples/verify.sql +8 -0
- package/package.json +13 -3
- package/scripts/orm-runner/README.md +35 -0
- package/scripts/orm-runner/package-lock.json +659 -0
- package/scripts/orm-runner/package.json +14 -0
- package/scripts/orm-runner/verify.mjs +360 -0
- package/scripts/test-pg-matrix.cjs +30 -0
- package/src/analysis.js +9 -7
- package/src/combined.js +60 -0
- package/src/db-inspect.js +30 -0
- package/src/engine.js +9 -3
- package/src/github.js +17 -0
- package/src/locks.js +8 -0
- package/src/plans.js +9 -0
- package/src/presets.js +5 -0
- package/src/risk.js +5 -0
- package/src/rules/dataIntegrityRules.js +40 -0
- package/src/rules/operationalRiskRules.js +57 -0
- package/src/rules/ruleCatalog.js +33 -0
- package/src/rules/versionCatalog.js +16 -0
- package/src/rules/versionRules.js +49 -0
- package/src/simulator.js +135 -0
- package/src/team-policy.js +23 -0
|
@@ -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,4 +1,6 @@
|
|
|
1
|
-
> **Development
|
|
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.
|
|
2
4
|
|
|
3
5
|
# pg-safe-migrate
|
|
4
6
|
|
|
@@ -6,9 +8,9 @@
|
|
|
6
8
|
|
|
7
9
|
An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, and raw SQL**.
|
|
8
10
|
|
|
9
|
-
Detect
|
|
11
|
+
Detect risky PostgreSQL DDL patterns and provide additional framework-specific migration advisories.
|
|
10
12
|
|
|
11
|
-
**Features:** PostgreSQL AST parsing ·
|
|
13
|
+
**Features:** PostgreSQL AST parsing · PG001–PG017 identifiers (see rule coverage below) · Git-diff mode · JSON/SARIF · configurable severity · optional advisor · GitHub Actions
|
|
12
14
|
|
|
13
15
|
> **Important:** This tool identifies configured migration risks. It does not guarantee zero downtime.
|
|
14
16
|
|
|
@@ -55,7 +57,7 @@ npm install --save-dev @subodh001/pg-safe-migrate
|
|
|
55
57
|
Or execute the published package without installing it in your project:
|
|
56
58
|
|
|
57
59
|
```bash
|
|
58
|
-
npx --yes --package=@subodh001/pg-safe-migrate@
|
|
60
|
+
npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
|
|
59
61
|
```
|
|
60
62
|
|
|
61
63
|
## Quick start
|
|
@@ -118,6 +120,36 @@ For pull requests, fetch the base branch first. Use `fetch-depth: 0` in GitHub A
|
|
|
118
120
|
| **PG005** | ADD FOREIGN KEY without NOT VALID | Validation may block writes |
|
|
119
121
|
| **PG006** | RENAME | Breaks applications expecting old names |
|
|
120
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
|
+
|
|
121
153
|
Each finding includes a description of the risk and a suggested safer migration approach.
|
|
122
154
|
|
|
123
155
|
A passing result means no configured patterns were detected, not that a migration is guaranteed to be safe.
|
|
@@ -141,7 +173,7 @@ For reproducible builds, pin the package to a reviewed version and upgrade delib
|
|
|
141
173
|
From a clean directory, run:
|
|
142
174
|
|
|
143
175
|
```bash
|
|
144
|
-
npx --yes --package=@subodh001/pg-safe-migrate@
|
|
176
|
+
npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
|
|
145
177
|
```
|
|
146
178
|
|
|
147
179
|
Create a file named `unsafe.sql`:
|
|
@@ -153,7 +185,7 @@ CREATE INDEX idx_users_email ON users(email);
|
|
|
153
185
|
Then execute:
|
|
154
186
|
|
|
155
187
|
```bash
|
|
156
|
-
npx --yes --package=@subodh001/pg-safe-migrate@
|
|
188
|
+
npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate unsafe.sql
|
|
157
189
|
```
|
|
158
190
|
|
|
159
191
|
Expected behavior: PG001 is reported and the CLI exits with code `1`.
|
|
@@ -195,13 +227,15 @@ npm pack --dry-run
|
|
|
195
227
|
|
|
196
228
|
## Current release
|
|
197
229
|
|
|
198
|
-
**
|
|
230
|
+
**v2.0.0**
|
|
199
231
|
|
|
200
|
-
-
|
|
232
|
+
- Expanded PostgreSQL migration risk checks and framework advisories
|
|
201
233
|
- PostgreSQL AST-based parsing
|
|
202
234
|
- Prisma and Drizzle migration directory detection
|
|
203
235
|
- Git-diff mode
|
|
204
236
|
- GitHub Actions support
|
|
237
|
+
- JSON/SARIF reports and optional advisor
|
|
238
|
+
- Configurable severity, exclusions, and PostgreSQL-version guidance
|
|
205
239
|
- Actionable migration recommendations
|
|
206
240
|
|
|
207
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)
|
|
@@ -223,6 +257,10 @@ Some flagged operations may be acceptable under controlled conditions. Some unfl
|
|
|
223
257
|
|
|
224
258
|
Always consider PostgreSQL version, table size, transaction behavior, lock timeouts, long-running transactions, and application deployment sequencing.
|
|
225
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
|
+
|
|
226
264
|
## Contributing
|
|
227
265
|
|
|
228
266
|
Contributions, bug reports, PostgreSQL edge cases, and suggestions for additional safety rules are welcome.
|
|
@@ -233,9 +271,7 @@ Open an issue or submit a pull request on GitHub.
|
|
|
233
271
|
|
|
234
272
|
MIT License.
|
|
235
273
|
|
|
236
|
-
## v2.0
|
|
237
|
-
|
|
238
|
-
> Development candidate: do not publish until the full test suite and representative PostgreSQL integration tests pass.
|
|
274
|
+
## v2.0 features
|
|
239
275
|
|
|
240
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.
|
|
241
277
|
- `--advisor` gives Prisma/Drizzle/raw-SQL-aware deployment guidance. Recommendations are advisory and do not inspect the live database.
|
|
@@ -255,3 +291,50 @@ node bin/cli.js --changed origin/main --format sarif --output report.sarif --fai
|
|
|
255
291
|
### Known gaps
|
|
256
292
|
|
|
257
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
|
|
339
|
+
|
|
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
|
@@ -3,13 +3,23 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { program } from 'commander';
|
|
5
5
|
import chalk from 'chalk';
|
|
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');
|
|
6
12
|
import { findMigrationFiles } from '../src/detector.js';
|
|
7
13
|
import { getChangedSqlFiles } from '../src/gitDiff.js';
|
|
8
14
|
import { loadConfig, isExcluded } from '../src/config.js';
|
|
9
15
|
import { analyzeFiles } from '../src/analysis.js';
|
|
10
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';
|
|
11
21
|
|
|
12
|
-
program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk linter (not a downtime guarantee)').version(
|
|
22
|
+
program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk linter (not a downtime guarantee)').version(version)
|
|
13
23
|
.argument('[target]', 'SQL file or migrations directory')
|
|
14
24
|
.option('-c, --changed [baseBranch]', 'Lint changed SQL files')
|
|
15
25
|
.option('--format <format>', 'text, json or sarif', 'text')
|
|
@@ -18,21 +28,58 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
|
|
|
18
28
|
.option('--postgres-version <version>', 'Target PostgreSQL major version')
|
|
19
29
|
.option('--fail-on <severity>', 'warning, error or none', 'error')
|
|
20
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)')
|
|
21
43
|
.action(async (target,opts)=>{
|
|
22
44
|
try {
|
|
23
45
|
if (!['text','json','sarif'].includes(opts.format)) throw new Error('format must be text, json or sarif');
|
|
24
46
|
if (!['none','warning','error'].includes(opts.failOn)) throw new Error('fail-on must be none, warning or error');
|
|
25
|
-
const
|
|
47
|
+
const preset = getPreset(opts.preset);
|
|
48
|
+
const userConfig = loadConfig(opts.config);
|
|
49
|
+
const config = { ...preset, ...userConfig, rules: { ...preset.rules, ...userConfig.rules } };
|
|
26
50
|
if(opts.postgresVersion!==undefined) {
|
|
27
51
|
const version=Number(opts.postgresVersion);
|
|
28
52
|
if (!Number.isInteger(version)||version<10||version>99) throw new Error('postgres-version must be an integer >= 10');
|
|
29
53
|
config.postgresVersion=version;
|
|
30
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
|
+
}
|
|
31
75
|
const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
|
|
32
76
|
const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
|
|
33
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));}
|
|
34
80
|
const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion}):opts.format==='sarif'?toSarif(findings):[
|
|
35
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))}`]:[]),
|
|
36
83
|
`Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
|
|
37
84
|
].join('\n');
|
|
38
85
|
if(opts.output) {fs.mkdirSync(path.dirname(path.resolve(opts.output)),{recursive:true});fs.writeFileSync(opts.output,report+'\n');}
|
|
@@ -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 @@
|
|
|
1
|
+
DROP TABLE users;
|
|
@@ -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 $$;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@subodh001/pg-safe-migrate",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "PostgreSQL AST migration risk linter for Prisma, Drizzle and SQL",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -8,8 +8,11 @@
|
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
10
|
"test": "node --test",
|
|
11
|
+
"test:unit": "node scripts/run-unit-tests.cjs",
|
|
12
|
+
"test:integration": "node scripts/test-pg-matrix.cjs",
|
|
11
13
|
"lint": "node bin/cli.js",
|
|
12
|
-
"pack:check": "npm pack --dry-run"
|
|
14
|
+
"pack:check": "npm pack --dry-run",
|
|
15
|
+
"test:release": "npm run test:unit && node test/release-smoke.cjs"
|
|
13
16
|
},
|
|
14
17
|
"keywords": [
|
|
15
18
|
"postgresql",
|
|
@@ -34,7 +37,14 @@
|
|
|
34
37
|
"bin/",
|
|
35
38
|
"src/",
|
|
36
39
|
"README.md",
|
|
37
|
-
"LICENSE"
|
|
40
|
+
"LICENSE",
|
|
41
|
+
"examples/",
|
|
42
|
+
"scripts/test-pg-matrix.cjs",
|
|
43
|
+
"scripts/orm-runner/verify.mjs",
|
|
44
|
+
"scripts/orm-runner/package.json",
|
|
45
|
+
"scripts/orm-runner/package-lock.json",
|
|
46
|
+
"scripts/orm-runner/README.md",
|
|
47
|
+
"ALL-MILESTONES-TESTING.md"
|
|
38
48
|
],
|
|
39
49
|
"repository": {
|
|
40
50
|
"type": "git",
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Optional real ORM migration verification
|
|
2
|
+
|
|
3
|
+
This integration test runs **actual Prisma Migrate and Drizzle ORM migration runners** against a disposable PostgreSQL database. It is separate from the package's default `npm test` and GitHub Actions workflow.
|
|
4
|
+
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
- Node.js and npm
|
|
8
|
+
- Docker with an available local PostgreSQL port, or another **disposable** PostgreSQL database
|
|
9
|
+
- Dependencies installed in `scripts/orm-runner` with `npm install`
|
|
10
|
+
|
|
11
|
+
## Windows PowerShell
|
|
12
|
+
|
|
13
|
+
From the repository root:
|
|
14
|
+
|
|
15
|
+
```powershell
|
|
16
|
+
docker run -d --name pg-safe-orm-test -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=pg_safe_local_test_2026 -e POSTGRES_DB=pg_safe_migrate_test -p 127.0.0.1:55432:5432 postgres:16
|
|
17
|
+
$env:DATABASE_URL = "postgresql://postgres:pg_safe_local_test_2026@127.0.0.1:55432/pg_safe_migrate_test"
|
|
18
|
+
cd scripts/orm-runner
|
|
19
|
+
npm install
|
|
20
|
+
npm run verify
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The Docker container command is for an isolated local test only. If the container already exists, start it with `docker start pg-safe-orm-test` instead of creating another one. Stop and remove it when finished with `docker rm -f pg-safe-orm-test`.
|
|
24
|
+
|
|
25
|
+
## Expected checks
|
|
26
|
+
|
|
27
|
+
1. Prisma applies a baseline table migration.
|
|
28
|
+
2. Prisma applies a **separate** concurrent-index migration and the index exists.
|
|
29
|
+
3. The tested Drizzle node-postgres migrator rejects `CREATE INDEX CONCURRENTLY` inside its transaction with PostgreSQL `25001`.
|
|
30
|
+
4. The rejected Drizzle index is absent.
|
|
31
|
+
5. Temporary database schemas and local temporary files are cleaned up.
|
|
32
|
+
|
|
33
|
+
`KEEP_TEST_SCHEMAS=1` retains test schemas for inspection; do not set it during normal verification.
|
|
34
|
+
|
|
35
|
+
**Safety:** This script creates and drops schemas. Run it only against a disposable test database, never a production or shared database. Results depend on the exact Prisma, Drizzle, PostgreSQL, and runner versions installed.
|