@subodh001/pg-safe-migrate 1.1.1 → 2.0.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/README.md CHANGED
@@ -1,30 +1,257 @@
1
+ > **Development notice:** This checkout is a v2.0.0-rc.1 candidate, not the published v1.1.2. See [UPGRADE-NOTES.md](UPGRADE-NOTES.md) for implemented features and unverified limitations.
2
+
1
3
  # pg-safe-migrate
2
4
 
3
- AST-based PostgreSQL migration **risk** linter for Prisma, Drizzle and SQL folders. Static checks do **not** guarantee zero downtime. PostgreSQL version, table size, locks, transaction boundaries and deployment order matter.
5
+ **Catch risky PostgreSQL migrations before they reach production.**
6
+
7
+ An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, and raw SQL**.
8
+
9
+ Detect six common migration patterns that may cause blocking database locks or application compatibility problems.
10
+
11
+ **Features:** PostgreSQL AST parsing · 6 safety rules · Git-diff mode · GitHub Actions · Zero-config migration detection
12
+
13
+ > **Important:** This tool identifies configured migration risks. It does not guarantee zero downtime.
14
+
15
+ ## Demo
16
+
17
+ See how `pg-safe-migrate` catches an unsafe PostgreSQL migration and suggests a safer alternative.
18
+
19
+ ![pg-safe-migrate CLI demonstration](assets/pg-safe-migrate-demo.gif)
20
+
21
+ ### Example
22
+
23
+ Unsafe migration:
24
+
25
+ ```sql
26
+ CREATE INDEX idx_users_email ON users(email);
27
+ ```
28
+
29
+ Detected issue:
30
+
31
+ ```text
32
+ [PG001] CREATE INDEX on "users" acquires a SHARE lock and blocks writes.
33
+
34
+ Fix: Use CREATE INDEX CONCURRENTLY and execute outside a transaction block.
35
+
36
+ Found 1 blocking migration issue(s).
37
+ ```
38
+
39
+ Safer alternative:
40
+
41
+ ```sql
42
+ CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
43
+ ```
44
+
45
+ `CREATE INDEX CONCURRENTLY` must run outside a transaction block.
46
+
47
+ ## Installation
48
+
49
+ Install as a development dependency:
50
+
51
+ ```bash
52
+ npm install --save-dev @subodh001/pg-safe-migrate
53
+ ```
54
+
55
+ Or execute the published package without installing it in your project:
56
+
57
+ ```bash
58
+ npx --yes --package=@subodh001/pg-safe-migrate@1.1.2 pg-safe-migrate --help
59
+ ```
60
+
61
+ ## Quick start
62
+
63
+ ### Automatically detect migrations
64
+
65
+ ```bash
66
+ npx pg-safe-migrate
67
+ ```
68
+
69
+ The CLI searches these directories:
70
+
71
+ - `prisma/migrations`
72
+ - `drizzle`
73
+ - `migrations`
74
+ - `db/migrations`
75
+
76
+ ### Prisma
77
+
78
+ ```bash
79
+ npx pg-safe-migrate prisma/migrations
80
+ ```
81
+
82
+ ### Drizzle
83
+
84
+ ```bash
85
+ npx pg-safe-migrate drizzle
86
+ ```
87
+
88
+ ### Raw SQL
89
+
90
+ ```bash
91
+ npx pg-safe-migrate db/migrations
92
+ ```
93
+
94
+ ### Check a specific migration
95
+
96
+ ```bash
97
+ npx pg-safe-migrate path/to/migration.sql
98
+ ```
4
99
 
5
- ## Usage
100
+ ### Check changed migrations only
101
+
102
+ ```bash
103
+ npx pg-safe-migrate --changed origin/main
104
+ ```
105
+
106
+ Without a base reference, `--changed` checks staged, unstaged, and untracked SQL files. With a base reference, it additionally checks branch changes.
107
+
108
+ For pull requests, fetch the base branch first. Use `fetch-depth: 0` in GitHub Actions.
109
+
110
+ ## PostgreSQL migration rules
111
+
112
+ | Rule | Detected pattern | Potential risk |
113
+ |---|---|---|
114
+ | **PG001** | CREATE INDEX without CONCURRENTLY | Blocks writes during index creation |
115
+ | **PG002** | DROP COLUMN | Breaks older application versions |
116
+ | **PG003** | ALTER COLUMN TYPE | Strong locks and possible table rewrites |
117
+ | **PG004** | ADD COLUMN NOT NULL without DEFAULT | Backfill and compatibility risks |
118
+ | **PG005** | ADD FOREIGN KEY without NOT VALID | Validation may block writes |
119
+ | **PG006** | RENAME | Breaks applications expecting old names |
120
+
121
+ Each finding includes a description of the risk and a suggested safer migration approach.
122
+
123
+ A passing result means no configured patterns were detected, not that a migration is guaranteed to be safe.
124
+
125
+ ## GitHub Actions integration
126
+
127
+ Automatically check migration files during pull requests.
128
+
129
+ Copy the [example consumer workflow](https://github.com/subodhsingh001/pg-safe-migrate/blob/main/examples/consumer-workflow.yml) into your application's repository:
130
+
131
+ ```text
132
+ .github/workflows/pg-safe-migrate.yml
133
+ ```
134
+
135
+ The workflow checks changed SQL migrations so teams can adopt the linter without immediately rewriting historical migrations.
136
+
137
+ For reproducible builds, pin the package to a reviewed version and upgrade deliberately.
138
+
139
+ ## Verify the published CLI
140
+
141
+ From a clean directory, run:
142
+
143
+ ```bash
144
+ npx --yes --package=@subodh001/pg-safe-migrate@1.1.2 pg-safe-migrate --help
145
+ ```
146
+
147
+ Create a file named `unsafe.sql`:
148
+
149
+ ```sql
150
+ CREATE INDEX idx_users_email ON users(email);
151
+ ```
152
+
153
+ Then execute:
154
+
155
+ ```bash
156
+ npx --yes --package=@subodh001/pg-safe-migrate@1.1.2 pg-safe-migrate unsafe.sql
157
+ ```
158
+
159
+ Expected behavior: PG001 is reported and the CLI exits with code `1`.
160
+
161
+ The included `examples/safe.sql` demonstrates concurrent index creation and should pass PG001.
162
+
163
+ ## Development
164
+
165
+ Clone the repository:
166
+
167
+ ```bash
168
+ git clone https://github.com/subodhsingh001/pg-safe-migrate.git
169
+ cd pg-safe-migrate
170
+ ```
171
+
172
+ Install dependencies:
173
+
174
+ ```bash
175
+ npm ci
176
+ ```
177
+
178
+ Run tests:
6
179
 
7
180
  ```bash
8
- npm install
9
181
  npm test
182
+ ```
183
+
184
+ Test the rule engine:
185
+
186
+ ```bash
10
187
  node bin/cli.js test/unsafe_migration.sql
11
- node bin/cli.js --changed
12
- node bin/cli.js --changed origin/main
13
188
  ```
14
189
 
15
- `--changed` includes staged, unstaged and untracked SQL files; with a base ref it also includes added/modified/renamed SQL files from the branch diff. Fetch the base ref in CI. When no argument is supplied the CLI scans all recognized migration directories.
190
+ Check the npm package:
191
+
192
+ ```bash
193
+ npm pack --dry-run
194
+ ```
195
+
196
+ ## Current release
197
+
198
+ **v1.1.2**
199
+
200
+ - Six PostgreSQL migration risk rules
201
+ - PostgreSQL AST-based parsing
202
+ - Prisma and Drizzle migration directory detection
203
+ - Git-diff mode
204
+ - GitHub Actions support
205
+ - Actionable migration recommendations
206
+
207
+ [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)
208
+
209
+ ## Limitations
16
210
 
17
- ## Rules
211
+ `pg-safe-migrate` is a static AST-based linter, not a migration execution simulator.
18
212
 
19
- - PG001: CREATE INDEX without CONCURRENTLY (blocks writes)
20
- - PG002: DROP COLUMN (application compatibility)
21
- - PG003: ALTER COLUMN TYPE (locking/rewrite risk, depending on change)
22
- - PG004: ADD NOT NULL column without DEFAULT (backfill/deployment risk)
23
- - PG005: ADD FOREIGN KEY without NOT VALID (validation lock risk)
24
- - PG006: RENAME (application compatibility)
213
+ It does not:
25
214
 
26
- Exit code 1 indicates issues or an error; 0 means no configured issues detected. Review changes with a DBA before production use. Some safe migration sequences still require lock_timeout, retries, explicit nontransactional execution and coordination across app versions.
215
+ - Connect to your production database
216
+ - Estimate actual lock waiting times
217
+ - Validate rollback procedures
218
+ - Inspect live database schemas
219
+ - Guarantee zero downtime
220
+ - Analyze SQL embedded inside changed JavaScript or TypeScript files
221
+
222
+ Some flagged operations may be acceptable under controlled conditions. Some unflagged operations may still cause downtime.
223
+
224
+ Always consider PostgreSQL version, table size, transaction behavior, lock timeouts, long-running transactions, and application deployment sequencing.
225
+
226
+ ## Contributing
227
+
228
+ Contributions, bug reports, PostgreSQL edge cases, and suggestions for additional safety rules are welcome.
229
+
230
+ Open an issue or submit a pull request on GitHub.
231
+
232
+ ## License
233
+
234
+ MIT License.
235
+
236
+ ## v2.0 release candidate features
237
+
238
+ > Development candidate: do not publish until the full test suite and representative PostgreSQL integration tests pass.
239
+
240
+ - `--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
+ - `--advisor` gives Prisma/Drizzle/raw-SQL-aware deployment guidance. Recommendations are advisory and do not inspect the live database.
242
+ - 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.
243
+ - 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.
244
+ - JSON and SARIF outputs include source locations when the PostgreSQL parser supplies statement offsets.
245
+ - `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.
246
+
247
+ ### Examples
248
+
249
+ ```bash
250
+ node bin/cli.js prisma/migrations --postgres-version 16 --advisor
251
+ node bin/cli.js db/migrations --format json --output report.json
252
+ node bin/cli.js --changed origin/main --format sarif --output report.sarif --fail-on none
253
+ ```
27
254
 
28
- ## Publishing
255
+ ### Known gaps
29
256
 
30
- Set the repository URL in package.json, then run `npm ci && npm test && npm pack --dry-run`. Confirm the npm package name is available and publish only after reviewing the package contents.
257
+ 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.
package/bin/cli.js CHANGED
@@ -1,61 +1,43 @@
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';
7
6
  import { findMigrationFiles } from '../src/detector.js';
8
7
  import { getChangedSqlFiles } from '../src/gitDiff.js';
8
+ import { loadConfig, isExcluded } from '../src/config.js';
9
+ import { analyzeFiles } from '../src/analysis.js';
10
+ import { toJson, toSarif } from '../src/reports.js';
9
11
 
10
- program
11
- .name('pg-safe-migrate')
12
- .description('Deterministic AST linter for zero-downtime PostgreSQL migrations')
13
- .version('1.1.1')
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
-
12
+ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk linter (not a downtime guarantee)').version('2.0.0-rc.2')
13
+ .argument('[target]', 'SQL file or migrations directory')
14
+ .option('-c, --changed [baseBranch]', 'Lint changed SQL files')
15
+ .option('--format <format>', 'text, json or sarif', 'text')
16
+ .option('--output <file>', 'Write report to file')
17
+ .option('--config <file>', 'JSON configuration file', 'pg-safe-migrate.config.json')
18
+ .option('--postgres-version <version>', 'Target PostgreSQL major version')
19
+ .option('--fail-on <severity>', 'warning, error or none', 'error')
20
+ .option('--advisor', 'Include deployment guidance')
21
+ .action(async (target,opts)=>{
22
+ try {
23
+ if (!['text','json','sarif'].includes(opts.format)) throw new Error('format must be text, json or sarif');
24
+ if (!['none','warning','error'].includes(opts.failOn)) throw new Error('fail-on must be none, warning or error');
25
+ const config=loadConfig(opts.config);
26
+ if(opts.postgresVersion!==undefined) {
27
+ const version=Number(opts.postgresVersion);
28
+ if (!Number.isInteger(version)||version<10||version>99) throw new Error('postgres-version must be an integer >= 10');
29
+ config.postgresVersion=version;
30
+ }
31
+ const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
32
+ const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
33
+ const findings=await analyzeFiles(entries,config,{advisor:opts.advisor});
34
+ const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion}):opts.format==='sarif'?toSarif(findings):[
35
+ ...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}`):[])]),
36
+ `Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
37
+ ].join('\n');
38
+ if(opts.output) {fs.mkdirSync(path.dirname(path.resolve(opts.output)),{recursive:true});fs.writeFileSync(opts.output,report+'\n');}
39
+ else console.log(opts.format==='text'?(findings.length?chalk.yellow(report):chalk.green(report)):report);
40
+ process.exitCode=opts.failOn==='warning'?Number(findings.length>0):opts.failOn==='error'?Number(findings.some(f=>f.severity==='error')):0;
41
+ }catch(e){console.error(`Error: ${e.message}`);process.exitCode=2;}
42
+ });
61
43
  program.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@subodh001/pg-safe-migrate",
3
- "version": "1.1.1",
3
+ "version": "2.0.0",
4
4
  "description": "PostgreSQL AST migration risk linter for Prisma, Drizzle and SQL",
5
5
  "type": "module",
6
6
  "bin": {
@@ -35,5 +35,13 @@
35
35
  "src/",
36
36
  "README.md",
37
37
  "LICENSE"
38
- ]
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/subodhsingh001/pg-safe-migrate.git"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/subodhsingh001/pg-safe-migrate/issues"
45
+ },
46
+ "homepage": "https://github.com/subodhsingh001/pg-safe-migrate#readme"
39
47
  }
package/src/advisor.js ADDED
@@ -0,0 +1,22 @@
1
+ const plans = {
2
+ PG001:['Confirm the runner is non-transactional.','Create the index CONCURRENTLY.','Monitor and clean up invalid indexes after failure.'],
3
+ PG002:['Deploy code that no longer reads or writes the old column.','Verify all old application instances are retired.','Drop the column in a later deployment.'],
4
+ PG003:['Assess type conversion and rewrite requirements.','Consider a replacement column with batched backfill.','Switch readers and writers before retiring the old column.'],
5
+ PG004:['Add a nullable column first.','Backfill in batches.','Validate before applying NOT NULL.'],
6
+ PG005:['Add the foreign key NOT VALID.','Validate in a separate migration.','Monitor lock duration.'],
7
+ PG006:['Introduce a compatible replacement.','Deploy applications supporting both names.','Remove the old name after a compatibility window.'],
8
+ PG007:['Verify index usage and dependencies.','Use DROP INDEX CONCURRENTLY outside transactions if appropriate.','Confirm the operation is supported without CASCADE.'],
9
+ PG008:['Split transactional and non-transactional migrations.','Run concurrent index DDL outside explicit transactions.','Verify migration runner behavior.'],
10
+ PG010:['Consider CREATE UNIQUE INDEX CONCURRENTLY.','Attach the index to the constraint if supported.','Validate uniqueness and existing duplicates.'],
11
+ PG011:['Check all application dependencies.','Archive required data.','Remove the table only after compatible code is deployed.'],
12
+ PG012:['Consider adding the CHECK constraint NOT VALID.','Validate it separately.','Monitor scan and lock impact.'],
13
+ PG013:['Review PostgreSQL version and proof of existing non-null values.','Consider a validated CHECK constraint strategy.','Apply SET NOT NULL during a controlled deployment.'],
14
+ PG014:['Avoid adding a default in the same step on PostgreSQL 10.','Backfill gradually.','Apply defaults and constraints in later migrations.'],
15
+ PG015:['Check the Prisma migration runner transaction strategy.','Execute CONCURRENTLY outside a transaction.','Verify the deployed migration in staging.'],
16
+ PG016:['Check Drizzle runner transaction wrapping.','Execute CONCURRENTLY outside a transaction.','Verify the deployed migration in staging.'],
17
+ PG017:['Inspect the earlier migration and dependency graph.','Confirm the final schema and deployment order.','Test the ordered migrations on staging.']
18
+ };
19
+ export function advise(issue,framework='sql') {
20
+ const context = framework==='prisma' ? 'Prisma migration: review migration.sql and the deployment runner.' : framework==='drizzle' ? 'Drizzle migration: review generated SQL and runner transaction behavior.' : 'Raw SQL: verify the execution transaction policy.';
21
+ return {ruleId:issue.ruleId,steps:plans[issue.ruleId] || ['Review SQL dependencies.','Test on staging.','Deploy with lock and statement timeouts.'],note:`${context} Guidance only; not validated against a live database.`};
22
+ }
@@ -0,0 +1,256 @@
1
+
2
+ import { parseSqlFile } from './parser.js';
3
+ import { lintStatements } from './engine.js';
4
+ import { advise } from './advisor.js';
5
+
6
+ const ADVISORY_RULES = new Set(['PG015', 'PG016', 'PG017']);
7
+
8
+ export function position(sql, offset = 0) {
9
+ const prefix = sql.slice(0, Math.max(0, offset));
10
+ const lines = prefix.split('\n');
11
+
12
+ return {
13
+ line: lines.length,
14
+ column: lines.at(-1).length + 1
15
+ };
16
+ }
17
+
18
+ export function frameworkFor(file) {
19
+ const p = file.replaceAll('\\', '/');
20
+
21
+ if (/(^|\/)prisma\/migrations\//.test(p)) return 'prisma';
22
+ if (/(^|\/)drizzle\//.test(p)) return 'drizzle';
23
+
24
+ return 'sql';
25
+ }
26
+
27
+ function txType(stmt) {
28
+ const kind = stmt.TransactionStmt?.kind;
29
+
30
+ if (kind === 'TRANS_STMT_BEGIN' || kind === 'TRANS_STMT_START') {
31
+ return 'begin';
32
+ }
33
+
34
+ if ([
35
+ 'TRANS_STMT_COMMIT',
36
+ 'TRANS_STMT_ROLLBACK',
37
+ 'TRANS_STMT_ROLLBACK_TO',
38
+ 'TRANS_STMT_PREPARE'
39
+ ].includes(kind)) {
40
+ return 'end';
41
+ }
42
+
43
+ return null;
44
+ }
45
+
46
+ function concurrently(stmt) {
47
+ return Boolean(
48
+ stmt.IndexStmt?.concurrent ||
49
+ (
50
+ stmt.DropStmt?.removeType === 'OBJECT_INDEX' &&
51
+ stmt.DropStmt.concurrent
52
+ )
53
+ );
54
+ }
55
+
56
+ function ddlTarget(stmt) {
57
+ if (stmt.AlterTableStmt) {
58
+ return stmt.AlterTableStmt.relation?.relname;
59
+ }
60
+
61
+ if (stmt.RenameStmt) {
62
+ return stmt.RenameStmt.relation?.relname;
63
+ }
64
+
65
+ if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') {
66
+ return stmt.DropStmt.objects?.[0]?.List?.items
67
+ ?.map(x => x.String?.sval)
68
+ .join('.');
69
+ }
70
+
71
+ return null;
72
+ }
73
+
74
+ function extras(stmt, postgresVersion) {
75
+ const issues = [];
76
+
77
+ const add = (ruleId, message, fix) => {
78
+ issues.push({ ruleId, message, fix });
79
+ };
80
+
81
+ if (!stmt.AlterTableStmt) return issues;
82
+
83
+ for (const wrapper of stmt.AlterTableStmt.cmds || []) {
84
+ const cmd = wrapper.AlterTableCmd;
85
+ if (!cmd) continue;
86
+
87
+ if (cmd.subtype === 'AT_SetNotNull') {
88
+ add(
89
+ 'PG013',
90
+ 'SET NOT NULL may scan a large table and requires a strong lock.',
91
+ 'Validate an equivalent CHECK constraint first where supported; test on your PostgreSQL version.'
92
+ );
93
+ }
94
+
95
+ if (
96
+ cmd.subtype === 'AT_AddConstraint' &&
97
+ cmd.def?.Constraint?.contype === 'CONSTR_CHECK' &&
98
+ !cmd.def.Constraint.skip_validation
99
+ ) {
100
+ add(
101
+ 'PG012',
102
+ 'Adding a validated CHECK constraint may scan existing rows.',
103
+ 'Consider NOT VALID followed by a separately scheduled VALIDATE CONSTRAINT.'
104
+ );
105
+ }
106
+
107
+ if (
108
+ cmd.subtype === 'AT_AddConstraint' &&
109
+ cmd.def?.Constraint?.contype === 'CONSTR_UNIQUE'
110
+ ) {
111
+ add(
112
+ 'PG010',
113
+ 'Adding a UNIQUE constraint can require a blocking index build.',
114
+ 'Consider CREATE UNIQUE INDEX CONCURRENTLY then attach the index using a constraint, where applicable.'
115
+ );
116
+ }
117
+
118
+ if (
119
+ cmd.subtype === 'AT_AddColumn' &&
120
+ postgresVersion != null &&
121
+ Number(postgresVersion) < 11
122
+ ) {
123
+ const def = cmd.def?.ColumnDef;
124
+
125
+ if (
126
+ def?.constraints?.some(
127
+ x => x.Constraint?.contype === 'CONSTR_DEFAULT'
128
+ )
129
+ ) {
130
+ add(
131
+ 'PG014',
132
+ 'On PostgreSQL 10, adding a column with a default may rewrite the table.',
133
+ 'Use a nullable column and controlled backfill, or evaluate upgrading PostgreSQL.'
134
+ );
135
+ }
136
+ }
137
+ }
138
+
139
+ return issues;
140
+ }
141
+
142
+ export async function analyzeFiles(entries, config = {}, options = {}) {
143
+ const findings = [];
144
+ const seen = new Map();
145
+ const version = config.postgresVersion ?? null;
146
+
147
+ const files = [...entries].sort((a, b) =>
148
+ a.file.localeCompare(b.file)
149
+ );
150
+
151
+ for (const { file, sql } of files) {
152
+ const parsed = await parseSqlFile(sql, { details: true });
153
+ const framework = frameworkFor(file);
154
+
155
+ let inTransaction = false;
156
+
157
+ for (const { stmt, offset } of parsed) {
158
+ const loc = position(sql, offset);
159
+ const transaction = txType(stmt);
160
+
161
+ if (transaction === 'begin') {
162
+ inTransaction = true;
163
+ }
164
+
165
+ const issues = [
166
+ ...lintStatements([stmt]),
167
+ ...extras(stmt, version)
168
+ ];
169
+
170
+ if (inTransaction && concurrently(stmt)) {
171
+ issues.push({
172
+ ruleId: 'PG008',
173
+ message: 'CONCURRENTLY cannot execute inside an explicit transaction block.',
174
+ fix: 'Run concurrent index operations outside BEGIN/COMMIT.'
175
+ });
176
+ }
177
+
178
+ if (framework === 'prisma' && concurrently(stmt)) {
179
+ issues.push({
180
+ ruleId: 'PG015',
181
+ message: 'Verify that the Prisma migration execution path does not wrap CONCURRENTLY in a transaction.',
182
+ fix: 'Review the generated migration and execution strategy; PostgreSQL forbids CONCURRENTLY inside a transaction.'
183
+ });
184
+ }
185
+
186
+ if (framework === 'drizzle' && concurrently(stmt)) {
187
+ issues.push({
188
+ ruleId: 'PG016',
189
+ message: 'Verify the Drizzle migration runner transaction behavior for CONCURRENTLY.',
190
+ fix: 'Use a non-transactional execution path for concurrent index operations.'
191
+ });
192
+ }
193
+
194
+ const target = ddlTarget(stmt);
195
+
196
+ if (
197
+ target &&
198
+ seen.has(target) &&
199
+ (
200
+ stmt.RenameStmt ||
201
+ stmt.DropStmt?.removeType === 'OBJECT_TABLE'
202
+ )
203
+ ) {
204
+ const previous = seen.get(target);
205
+
206
+ if (previous.file !== file) {
207
+ issues.push({
208
+ ruleId: 'PG017',
209
+ message: `Potential cross-file dependency: ${target} was modified earlier in ${previous.file}.`,
210
+ fix: 'Review migration order and deployed application compatibility; this is a heuristic, not proof of a conflict.'
211
+ });
212
+ }
213
+ }
214
+
215
+ if (target) {
216
+ seen.set(target, { file });
217
+ }
218
+
219
+ for (const issue of issues) {
220
+
221
+ const isAdvisory = ADVISORY_RULES.has(issue.ruleId);
222
+
223
+ const defaultSeverity = isAdvisory
224
+ ? 'warning'
225
+ : 'error';
226
+
227
+ const severity =
228
+ config.rules?.[issue.ruleId] ??
229
+ (isAdvisory
230
+ ? 'warning'
231
+ : (config.severity ?? defaultSeverity));
232
+
233
+
234
+ if (severity === 'off') continue;
235
+
236
+ findings.push({
237
+ ...issue,
238
+ severity,
239
+ file,
240
+ line: loc.line,
241
+ column: loc.column,
242
+ framework,
243
+ ...(options.advisor
244
+ ? { advisor: advise(issue, framework) }
245
+ : {})
246
+ });
247
+ }
248
+
249
+ if (transaction === 'end') {
250
+ inTransaction = false;
251
+ }
252
+ }
253
+ }
254
+
255
+ return findings;
256
+ }
package/src/config.js ADDED
@@ -0,0 +1,27 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export const DEFAULT_CONFIG = Object.freeze({ severity: 'error', rules: {}, exclude: [], postgresVersion: null });
5
+ export function loadConfig(file = 'pg-safe-migrate.config.json') {
6
+ if (!fs.existsSync(file)) return { ...DEFAULT_CONFIG };
7
+ let parsed;
8
+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); }
9
+ catch (e) { throw new Error(`Invalid configuration ${file}: ${e.message}`); }
10
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') throw new Error('Configuration must be a JSON object.');
11
+ if (parsed.rules !== undefined && (!parsed.rules || Array.isArray(parsed.rules) || typeof parsed.rules !== 'object')) throw new Error('rules must be an object.');
12
+ if (parsed.exclude !== undefined && (!Array.isArray(parsed.exclude) || parsed.exclude.some(x => typeof x !== 'string'))) throw new Error('exclude must be an array of strings.');
13
+ const rules = parsed.rules || {};
14
+ for (const [id, value] of Object.entries(rules)) {
15
+ if (!/^PG\d{3}$/.test(id) || !['off','warning','error'].includes(value)) throw new Error(`Invalid rule configuration: ${id}=${value}`);
16
+ }
17
+ if (parsed.severity !== undefined && !['warning','error'].includes(parsed.severity)) throw new Error('severity must be warning or error.');
18
+ if (parsed.postgresVersion != null && (!Number.isInteger(parsed.postgresVersion) || parsed.postgresVersion < 10 || parsed.postgresVersion > 99)) throw new Error('postgresVersion must be an integer >= 10.');
19
+ return { ...DEFAULT_CONFIG, ...parsed, rules };
20
+ }
21
+ export function isExcluded(file, patterns, cwd = process.cwd()) {
22
+ const rel = path.relative(cwd, path.resolve(file)).replaceAll('\\','/');
23
+ return patterns.some(pattern => {
24
+ const normalized = pattern.replaceAll('\\','/').replace(/^\.\//,'').replace(/\/$/,'');
25
+ return rel === normalized || rel.startsWith(normalized + '/') || (normalized.startsWith('*.') && rel.endsWith(normalized.slice(1)));
26
+ });
27
+ }
package/src/engine.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { additionalRules } from './rules/additionalRules.js';
1
2
  import { concurrentIndexRule } from './rules/concurrentIndex.js';
2
3
  import { dropColumnRule } from './rules/dropColumn.js';
3
4
  import { alterTableRules, renameRule } from './rules/alterTableRules.js';
@@ -6,7 +7,8 @@ const ACTIVE_RULES = [
6
7
  concurrentIndexRule,
7
8
  dropColumnRule,
8
9
  alterTableRules,
9
- renameRule
10
+ renameRule,
11
+ additionalRules
10
12
  ];
11
13
 
12
14
  export function lintStatements(stmts) {
package/src/parser.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import pgQuery from 'libpg-query';
2
2
 
3
- export async function parseSqlFile(sqlContent) {
4
- if (!sqlContent || !sqlContent.trim()) {
5
- return [];
6
- }
3
+ export async function parseSqlFile(sqlContent, options = {}) {
4
+ if (!sqlContent || !sqlContent.trim()) return [];
7
5
  try {
8
6
  const result = await pgQuery.parse(sqlContent);
9
- return (result.stmts || []).map((s) => s.stmt);
7
+ const statements = result.stmts || [];
8
+ if (!options.details) return statements.map(s => s.stmt);
9
+ return statements.map(s => ({stmt:s.stmt,offset:typeof s.stmt_location==='number'?s.stmt_location:0}));
10
10
  } catch (err) {
11
11
  throw new Error(`SQL Syntax Error: ${err.message}`);
12
12
  }
package/src/reports.js ADDED
@@ -0,0 +1,5 @@
1
+ export function toJson(findings, meta = {}) { return JSON.stringify({ tool: 'pg-safe-migrate', ...meta, findings }, null, 2); }
2
+ export function toSarif(findings) {
3
+ const ids = [...new Set(findings.map(f => f.ruleId))].sort();
4
+ return JSON.stringify({ version: '2.1.0', $schema: 'https://json.schemastore.org/sarif-2.1.0.json', runs: [{ tool: { driver: { name: 'pg-safe-migrate', informationUri: 'https://github.com/subodhsingh001/pg-safe-migrate', rules: ids.map(id => ({ id, shortDescription: { text: id } })) } }, results: findings.map(f => ({ ruleId: f.ruleId, level: f.severity === 'warning' ? 'warning' : 'error', message: { text: `${f.message} Fix: ${f.fix}` }, locations: [{ physicalLocation: { artifactLocation: { uri: f.file.replaceAll('\\','/') }, region: { startLine: Math.max(1, f.line || 1), startColumn: Math.max(1, f.column || 1) } } }] })) }] }, null, 2);
5
+ }
@@ -0,0 +1,9 @@
1
+ export const additionalRules = {
2
+ id: 'PG007-PG011',
3
+ check(stmt) {
4
+ const issues = [];
5
+ if (stmt.DropStmt?.removeType === 'OBJECT_INDEX' && !stmt.DropStmt.concurrent) issues.push({ ruleId: 'PG007', severity: 'ERROR', message: 'DROP INDEX without CONCURRENTLY can block concurrent operations.', fix: 'Consider DROP INDEX CONCURRENTLY outside a transaction (not supported with CASCADE).' });
6
+ if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') issues.push({ ruleId: 'PG011', severity: 'ERROR', message: 'DROP TABLE is destructive and may break running application versions.', fix: 'Remove application dependencies first and verify data retention requirements.' });
7
+ return issues;
8
+ }
9
+ };