@subodh001/pg-safe-migrate 2.5.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +81 -0
- package/CONTRIBUTING.md +3 -0
- package/README.md +208 -320
- package/SECURITY.md +13 -0
- package/bin/cli.js +18 -10
- package/docs/RULES.md +31 -0
- package/examples/consumer-workflow.yml +4 -17
- package/examples/suppression-gate-policy.json +11 -0
- package/package.json +6 -2
- package/src/analysis.js +69 -6
- package/src/config.js +12 -1
- package/src/locks.js +128 -12
- package/src/parser.js +46 -10
- package/src/reports.js +8 -5
- package/src/rules/ruleCatalog.js +6 -2
- package/src/suppression-matcher.js +24 -0
- package/src/suppression-report.js +19 -0
- package/src/suppression.js +78 -0
- package/src/team-policy.js +38 -2
package/bin/cli.js
CHANGED
|
@@ -13,11 +13,12 @@ import { findMigrationFiles } from '../src/detector.js';
|
|
|
13
13
|
import { getChangedSqlFiles } from '../src/gitDiff.js';
|
|
14
14
|
import { loadConfig, isExcluded } from '../src/config.js';
|
|
15
15
|
import { analyzeFiles } from '../src/analysis.js';
|
|
16
|
+
import { suppressionReport, suppressionText, suppressionMarkdown } from '../src/suppression-report.js';
|
|
16
17
|
import { toJson, toSarif, toMarkdownReport } from '../src/reports.js';
|
|
17
18
|
import { inspectDatabaseUrl } from '../src/db-inspect.js';
|
|
18
19
|
import { simulateSqlFile } from '../src/simulator.js';
|
|
19
20
|
import { combinedAssessment } from '../src/combined.js';
|
|
20
|
-
import { loadTeamPolicy, assessTeamPolicy, assessLintPolicy } from '../src/team-policy.js';
|
|
21
|
+
import { loadTeamPolicy, assessTeamPolicy, assessLintPolicy, validateGateConfig, applySuppressionPolicy, enforceSuppressionAudit } from '../src/team-policy.js';
|
|
21
22
|
import { loadProductionContext, productionAssessment } from '../src/production-context.js';
|
|
22
23
|
import { createRiskBaseline, loadRiskBaseline, compareRiskBaseline, writeRiskBaseline } from '../src/risk-baseline.js';
|
|
23
24
|
|
|
@@ -59,8 +60,10 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
|
|
|
59
60
|
config.postgresVersion=version;
|
|
60
61
|
}
|
|
61
62
|
if ((opts.gatePolicy || opts.riskBaseline || opts.writeRiskBaseline || opts.productionContext) && (opts.assess || opts.simulate || opts.migrationsDir || opts.inspectDb)) throw new Error('--gate-policy is for static lint mode only');
|
|
63
|
+
if (config.suppression?.enabled && (opts.assess || opts.teamPolicy || ((opts.riskBaseline || opts.writeRiskBaseline) && opts.gatePolicy))) throw new Error('Inline suppression is not supported with combined assessment or gate plus risk baseline');
|
|
62
64
|
if (opts.assess) {
|
|
63
65
|
const policy = opts.teamPolicy ? loadTeamPolicy(opts.teamPolicy) : null;
|
|
66
|
+
validateGateConfig(config, policy);
|
|
64
67
|
const assessment = await combinedAssessment({ file: opts.simulate, migrationsDir: opts.migrationsDir, baseline: opts.baseline, verifySql: opts.verifySql, postgresVersion: String(opts.postgresVersion ?? '16'), config });
|
|
65
68
|
if (policy) assessment.teamPolicy = assessTeamPolicy(assessment, policy);
|
|
66
69
|
if (opts.output) { fs.mkdirSync(path.dirname(path.resolve(opts.output)), {recursive:true}); fs.writeFileSync(opts.output, JSON.stringify(assessment,null,2)+'\n'); }
|
|
@@ -80,23 +83,28 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
|
|
|
80
83
|
return;
|
|
81
84
|
}
|
|
82
85
|
const gatePolicy = opts.gatePolicy ? loadTeamPolicy(opts.gatePolicy) : null;
|
|
86
|
+
validateGateConfig(config, gatePolicy);
|
|
83
87
|
if (gatePolicy?.requireSimulation) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
|
|
84
88
|
const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
|
|
85
89
|
const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
|
|
86
|
-
const
|
|
87
|
-
const
|
|
90
|
+
const suppressionAudit = [];
|
|
91
|
+
const findings=await analyzeFiles(entries,applySuppressionPolicy(config, gatePolicy),{advisor:opts.advisor,suppressionAudit});
|
|
92
|
+
const suppression = config.suppression?.enabled ? suppressionReport(suppressionAudit) : undefined;
|
|
93
|
+
const allFindings = [...findings, ...suppressionAudit.filter(r => r.status === 'suppressed').map(r => r.finding)];
|
|
94
|
+
const production = opts.productionContext ? productionAssessment(allFindings, loadProductionContext(opts.productionContext)) : null;
|
|
88
95
|
if (opts.writeRiskBaseline && opts.riskBaseline) throw new Error('Cannot combine --write-risk-baseline and --risk-baseline');
|
|
89
96
|
if (opts.writeRiskBaseline && opts.gatePolicy) throw new Error('Baseline creation cannot be combined with a gate policy');
|
|
90
|
-
const baselineComparison = opts.riskBaseline ? compareRiskBaseline(
|
|
97
|
+
const baselineComparison = opts.riskBaseline ? compareRiskBaseline(allFindings, entries, loadRiskBaseline(opts.riskBaseline)) : null;
|
|
91
98
|
// In baseline mode, only newly introduced findings are subject to the opt-in gate.
|
|
92
99
|
const gateFindings = baselineComparison ? baselineComparison.newFindings : findings;
|
|
93
|
-
const gate = opts.gatePolicy ? assessLintPolicy(gateFindings, gatePolicy, summarizeRisk(gateFindings)) : null;
|
|
94
|
-
if (opts.writeRiskBaseline) writeRiskBaseline(opts.writeRiskBaseline, createRiskBaseline(
|
|
100
|
+
const gate = opts.gatePolicy ? enforceSuppressionAudit(assessLintPolicy(suppression ? allFindings : gateFindings, gatePolicy, summarizeRisk(suppression ? allFindings : gateFindings)), gatePolicy, suppression) : null;
|
|
101
|
+
if (opts.writeRiskBaseline) writeRiskBaseline(opts.writeRiskBaseline, createRiskBaseline(allFindings, entries));
|
|
95
102
|
if (opts.github) process.stdout.write(toGitHubAnnotations(findings));
|
|
96
|
-
if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length));}
|
|
97
|
-
const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion}):opts.format==='sarif'?toSarif(findings):opts.format==='markdown'?toMarkdownReport(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,risk:opts.risk?summarizeRisk(
|
|
103
|
+
if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length) + (suppression ? suppressionMarkdown(suppression) : ''));}
|
|
104
|
+
const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,...(suppression ? { suppression } : {})}):opts.format==='sarif'?toSarif(findings,suppression):opts.format==='markdown'?toMarkdownReport(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,risk:opts.risk?summarizeRisk(allFindings):undefined,suppression}):[
|
|
98
105
|
...findings.flatMap(f=>[`${f.file}:${f.line}:${f.column} [${f.ruleId}] ${f.severity}: ${f.message}`,` Fix: ${f.fix}`,...(f.advisor?f.advisor.steps.map((s,i)=>` ${i+1}. ${s}`):[])]),
|
|
99
|
-
...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(
|
|
106
|
+
...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(allFindings))}`]:[]),
|
|
107
|
+
...(suppression ? [suppressionText(suppression)] : []),
|
|
100
108
|
`Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
|
|
101
109
|
].join('\n');
|
|
102
110
|
const gateReport = opts.format === 'json' && (gate || baselineComparison || production) ? JSON.stringify({ ...JSON.parse(report), ...(baselineComparison ? { baseline: { newCount: baselineComparison.newCount, existingCount: baselineComparison.existingCount, resolvedCount: baselineComparison.resolvedCount, newFindings: baselineComparison.newFindings } } : {}), ...(production ? { production } : {}), ...(gate ? { gate: { name: gate.name, decision: gate.passed ? 'PASS' : 'BLOCK', passed: gate.passed, reasons: gate.reasons, note: gate.note } } : {}) }, null, 2) : report;
|
|
@@ -104,7 +112,7 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
|
|
|
104
112
|
else console.log(opts.format==='text'?(findings.length?chalk.yellow(gateReport):chalk.green(gateReport)):gateReport);
|
|
105
113
|
if (production && opts.format !== 'json') console.error(`[PG Safe Migrate production] Advisory context evaluated for ${production.assessments.length} finding(s). Use --format json for details. No downtime guarantee.`);
|
|
106
114
|
if (baselineComparison && opts.format !== 'json') console.error(`[PG Safe Migrate baseline] ${baselineComparison.newCount} new, ${baselineComparison.existingCount} existing, ${baselineComparison.resolvedCount} resolved finding(s).`);
|
|
107
|
-
if (opts.writeRiskBaseline) console.error(`[PG Safe Migrate baseline] Wrote ${
|
|
115
|
+
if (opts.writeRiskBaseline) console.error(`[PG Safe Migrate baseline] Wrote ${allFindings.length} finding fingerprint(s) to ${opts.writeRiskBaseline}; review before committing.`);
|
|
108
116
|
if (gate) console.error(`[PG Safe Migrate gate] ${gate.passed ? 'PASS' : 'BLOCK'} (${gate.name})${gate.reasons.length ? ': '+gate.reasons.join('; ') : ''}. ${gate.note}`);
|
|
109
117
|
process.exitCode=(gate && !gate.passed) || (opts.failOn==='warning' && gateFindings.length>0) || (opts.failOn==='error' && gateFindings.some(f=>f.severity==='error')) ? 1 : 0;
|
|
110
118
|
}catch(e){console.error(`Error: ${e.message}`);process.exitCode=2;}
|
package/docs/RULES.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Rule reference (development branch)
|
|
2
|
+
|
|
3
|
+
23 catalog identifiers, including legacy PG013; PG009 and PG018 are unused. PG013 is suppressed when PG025 is emitted. PG019 and PG020 require a target version below 15; PG014 targets PostgreSQL 10. Defaults below describe CLI reporting, not raw engine metadata. Catalog `defaultSeverity` preserves raw rule metadata; `defaultCliSeverity` describes default CLI reporting. PG024 and PG025 are raw warnings but CLI errors by default.
|
|
4
|
+
|
|
5
|
+
| ID | Diagnostic | Default | Guidance |
|
|
6
|
+
|---|---|---|---|
|
|
7
|
+
| PG001 | Non-concurrent index creation | error | Use CREATE INDEX CONCURRENTLY outside a transaction. |
|
|
8
|
+
| PG002 | Dropping a column | error | Deprecate consumers before removing the column. |
|
|
9
|
+
| PG003 | Changing a column type | error | Check binary compatibility; consider expand/backfill/contract. |
|
|
10
|
+
| PG004 | Adding NOT NULL column without default | error | Add nullable, backfill, then enforce NOT NULL. |
|
|
11
|
+
| PG005 | Adding validated foreign key | error | Add NOT VALID then VALIDATE CONSTRAINT separately. |
|
|
12
|
+
| PG006 | Renaming an object | error | Use an expand/contract deployment. |
|
|
13
|
+
| PG007 | Dropping index without CONCURRENTLY | error | Use DROP INDEX CONCURRENTLY where supported. |
|
|
14
|
+
| PG008 | Concurrent index operation inside transaction | error | Run outside BEGIN/COMMIT. |
|
|
15
|
+
| PG010 | Adding UNIQUE constraint | error | Consider a concurrent unique index and attach it where applicable. |
|
|
16
|
+
| PG011 | Dropping a table | error | Verify retention and application dependencies. |
|
|
17
|
+
| PG012 | Adding validated CHECK constraint | error | Add NOT VALID and validate separately. |
|
|
18
|
+
| PG013 | Legacy SET NOT NULL diagnostic (superseded by PG025) | error | Validate an equivalent CHECK constraint first. |
|
|
19
|
+
| PG014 | Adding column with default on PostgreSQL 10 | error | Use controlled backfill or evaluate upgrading PostgreSQL. |
|
|
20
|
+
| PG015 | Prisma concurrent index migration | warning | Use a separately managed nontransactional migration. |
|
|
21
|
+
| PG016 | Drizzle concurrent index migration | warning | Use a separately managed nontransactional migration. |
|
|
22
|
+
| PG017 | Potential cross-file dependency or Flyway transaction advisory | warning | Review migration order; this is a heuristic. |
|
|
23
|
+
| PG019 | MERGE requires PostgreSQL 15+ | error | Use a compatible INSERT ... ON CONFLICT pattern where applicable. |
|
|
24
|
+
| PG020 | UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+ | error | Use a version-compatible uniqueness strategy. |
|
|
25
|
+
| PG021 | Volatile default may rewrite table | error | Add column, backfill in batches, then set default. |
|
|
26
|
+
| PG022 | SET LOGGED rewrites table | error | Schedule controlled maintenance and evaluate alternatives. |
|
|
27
|
+
| PG023 | TRUNCATE removes table rows | error | Confirm retention, backups and downstream dependencies. |
|
|
28
|
+
| PG024 | Dropping a constraint | error | Review dependent queries and data-integrity requirements. |
|
|
29
|
+
| PG025 | SET NOT NULL may scan table | error | Backfill and validate a CHECK constraint first where appropriate. |
|
|
30
|
+
|
|
31
|
+
PG017 also covers Flyway nontransactional execution advice. Rules are configurable using `rules` with `off`, `warning`, or `error`. Static findings are not a downtime guarantee.
|
|
@@ -5,7 +5,6 @@ on:
|
|
|
5
5
|
- '**/*.sql'
|
|
6
6
|
permissions:
|
|
7
7
|
contents: read
|
|
8
|
-
security-events: write
|
|
9
8
|
jobs:
|
|
10
9
|
migrations:
|
|
11
10
|
runs-on: ubuntu-latest
|
|
@@ -13,23 +12,11 @@ jobs:
|
|
|
13
12
|
- uses: actions/checkout@v4
|
|
14
13
|
with:
|
|
15
14
|
fetch-depth: 0
|
|
15
|
+
persist-credentials: false
|
|
16
16
|
- uses: actions/setup-node@v4
|
|
17
17
|
with:
|
|
18
|
-
node-version: '
|
|
19
|
-
- name:
|
|
20
|
-
run: npm install --no-save --package-lock=false @subodh001/pg-safe-migrate@2.0.0-rc.2
|
|
21
|
-
- name: Analyze changed migrations and create SARIF
|
|
22
|
-
if: github.event_name == 'pull_request'
|
|
18
|
+
node-version: '22'
|
|
19
|
+
- name: Check changed SQL
|
|
23
20
|
env:
|
|
24
21
|
BASE_REF: ${{ github.base_ref }}
|
|
25
|
-
run:
|
|
26
|
-
npx pg-safe-migrate --changed "origin/$BASE_REF" --format sarif --output pg-safe-migrate.sarif --fail-on none
|
|
27
|
-
- name: Upload code scanning report
|
|
28
|
-
if: always() && hashFiles('pg-safe-migrate.sarif') != ''
|
|
29
|
-
uses: github/codeql-action/upload-sarif@v3
|
|
30
|
-
with:
|
|
31
|
-
sarif_file: pg-safe-migrate.sarif
|
|
32
|
-
- name: Enforce migration policy
|
|
33
|
-
env:
|
|
34
|
-
BASE_REF: ${{ github.base_ref }}
|
|
35
|
-
run: npx pg-safe-migrate --changed "origin/$BASE_REF" --fail-on error
|
|
22
|
+
run: npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --changed "origin/$BASE_REF" --fail-on error
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@subodh001/pg-safe-migrate",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.0",
|
|
4
4
|
"description": "Detect risky PostgreSQL schema migrations before deployment: SQL linting, lock analysis, risk scoring and CI reports for Prisma, Drizzle and Flyway",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -52,7 +52,11 @@
|
|
|
52
52
|
"scripts/orm-runner/package.json",
|
|
53
53
|
"scripts/orm-runner/package-lock.json",
|
|
54
54
|
"scripts/orm-runner/README.md",
|
|
55
|
-
"ALL-MILESTONES-TESTING.md"
|
|
55
|
+
"ALL-MILESTONES-TESTING.md",
|
|
56
|
+
"CHANGELOG.md",
|
|
57
|
+
"SECURITY.md",
|
|
58
|
+
"CONTRIBUTING.md",
|
|
59
|
+
"docs/RULES.md"
|
|
56
60
|
],
|
|
57
61
|
"repository": {
|
|
58
62
|
"type": "git",
|
package/src/analysis.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
|
|
2
1
|
import { parseSqlFile } from './parser.js';
|
|
3
2
|
import { lintStatements } from './engine.js';
|
|
4
3
|
import { advise } from './advisor.js';
|
|
5
4
|
import { lockFor } from './locks.js';
|
|
5
|
+
import { normalizeSuppression } from './config.js';
|
|
6
|
+
import { matchSuppressions } from './suppression-matcher.js';
|
|
6
7
|
|
|
7
8
|
const ADVISORY_RULES = new Set(['PG015', 'PG016', 'PG017']);
|
|
8
9
|
|
|
@@ -26,6 +27,46 @@ export function position(sql, offset = 0) {
|
|
|
26
27
|
};
|
|
27
28
|
}
|
|
28
29
|
|
|
30
|
+
|
|
31
|
+
function createPositionTracker(sql) {
|
|
32
|
+
const source = String(sql ?? '');
|
|
33
|
+
|
|
34
|
+
let cursor = 0;
|
|
35
|
+
let line = 1;
|
|
36
|
+
let lineStart = 0;
|
|
37
|
+
|
|
38
|
+
return function locate(offset = 0) {
|
|
39
|
+
const numericOffset = Number(offset);
|
|
40
|
+
|
|
41
|
+
const safeOffset = Number.isFinite(numericOffset)
|
|
42
|
+
? Math.min(
|
|
43
|
+
source.length,
|
|
44
|
+
Math.max(0, Math.floor(numericOffset))
|
|
45
|
+
)
|
|
46
|
+
: 0;
|
|
47
|
+
|
|
48
|
+
// Preserve correctness if offsets arrive out of order.
|
|
49
|
+
if (safeOffset < cursor) {
|
|
50
|
+
return position(source, safeOffset);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
while (cursor < safeOffset) {
|
|
54
|
+
if (source.charCodeAt(cursor) === 10) {
|
|
55
|
+
line++;
|
|
56
|
+
lineStart = cursor + 1;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
cursor++;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
line,
|
|
64
|
+
column: safeOffset - lineStart + 1
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
29
70
|
export function frameworkFor(file) {
|
|
30
71
|
const p = file.replaceAll('\\', '/').toLowerCase();
|
|
31
72
|
|
|
@@ -57,7 +98,6 @@ function txType(stmt) {
|
|
|
57
98
|
if ([
|
|
58
99
|
'TRANS_STMT_COMMIT',
|
|
59
100
|
'TRANS_STMT_ROLLBACK',
|
|
60
|
-
'TRANS_STMT_ROLLBACK_TO',
|
|
61
101
|
'TRANS_STMT_PREPARE'
|
|
62
102
|
].includes(kind)) {
|
|
63
103
|
return 'end';
|
|
@@ -171,6 +211,9 @@ export async function analyzeFiles(
|
|
|
171
211
|
options = {}
|
|
172
212
|
) {
|
|
173
213
|
const findings = [];
|
|
214
|
+
const policy = normalizeSuppression(config.suppression);
|
|
215
|
+
const audit = options.suppressionAudit;
|
|
216
|
+
if (policy.enabled && !Array.isArray(audit)) throw new Error('Enabled suppression requires an audit sink');
|
|
174
217
|
const seen = new Map();
|
|
175
218
|
|
|
176
219
|
const version = config.postgresVersion ?? null;
|
|
@@ -184,12 +227,24 @@ export async function analyzeFiles(
|
|
|
184
227
|
details: true
|
|
185
228
|
});
|
|
186
229
|
|
|
230
|
+
const candidates = new Map();
|
|
231
|
+
if (policy.enabled) {
|
|
232
|
+
const result = await matchSuppressions(sql, parsed);
|
|
233
|
+
if (result.scanError) audit.push({ file, status: 'scan-error', ...result.scanError });
|
|
234
|
+
for (const rejected of result.rejected) audit.push({ file, status: 'rejected', ...rejected });
|
|
235
|
+
for (const match of result.matches) {
|
|
236
|
+
if (match.ruleIds.some(id => policy.protectedRules.includes(id))) {
|
|
237
|
+
audit.push({ file, status: 'rejected', ...match, message: 'Directive includes a protected rule' });
|
|
238
|
+
} else candidates.set(match.statementOffset, { match, used: new Set() });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
187
241
|
const framework = frameworkFor(file);
|
|
242
|
+
const locate = createPositionTracker(sql);
|
|
188
243
|
|
|
189
244
|
let inTransaction = false;
|
|
190
245
|
|
|
191
246
|
for (const { stmt, offset } of parsed) {
|
|
192
|
-
const loc =
|
|
247
|
+
const loc = locate(offset);
|
|
193
248
|
const transaction = txType(stmt);
|
|
194
249
|
|
|
195
250
|
// Track explicit transaction boundaries.
|
|
@@ -321,7 +376,7 @@ export async function analyzeFiles(
|
|
|
321
376
|
continue;
|
|
322
377
|
}
|
|
323
378
|
|
|
324
|
-
|
|
379
|
+
const finding = {
|
|
325
380
|
...issue,
|
|
326
381
|
severity,
|
|
327
382
|
file,
|
|
@@ -334,14 +389,22 @@ export async function analyzeFiles(
|
|
|
334
389
|
advisor: advise(issue, framework)
|
|
335
390
|
}
|
|
336
391
|
: {})
|
|
337
|
-
}
|
|
392
|
+
};
|
|
393
|
+
const candidate = candidates.get(offset);
|
|
394
|
+
if (candidate?.match.ruleIds.includes(issue.ruleId)) {
|
|
395
|
+
candidate.used.add(issue.ruleId);
|
|
396
|
+
audit.push({ file, status: 'suppressed', directiveLine: candidate.match.line, reason: candidate.match.reason, finding });
|
|
397
|
+
} else findings.push(finding);
|
|
338
398
|
}
|
|
339
399
|
|
|
340
400
|
// Close the explicit transaction after processing.
|
|
341
401
|
if (transaction === 'end') {
|
|
342
|
-
inTransaction =
|
|
402
|
+
inTransaction = Boolean(stmt.TransactionStmt?.chain);
|
|
343
403
|
}
|
|
344
404
|
}
|
|
405
|
+
for (const { match, used } of candidates.values()) {
|
|
406
|
+
for (const ruleId of match.ruleIds) if (!used.has(ruleId)) audit.push({ file, status: 'unused', ruleId, directiveLine: match.line, reason: match.reason });
|
|
407
|
+
}
|
|
345
408
|
}
|
|
346
409
|
|
|
347
410
|
return findings;
|
package/src/config.js
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { getRule } from './rules/ruleCatalog.js';
|
|
4
|
+
|
|
5
|
+
export function normalizeSuppression(value = {}) {
|
|
6
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('suppression must be an object');
|
|
7
|
+
for (const key of Object.keys(value)) if (!['enabled','requireReason','reportSuppressed','protectedRules'].includes(key)) throw new Error(`Unknown suppression option: ${key}`);
|
|
8
|
+
if (value.enabled !== undefined && typeof value.enabled !== 'boolean') throw new Error('suppression.enabled must be boolean');
|
|
9
|
+
for (const key of ['requireReason','reportSuppressed']) if (value[key] !== undefined && value[key] !== true) throw new Error(`suppression.${key} must be true in this development version`);
|
|
10
|
+
const protectedRules = value.protectedRules === undefined ? ['PG011','PG023'] : value.protectedRules;
|
|
11
|
+
if (!Array.isArray(protectedRules) || protectedRules.some(id => typeof id !== 'string' || !/^PG\d{3}$/.test(id) || !getRule(id))) throw new Error('suppression.protectedRules must contain known rule IDs');
|
|
12
|
+
return { enabled: value.enabled ?? false, requireReason: true, reportSuppressed: true, protectedRules: [...new Set(protectedRules)] };
|
|
13
|
+
}
|
|
3
14
|
|
|
4
15
|
export const DEFAULT_CONFIG = Object.freeze({ severity: 'error', rules: {}, exclude: [], postgresVersion: null });
|
|
5
16
|
export function loadConfig(file = 'pg-safe-migrate.config.json') {
|
|
@@ -16,7 +27,7 @@ export function loadConfig(file = 'pg-safe-migrate.config.json') {
|
|
|
16
27
|
}
|
|
17
28
|
if (parsed.severity !== undefined && !['warning','error'].includes(parsed.severity)) throw new Error('severity must be warning or error.');
|
|
18
29
|
if (parsed.postgresVersion != null && (!Number.isInteger(parsed.postgresVersion) || parsed.postgresVersion < 10 || parsed.postgresVersion > 99)) throw new Error('postgresVersion must be an integer >= 10.');
|
|
19
|
-
return { ...DEFAULT_CONFIG, ...parsed, rules };
|
|
30
|
+
return { ...DEFAULT_CONFIG, ...parsed, rules, suppression: normalizeSuppression(parsed.suppression) };
|
|
20
31
|
}
|
|
21
32
|
export function isExcluded(file, patterns, cwd = process.cwd()) {
|
|
22
33
|
const rel = path.relative(cwd, path.resolve(file)).replaceAll('\\','/');
|
package/src/locks.js
CHANGED
|
@@ -1,18 +1,134 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
1
|
+
|
|
2
|
+
// PostgreSQL table-lock planning hints.
|
|
3
|
+
// These are not predictions of wait time, duration, or downtime.
|
|
4
|
+
|
|
3
5
|
function assessment(mode, impact, note, confidence = 'heuristic') {
|
|
4
6
|
return { mode, confidence, impact, note };
|
|
5
7
|
}
|
|
6
8
|
|
|
9
|
+
function alterTableLock(alter) {
|
|
10
|
+
const commands = (alter.cmds || [])
|
|
11
|
+
.map(wrapper => wrapper.AlterTableCmd)
|
|
12
|
+
.filter(Boolean);
|
|
13
|
+
|
|
14
|
+
// A statement may contain multiple subcommands.
|
|
15
|
+
// Do not classify a mixed statement using only its weakest lock.
|
|
16
|
+
if (commands.length === 0) {
|
|
17
|
+
return assessment(
|
|
18
|
+
'ACCESS EXCLUSIVE',
|
|
19
|
+
'reads-and-writes',
|
|
20
|
+
'ALTER TABLE lock requirements depend on its subcommands.'
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const modes = commands.map(cmd => {
|
|
25
|
+
if (
|
|
26
|
+
cmd.subtype === 'AT_AddConstraint' &&
|
|
27
|
+
cmd.def?.Constraint?.contype === 'CONSTR_FOREIGN'
|
|
28
|
+
) {
|
|
29
|
+
return 'SHARE ROW EXCLUSIVE';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (cmd.subtype === 'AT_ValidateConstraint') {
|
|
33
|
+
return 'SHARE UPDATE EXCLUSIVE';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return 'ACCESS EXCLUSIVE';
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
if (modes.every(mode => mode === 'SHARE ROW EXCLUSIVE')) {
|
|
40
|
+
return assessment(
|
|
41
|
+
'SHARE ROW EXCLUSIVE',
|
|
42
|
+
'writes',
|
|
43
|
+
'ADD FOREIGN KEY acquires SHARE ROW EXCLUSIVE on both referencing and referenced tables. NOT VALID avoids the initial scan but not the lock.',
|
|
44
|
+
'documented'
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (modes.every(mode => mode === 'SHARE UPDATE EXCLUSIVE')) {
|
|
49
|
+
return assessment(
|
|
50
|
+
'SHARE UPDATE EXCLUSIVE',
|
|
51
|
+
'ddl-and-maintenance',
|
|
52
|
+
'VALIDATE CONSTRAINT generally uses SHARE UPDATE EXCLUSIVE on the altered table. Foreign-key validation can also lock the referenced table.',
|
|
53
|
+
'documented'
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return assessment(
|
|
58
|
+
'ACCESS EXCLUSIVE',
|
|
59
|
+
'reads-and-writes',
|
|
60
|
+
'ALTER TABLE contains a subcommand requiring ACCESS EXCLUSIVE, or a subcommand whose lock has not been specifically classified.'
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
7
64
|
export function lockFor(stmt) {
|
|
8
|
-
if (stmt.TruncateStmt)
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
65
|
+
if (stmt.TruncateStmt) {
|
|
66
|
+
return assessment(
|
|
67
|
+
'ACCESS EXCLUSIVE',
|
|
68
|
+
'reads-and-writes',
|
|
69
|
+
'TRUNCATE acquires ACCESS EXCLUSIVE on affected tables and can block readers and writers.',
|
|
70
|
+
'documented'
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (stmt.AlterTableStmt) {
|
|
75
|
+
return alterTableLock(stmt.AlterTableStmt);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') {
|
|
79
|
+
return assessment(
|
|
80
|
+
'ACCESS EXCLUSIVE',
|
|
81
|
+
'reads-and-writes',
|
|
82
|
+
'DROP TABLE requires ACCESS EXCLUSIVE on the target table.',
|
|
83
|
+
'documented'
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (stmt.RenameStmt) {
|
|
88
|
+
return assessment(
|
|
89
|
+
'ACCESS EXCLUSIVE',
|
|
90
|
+
'reads-and-writes',
|
|
91
|
+
'Rename operations can require strong locks; verify the specific object and operation.'
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (stmt.IndexStmt) {
|
|
96
|
+
return stmt.IndexStmt.concurrent
|
|
97
|
+
? assessment(
|
|
98
|
+
'SHARE UPDATE EXCLUSIVE',
|
|
99
|
+
'ddl-and-maintenance',
|
|
100
|
+
'CREATE INDEX CONCURRENTLY permits ordinary writes but can wait for transactions and conflict with some maintenance.',
|
|
101
|
+
'documented'
|
|
102
|
+
)
|
|
103
|
+
: assessment(
|
|
104
|
+
'SHARE',
|
|
105
|
+
'writes',
|
|
106
|
+
'CREATE INDEX without CONCURRENTLY can block writes while the index is built.',
|
|
107
|
+
'documented'
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (stmt.VacuumStmt) {
|
|
112
|
+
return assessment(
|
|
113
|
+
'SHARE UPDATE EXCLUSIVE',
|
|
114
|
+
'ddl-and-maintenance',
|
|
115
|
+
'Ordinary VACUUM uses SHARE UPDATE EXCLUSIVE; VACUUM FULL uses ACCESS EXCLUSIVE. Verify the options.'
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (stmt.UpdateStmt || stmt.DeleteStmt || stmt.InsertStmt) {
|
|
120
|
+
return assessment(
|
|
121
|
+
'ROW EXCLUSIVE',
|
|
122
|
+
'conflicting-writers-and-ddl',
|
|
123
|
+
'DML acquires ROW EXCLUSIVE table locks; row-level contention and execution time are not assessed.',
|
|
124
|
+
'documented'
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return assessment(
|
|
129
|
+
'unknown',
|
|
130
|
+
'unknown',
|
|
131
|
+
'Lock mode not classified; do not assume this operation is lock-free.',
|
|
132
|
+
'unknown'
|
|
133
|
+
);
|
|
18
134
|
}
|
package/src/parser.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
import pgQuery from 'libpg-query';
|
|
3
2
|
|
|
4
3
|
export async function parseSqlFile(sqlContent, options = {}) {
|
|
@@ -16,6 +15,22 @@ export async function parseSqlFile(sqlContent, options = {}) {
|
|
|
16
15
|
|
|
17
16
|
const source = String(sqlContent);
|
|
18
17
|
|
|
18
|
+
// Convert ordered PostgreSQL UTF-8 byte locations to UTF-16 offsets.
|
|
19
|
+
const byteLength = Buffer.byteLength(source);
|
|
20
|
+
let byteCursor = 0;
|
|
21
|
+
let charCursor = 0;
|
|
22
|
+
function locateByte(target) {
|
|
23
|
+
if (target < byteCursor) { byteCursor = 0; charCursor = 0; }
|
|
24
|
+
while (byteCursor < target && charCursor < source.length) {
|
|
25
|
+
const cp = source.codePointAt(charCursor);
|
|
26
|
+
const width = cp <= 0x7f ? 1 : cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4;
|
|
27
|
+
if (byteCursor + width > target) break;
|
|
28
|
+
byteCursor += width;
|
|
29
|
+
charCursor += cp > 0xffff ? 2 : 1;
|
|
30
|
+
}
|
|
31
|
+
return charCursor;
|
|
32
|
+
}
|
|
33
|
+
|
|
19
34
|
return statements.map(s => {
|
|
20
35
|
let offset =
|
|
21
36
|
typeof s.stmt_location === 'number'
|
|
@@ -24,17 +39,38 @@ export async function parseSqlFile(sqlContent, options = {}) {
|
|
|
24
39
|
|
|
25
40
|
offset = Math.max(
|
|
26
41
|
0,
|
|
27
|
-
Math.min(offset,
|
|
42
|
+
Math.min(offset, byteLength)
|
|
28
43
|
);
|
|
29
44
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
//
|
|
33
|
-
while (
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
45
|
+
offset = locateByte(offset);
|
|
46
|
+
|
|
47
|
+
// Skip only leading SQL trivia, never statement contents.
|
|
48
|
+
while (offset < source.length) {
|
|
49
|
+
if (/[ \t\r\n\f\v]/.test(source[offset])) {
|
|
50
|
+
offset++;
|
|
51
|
+
} else if (source.startsWith('--', offset)) {
|
|
52
|
+
offset += 2;
|
|
53
|
+
while (offset < source.length &&
|
|
54
|
+
source[offset] !== '\n' && source[offset] !== '\r') {
|
|
55
|
+
offset++;
|
|
56
|
+
}
|
|
57
|
+
} else if (source.startsWith('/*', offset)) {
|
|
58
|
+
offset += 2;
|
|
59
|
+
let depth = 1;
|
|
60
|
+
while (offset < source.length && depth > 0) {
|
|
61
|
+
if (source.startsWith('/*', offset)) {
|
|
62
|
+
depth++;
|
|
63
|
+
offset += 2;
|
|
64
|
+
} else if (source.startsWith('*/', offset)) {
|
|
65
|
+
depth--;
|
|
66
|
+
offset += 2;
|
|
67
|
+
} else {
|
|
68
|
+
offset++;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
38
74
|
}
|
|
39
75
|
|
|
40
76
|
return {
|
package/src/reports.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
|
+
import { suppressionMarkdown } from './suppression-report.js';
|
|
1
2
|
export function toJson(findings, meta = {}) { return JSON.stringify({ tool: 'pg-safe-migrate', ...meta, findings }, null, 2); }
|
|
2
|
-
export function toSarif(findings) {
|
|
3
|
-
const
|
|
4
|
-
|
|
3
|
+
export function toSarif(findings, audit) {
|
|
4
|
+
const suppressed = audit?.records.filter(r => r.status === 'suppressed') ?? [];
|
|
5
|
+
const all = [...findings, ...suppressed.map(r => r.finding)];
|
|
6
|
+
const ids = [...new Set(all.map(f => f.ruleId))].sort();
|
|
7
|
+
return JSON.stringify({ version: '2.1.0', $schema: 'https://json.schemastore.org/sarif-2.1.0.json', runs: [{ tool: { driver: { name: 'pg-safe-migrate', informationUri: 'https://github.com/subodhsingh001/pg-safe-migrate', rules: ids.map(id => ({ id, shortDescription: { text: id } })) } }, ...(audit ? { properties: { suppression: audit } } : {}), results: all.map((f, i) => ({ ...(i >= findings.length ? { suppressions: [{ kind: 'inSource', justification: suppressed[i - findings.length].reason }] } : {}), ruleId: f.ruleId, level: f.severity === 'warning' ? 'warning' : 'error', message: { text: `${f.message} Fix: ${f.fix}` }, locations: [{ physicalLocation: { artifactLocation: { uri: f.file.replaceAll('\\','/') }, region: { startLine: Math.max(1, f.line || 1), startColumn: Math.max(1, f.column || 1) } } }] })) }] }, null, 2);
|
|
5
8
|
}
|
|
6
9
|
|
|
7
10
|
// Human-readable report. Escapes Markdown cells and never includes untrusted HTML.
|
|
8
11
|
const mdCell = value => String(value ?? '').replace(/\r?\n/g, ' ').replace(/\|/g, '\\|').replace(/</g, '<').replace(/>/g, '>');
|
|
9
|
-
export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVersion, risk } = {}) {
|
|
12
|
+
export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVersion, risk, suppression } = {}) {
|
|
10
13
|
const errors = findings.filter(f => f.severity === 'error').length;
|
|
11
14
|
const warnings = findings.filter(f => f.severity === 'warning').length;
|
|
12
15
|
const lines = [
|
|
@@ -31,5 +34,5 @@ export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVers
|
|
|
31
34
|
lines.push('');
|
|
32
35
|
}
|
|
33
36
|
lines.push('> Static analysis is advisory. Review locks, data volume, transaction behavior, and production workload before deployment.', '');
|
|
34
|
-
return lines.join('\n');
|
|
37
|
+
return lines.join('\n') + (suppression ? suppressionMarkdown(suppression) : '');
|
|
35
38
|
}
|
package/src/rules/ruleCatalog.js
CHANGED
|
@@ -8,10 +8,14 @@ const definitions = [
|
|
|
8
8
|
['PG006','Renaming an object','compatibility','ERROR',null,'Use an expand/contract deployment.'],
|
|
9
9
|
['PG007','Dropping index without CONCURRENTLY','locking','ERROR',null,'Use DROP INDEX CONCURRENTLY where supported.'],
|
|
10
10
|
['PG008','Concurrent index operation inside transaction','compatibility','ERROR',null,'Run outside BEGIN/COMMIT.'],
|
|
11
|
+
['PG010','Adding UNIQUE constraint','locking','ERROR',null,'Consider a concurrent unique index and attach it where applicable.'],
|
|
11
12
|
['PG011','Dropping a table','data-loss','ERROR',null,'Verify retention and application dependencies.'],
|
|
13
|
+
['PG012','Adding validated CHECK constraint','constraint','ERROR',null,'Add NOT VALID and validate separately.'],
|
|
14
|
+
['PG013','Legacy SET NOT NULL diagnostic (superseded by PG025)','constraint','ERROR',null,'Validate an equivalent CHECK constraint first.'],
|
|
15
|
+
['PG014','Adding column with default on PostgreSQL 10','rewrite','ERROR',null,'Use controlled backfill or evaluate upgrading PostgreSQL.'],
|
|
12
16
|
['PG015','Prisma concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
|
|
13
17
|
['PG016','Drizzle concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
|
|
14
|
-
['PG017','Potential cross-file dependency','dependency','WARNING',null,'Review migration order; this is a heuristic.'],
|
|
18
|
+
['PG017','Potential cross-file dependency or Flyway transaction advisory','dependency','WARNING',null,'Review migration order; this is a heuristic.'],
|
|
15
19
|
['PG019','MERGE requires PostgreSQL 15+','version','ERROR',15,'Use a compatible INSERT ... ON CONFLICT pattern where applicable.'],
|
|
16
20
|
['PG020','UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+','version','ERROR',15,'Use a version-compatible uniqueness strategy.'],
|
|
17
21
|
['PG021','Volatile default may rewrite table','rewrite','ERROR',null,'Add column, backfill in batches, then set default.'],
|
|
@@ -21,7 +25,7 @@ const definitions = [
|
|
|
21
25
|
['PG025','SET NOT NULL may scan table','constraint','WARNING',null,'Backfill and validate a CHECK constraint first where appropriate.']
|
|
22
26
|
];
|
|
23
27
|
|
|
24
|
-
export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,minPostgresVersion,recommendation})));
|
|
28
|
+
export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,defaultCliSeverity: ['PG024','PG025'].includes(id) ? 'ERROR' : defaultSeverity,minPostgresVersion,recommendation})));
|
|
25
29
|
|
|
26
30
|
export function getRule(id) {
|
|
27
31
|
return RULE_CATALOG.find(rule => rule.id === String(id).toUpperCase()) ?? null;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { parseSqlFile } from './parser.js';
|
|
2
|
+
import { scanSuppressions } from './suppression.js';
|
|
3
|
+
import { getRule } from './rules/ruleCatalog.js';
|
|
4
|
+
|
|
5
|
+
// Preview only: no findings are removed and no CLI policy is changed.
|
|
6
|
+
export async function matchSuppressions(sql, parsed) {
|
|
7
|
+
const statements = parsed ?? await parseSqlFile(sql, { details: true });
|
|
8
|
+
const scan = scanSuppressions(sql);
|
|
9
|
+
const matches = [], rejected = [...scan.invalid];
|
|
10
|
+
let index = 0;
|
|
11
|
+
for (const directive of scan.directives) {
|
|
12
|
+
while (index < statements.length && statements[index].offset < directive.endOffset) index++;
|
|
13
|
+
const target = statements[index];
|
|
14
|
+
let message;
|
|
15
|
+
if (!directive.reason) message = 'Suppression reason required';
|
|
16
|
+
else if (directive.ruleIds.some(id => !getRule(id))) message = 'Unknown rule ID';
|
|
17
|
+
else if (!target || !/^[ \t\r\n]*$/.test(sql.slice(directive.endOffset, target.offset))) message = 'No immediately following statement';
|
|
18
|
+
// A comment inside a statement cannot bind across its terminating semicolon:
|
|
19
|
+
// the whitespace-only gap above rejects that semicolon and all SQL tokens.
|
|
20
|
+
if (message) rejected.push({ ...directive, message });
|
|
21
|
+
else matches.push({ ...directive, statementIndex: index, statementOffset: target.offset });
|
|
22
|
+
}
|
|
23
|
+
return { matches, rejected, scanError: scan.scanError };
|
|
24
|
+
}
|