pgsafe 2.7.0 → 2.7.1

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.
Files changed (58) hide show
  1. package/ALL-MILESTONES-TESTING.md +41 -0
  2. package/CHANGELOG.md +88 -0
  3. package/CONTRIBUTING.md +3 -0
  4. package/README.md +255 -116
  5. package/SECURITY.md +13 -0
  6. package/bin/cli.js +120 -0
  7. package/docs/RULES.md +31 -0
  8. package/examples/baseline.sql +7 -0
  9. package/examples/consumer-workflow.yml +22 -0
  10. package/examples/migrations/001_add_phone.sql +1 -0
  11. package/examples/migrations/002_add_email_index.sql +1 -0
  12. package/examples/reviewed-risk-baseline.json +7 -0
  13. package/examples/safe.sql +2 -0
  14. package/examples/suppression-gate-policy.json +11 -0
  15. package/examples/team-policy.json +7 -0
  16. package/examples/test-unsafe.sql +1 -0
  17. package/examples/unsafe.sql +2 -0
  18. package/examples/verify.sql +8 -0
  19. package/examples/week3-gate-policy.json +6 -0
  20. package/examples/week3-production-context.json +8 -0
  21. package/package.json +73 -46
  22. package/scripts/orm-runner/README.md +35 -0
  23. package/scripts/orm-runner/package-lock.json +659 -0
  24. package/scripts/orm-runner/package.json +14 -0
  25. package/scripts/orm-runner/verify.mjs +360 -0
  26. package/scripts/test-pg-matrix.cjs +30 -0
  27. package/src/advisor.js +77 -0
  28. package/src/analysis.js +411 -0
  29. package/src/combined.js +60 -0
  30. package/src/config.js +38 -0
  31. package/src/db-inspect.js +30 -0
  32. package/src/detector.js +25 -0
  33. package/src/engine.js +48 -0
  34. package/src/gitDiff.js +33 -0
  35. package/src/github.js +17 -0
  36. package/src/locks.js +134 -0
  37. package/src/parser.js +86 -0
  38. package/src/plans.js +9 -0
  39. package/src/presets.js +5 -0
  40. package/src/production-context.js +78 -0
  41. package/src/reports.js +38 -0
  42. package/src/risk-baseline.js +54 -0
  43. package/src/risk.js +29 -0
  44. package/src/rules/additionalRules.js +9 -0
  45. package/src/rules/alterTableRules.js +65 -0
  46. package/src/rules/concurrentIndex.js +18 -0
  47. package/src/rules/dataIntegrityRules.js +40 -0
  48. package/src/rules/dropColumn.js +12 -0
  49. package/src/rules/operationalRiskRules.js +57 -0
  50. package/src/rules/ruleCatalog.js +37 -0
  51. package/src/rules/versionCatalog.js +16 -0
  52. package/src/rules/versionRules.js +49 -0
  53. package/src/simulator.js +135 -0
  54. package/src/suppression-matcher.js +24 -0
  55. package/src/suppression-report.js +19 -0
  56. package/src/suppression.js +78 -0
  57. package/src/team-policy.js +84 -0
  58. package/bin/pgsafe.js +0 -3
package/src/locks.js ADDED
@@ -0,0 +1,134 @@
1
+
2
+ // PostgreSQL table-lock planning hints.
3
+ // These are not predictions of wait time, duration, or downtime.
4
+
5
+ function assessment(mode, impact, note, confidence = 'heuristic') {
6
+ return { mode, confidence, impact, note };
7
+ }
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
+
64
+ export function lockFor(stmt) {
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
+ );
134
+ }
package/src/parser.js ADDED
@@ -0,0 +1,86 @@
1
+ import pgQuery from 'libpg-query';
2
+
3
+ export async function parseSqlFile(sqlContent, options = {}) {
4
+ if (!sqlContent || !sqlContent.trim()) {
5
+ return [];
6
+ }
7
+
8
+ try {
9
+ const result = await pgQuery.parse(sqlContent);
10
+ const statements = result.stmts || [];
11
+
12
+ if (!options.details) {
13
+ return statements.map(s => s.stmt);
14
+ }
15
+
16
+ const source = String(sqlContent);
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
+
34
+ return statements.map(s => {
35
+ let offset =
36
+ typeof s.stmt_location === 'number'
37
+ ? s.stmt_location
38
+ : 0;
39
+
40
+ offset = Math.max(
41
+ 0,
42
+ Math.min(offset, byteLength)
43
+ );
44
+
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
+ }
74
+ }
75
+
76
+ return {
77
+ stmt: s.stmt,
78
+ offset
79
+ };
80
+ });
81
+ } catch (err) {
82
+ throw new Error(
83
+ `SQL Syntax Error: ${err.message}`
84
+ );
85
+ }
86
+ }
package/src/plans.js ADDED
@@ -0,0 +1,9 @@
1
+ export function migrationPlan(finding) {
2
+ const plans = {
3
+ PG001: ['Add a replacement column.', 'Backfill in small batches.', 'Deploy application dual-read/dual-write or compatibility logic.', 'Switch reads and writes.', 'Remove the old column in a later release.'],
4
+ PG013: ['Add an equivalent NOT VALID CHECK constraint.', 'Validate the constraint in a separate deployment.', 'Apply SET NOT NULL only after validating compatibility and lock behavior.'],
5
+ PG015: ['Create the table or column in an earlier migration.', 'Create the concurrent index in a standalone migration.', 'Verify runner transaction behavior on disposable PostgreSQL.'],
6
+ PG016: ['Apply ordinary schema changes with Drizzle migrator.', 'Run CREATE INDEX CONCURRENTLY separately outside a transaction.', 'Record the operation in deployment runbooks and verify the index.']
7
+ };
8
+ return { ruleId: finding.ruleId, steps: plans[finding.ruleId] || ['Review lock impact.', 'Test on a disposable copy.', 'Plan rollback and application compatibility.'], automated: false, reviewRequired: true };
9
+ }
package/src/presets.js ADDED
@@ -0,0 +1,5 @@
1
+ export function getPreset(name) {
2
+ if (name === 'recommended') return { severity: 'error', rules: {} };
3
+ if (name === 'strict') return { severity: 'error', rules: { PG015: 'error', PG016: 'error', PG017: 'error' } };
4
+ throw new Error('preset must be recommended or strict');
5
+ }
@@ -0,0 +1,78 @@
1
+ import fs from 'node:fs';
2
+
3
+ const MAX_BYTES = 1024 * 1024;
4
+ const MAX_TABLES = 200;
5
+ const MAX_ROWS = 1e15;
6
+ const MAX_TABLE_BYTES = 1e18;
7
+ const MAX_MS = 3600000;
8
+ const allowed = new Set(['schema', 'table', 'estimatedRows', 'bytes', 'writeQueriesPerSecond']);
9
+
10
+ function plainObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
11
+ function boundedNumber(value, name, max) {
12
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > max) throw new Error(`${name} must be a finite non-negative number <= ${max}`);
13
+ return value;
14
+ }
15
+ export function validateProductionContext(input) {
16
+ if (!plainObject(input) || input.schemaVersion !== 1 || !Array.isArray(input.tables)) throw new Error('production context requires schemaVersion 1 and a tables array');
17
+ if (input.tables.length > MAX_TABLES) throw new Error(`production context supports at most ${MAX_TABLES} tables`);
18
+ for (const key of Object.keys(input)) if (!['schemaVersion', 'tables', 'lockTimeoutMs', 'statementTimeoutMs'].includes(key)) throw new Error(`Unknown production context field: ${key}`);
19
+ const tables = [];
20
+ const seen = new Set();
21
+ for (const row of input.tables) {
22
+ if (!plainObject(row)) throw new Error('production context table entry must be an object');
23
+ for (const key of Object.keys(row)) if (!allowed.has(key)) throw new Error(`Unknown production table field: ${key}`);
24
+ if (typeof row.schema !== 'string' || !/^[a-zA-Z_][\w$]{0,62}$/.test(row.schema) || typeof row.table !== 'string' || !/^[a-zA-Z_][\w$]{0,62}$/.test(row.table)) throw new Error('production table schema and table must be simple PostgreSQL identifiers');
25
+ const id = `${row.schema.toLowerCase()}.${row.table.toLowerCase()}`;
26
+ if (seen.has(id)) throw new Error(`Duplicate production table: ${id}`);
27
+ seen.add(id);
28
+ const entry = { schema: row.schema, table: row.table };
29
+ if (row.estimatedRows !== undefined) entry.estimatedRows = boundedNumber(row.estimatedRows, 'estimatedRows', MAX_ROWS);
30
+ if (row.bytes !== undefined) entry.bytes = boundedNumber(row.bytes, 'bytes', MAX_TABLE_BYTES);
31
+ if (row.writeQueriesPerSecond !== undefined) entry.writeQueriesPerSecond = boundedNumber(row.writeQueriesPerSecond, 'writeQueriesPerSecond', 1e7);
32
+ tables.push(entry);
33
+ }
34
+ const result = { schemaVersion: 1, tables };
35
+ if (input.lockTimeoutMs !== undefined) result.lockTimeoutMs = boundedNumber(input.lockTimeoutMs, 'lockTimeoutMs', MAX_MS);
36
+ if (input.statementTimeoutMs !== undefined) result.statementTimeoutMs = boundedNumber(input.statementTimeoutMs, 'statementTimeoutMs', MAX_MS);
37
+ return result;
38
+ }
39
+ export function loadProductionContext(file) {
40
+ const stat = fs.statSync(file);
41
+ if (stat.size > MAX_BYTES) throw new Error('production context file exceeds 1 MiB');
42
+ let parsed;
43
+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { throw new Error('Invalid production context JSON'); }
44
+ return validateProductionContext(parsed);
45
+ }
46
+ function tableMention(message) {
47
+ const quoted = String(message).match(/(?:on|table)\s+["']?([a-zA-Z_][\w$]*(?:\.[a-zA-Z_][\w$]*)?)["']?/i);
48
+ return quoted?.[1]?.toLowerCase() || null;
49
+ }
50
+ export function productionAssessment(findings, context) {
51
+ const tables = context.tables;
52
+ const assessments = findings.map(finding => {
53
+ const mention = tableMention(finding.message);
54
+ const matches = mention ? tables.filter(t => `${t.schema}.${t.table}`.toLowerCase() === mention || t.table.toLowerCase() === mention) : [];
55
+ const table = matches.length === 1 ? matches[0] : null;
56
+ const mode = finding.lock?.mode || 'unknown';
57
+ const writesBlocked = ['ACCESS EXCLUSIVE', 'EXCLUSIVE', 'SHARE', 'SHARE ROW EXCLUSIVE'].includes(mode);
58
+ const readsBlocked = mode === 'ACCESS EXCLUSIVE';
59
+ const large = Boolean(table && ((table.estimatedRows ?? 0) >= 1000000 || (table.bytes ?? 0) >= 1073741824));
60
+ const busy = Boolean(table && (table.writeQueriesPerSecond ?? 0) >= 10);
61
+ const factors = [];
62
+ if (mode === 'unknown') factors.push('Lock behavior is unknown; manual review required');
63
+ else factors.push(`Classified lock: ${mode}${readsBlocked ? ' (may block reads and writes)' : writesBlocked ? ' (may block writes)' : ''}`);
64
+ if (large) factors.push('Supplied table estimate is large (>= 1M rows or >= 1 GiB)');
65
+ if (busy) factors.push('Supplied write rate is >= 10 queries/second');
66
+ if (!table) factors.push(matches.length > 1 ? 'Ambiguous table match; production statistics not applied' : 'No matching production table statistics supplied');
67
+ const guidance = [];
68
+ if (finding.ruleId === 'PG001') guidance.push('Consider CREATE INDEX CONCURRENTLY outside a transaction; check framework transaction settings and monitor index progress');
69
+ else if (['PG002', 'PG003', 'PG024', 'PG025'].includes(finding.ruleId)) guidance.push('Consider an expand/backfill/validate/contract rollout with application compatibility checks');
70
+ else if (finding.ruleId === 'PG023') guidance.push('Review data-loss consequences and schedule TRUNCATE with an explicit maintenance plan');
71
+ else guidance.push('Review lock scope, expected execution time, and rollback strategy before deployment');
72
+ if (writesBlocked || readsBlocked) guidance.push('Use a tested lock_timeout and monitor blocking sessions; a timeout does not eliminate lock risk');
73
+ if (context.lockTimeoutMs !== undefined) factors.push(`Provided lock_timeout: ${context.lockTimeoutMs} ms (not verified against server)`);
74
+ if (context.statementTimeoutMs !== undefined) factors.push(`Provided statement_timeout: ${context.statementTimeoutMs} ms (not verified against server)`);
75
+ return { ruleId: finding.ruleId, file: finding.file, line: finding.line, column: finding.column, table: table ? `${table.schema}.${table.table}` : null, lockMode: mode, potentialImpact: readsBlocked ? 'reads-and-writes' : writesBlocked ? 'writes' : 'review-required', attention: large && (writesBlocked || readsBlocked) ? 'elevated' : 'review', factors, guidance };
76
+ });
77
+ return { source: 'user-supplied estimates (not a live database inspection)', confidence: 'limited', assessments, limitations: ['Table statistics and workload rates may be stale or inaccurate', 'SQL table matching is heuristic; schema ambiguity prevents applying estimates', 'No measured lock waits, execution duration, or downtime prediction', 'Existing policy gate decisions are unchanged'] };
78
+ }
package/src/reports.js ADDED
@@ -0,0 +1,38 @@
1
+ import { suppressionMarkdown } from './suppression-report.js';
2
+ export function toJson(findings, meta = {}) { return JSON.stringify({ tool: 'pg-safe-migrate', ...meta, findings }, null, 2); }
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);
8
+ }
9
+
10
+ // Human-readable report. Escapes Markdown cells and never includes untrusted HTML.
11
+ const mdCell = value => String(value ?? '').replace(/\r?\n/g, ' ').replace(/\|/g, '\\|').replace(/</g, '&lt;').replace(/>/g, '&gt;');
12
+ export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVersion, risk, suppression } = {}) {
13
+ const errors = findings.filter(f => f.severity === 'error').length;
14
+ const warnings = findings.filter(f => f.severity === 'warning').length;
15
+ const lines = [
16
+ '# PG Safe Migrate report', '',
17
+ `Files checked: **${filesChecked}** | Errors: **${errors}** | Warnings: **${warnings}**${postgresVersion ? ` | PostgreSQL: **${mdCell(postgresVersion)}**` : ''}`, ''
18
+ ];
19
+ if (risk) {
20
+ lines.push('## Risk assessment', '', `**${risk.score}/100 (${mdCell(risk.band)})** — heuristic, not a downtime prediction.`, '');
21
+ if (risk.breakdown) {
22
+ lines.push('| Component | Points |', '|---|---:|');
23
+ for (const [name, value] of Object.entries(risk.breakdown)) lines.push(`| ${mdCell(name)} | ${Number(value) || 0} |`);
24
+ lines.push('');
25
+ }
26
+ if (risk.unknownLocks) lines.push('**Unclassified locks present:** review SQL manually.', '');
27
+ if (risk.limitations?.length) lines.push('Limitations: ' + risk.limitations.map(mdCell).join('; ') + '.', '');
28
+ }
29
+ lines.push('## Findings', '');
30
+ if (!findings.length) lines.push('No configured findings. This does not guarantee a safe migration.', '');
31
+ else {
32
+ lines.push('| Rule | Severity | File | Line | Message | Recommendation |', '|---|---|---|---:|---|---|');
33
+ for (const f of findings) lines.push(`| ${mdCell(f.ruleId)} | ${mdCell(f.severity)} | ${mdCell(f.file)} | ${Math.max(1, Number(f.line) || 1)} | ${mdCell(f.message)} | ${mdCell(f.fix)} |`);
34
+ lines.push('');
35
+ }
36
+ lines.push('> Static analysis is advisory. Review locks, data volume, transaction behavior, and production workload before deployment.', '');
37
+ return lines.join('\n') + (suppression ? suppressionMarkdown(suppression) : '');
38
+ }
@@ -0,0 +1,54 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+
5
+ const sha = value => crypto.createHash('sha256').update(value).digest('hex');
6
+ const normalizedPath = file => String(file).replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/+/g, '/');
7
+ const normalizedSql = sql => String(sql).replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').trim().toLowerCase();
8
+
9
+ // Statement boundaries are derived from the parser's starting positions when available.
10
+ // A conservative text fallback is used for baseline identity; it is not a SQL parser.
11
+ function statementAt(sql, line) {
12
+ const lines = String(sql).split(/\r?\n/);
13
+ const start = Math.max(0, Math.min(lines.length - 1, Number(line || 1) - 1));
14
+ let begin = start;
15
+ while (begin > 0 && !lines[begin - 1].includes(';')) begin--;
16
+ let end = start;
17
+ while (end < lines.length - 1 && !lines[end].includes(';')) end++;
18
+ return normalizedSql(lines.slice(begin, end + 1).join('\n'));
19
+ }
20
+
21
+ export function fingerprint(finding, sqlByFile = new Map()) {
22
+ const file = normalizedPath(finding.file);
23
+ const sql = sqlByFile.get(file);
24
+ const identity = sql === undefined ? String(finding.message || '') : statementAt(sql, finding.line);
25
+ return sha(JSON.stringify([file, finding.ruleId, finding.severity, identity]));
26
+ }
27
+ export function createRiskBaseline(findings, entries) {
28
+ const sqlByFile = new Map(entries.map(e => [normalizedPath(e.file), e.sql]));
29
+ const fingerprints = findings.map(f => fingerprint(f, sqlByFile)).sort();
30
+ return { schemaVersion: 1, tool: 'pg-safe-migrate', fingerprints };
31
+ }
32
+ export function loadRiskBaseline(filename) {
33
+ const obj = JSON.parse(fs.readFileSync(filename, 'utf8'));
34
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj) || obj.schemaVersion !== 1 || obj.tool !== 'pg-safe-migrate' || !Array.isArray(obj.fingerprints) || obj.fingerprints.length > 100000 || obj.fingerprints.some(x => typeof x !== 'string' || !/^[a-f0-9]{64}$/.test(x))) throw new Error('Invalid risk baseline (expected schemaVersion 1 and SHA-256 fingerprints)');
35
+ return obj;
36
+ }
37
+ export function compareRiskBaseline(findings, entries, baseline) {
38
+ const sqlByFile = new Map(entries.map(e => [normalizedPath(e.file), e.sql]));
39
+ const previous = new Map();
40
+ for (const id of baseline.fingerprints) previous.set(id, (previous.get(id) || 0) + 1);
41
+ const newFindings = [], existingFindings = [];
42
+ for (const f of findings) {
43
+ const id = fingerprint(f, sqlByFile);
44
+ if ((previous.get(id) || 0) > 0) { existingFindings.push(f); previous.set(id, previous.get(id) - 1); }
45
+ else newFindings.push(f);
46
+ }
47
+ const resolved = [...previous.values()].reduce((a,b)=>a+b,0);
48
+ return { newFindings, existingFindings, resolvedCount: resolved, newCount: newFindings.length, existingCount: existingFindings.length };
49
+ }
50
+ export function writeRiskBaseline(filename, baseline) {
51
+ const dest = path.resolve(filename);
52
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
53
+ fs.writeFileSync(dest, JSON.stringify(baseline, null, 2) + '\n', { flag: 'w' });
54
+ }
package/src/risk.js ADDED
@@ -0,0 +1,29 @@
1
+ // A bounded, explainable heuristic; not a prediction of outage duration.
2
+ const weights = { error: 20, warning: 5 };
3
+ const lockWeights = { 'ACCESS EXCLUSIVE': 15, 'EXCLUSIVE': 12, 'SHARE ROW EXCLUSIVE': 10, 'SHARE': 8, 'SHARE UPDATE EXCLUSIVE': 4, 'ROW EXCLUSIVE': 2 };
4
+ const destructiveRules = new Set(['PG001', 'PG002', 'PG003', 'PG023', 'PG024']);
5
+ const clamp = n => Math.max(0, Math.min(100, n));
6
+
7
+ export function summarizeRisk(findings = [], context = {}) {
8
+ const operations = Array.isArray(context.operations) ? context.operations : [];
9
+ const severityPoints = findings.reduce((sum, f) => sum + (weights[f.severity] || 0), 0);
10
+ // Only count distinct rule/location combinations to avoid inflated scores.
11
+ const destructive = new Set(findings.filter(f => destructiveRules.has(f.ruleId)).map(f => `${f.file || ''}:${f.line || 0}:${f.ruleId}`));
12
+ const destructivePoints = Math.min(20, destructive.size * 5);
13
+ // Maximum lock impact, rather than summing every statement in a large migration.
14
+ const lockPoints = operations.reduce((max, operation) => Math.max(max, lockWeights[operation?.lock?.mode] || 0), 0);
15
+ const unknownLocks = operations.some(operation => !operation?.lock?.mode || operation.lock.mode === 'unknown');
16
+ const transactionPoints = context.transactionRisk === true ? 10 : 0;
17
+ // Optional metadata is advisory only: never infer table size from SQL text.
18
+ const stats = context.tableStats;
19
+ const tableSizePoints = stats && Number.isFinite(stats.estimatedRows) && stats.estimatedRows >= 1000000 ? 10 : 0;
20
+ const score = clamp(severityPoints + destructivePoints + lockPoints + transactionPoints + tableSizePoints);
21
+ return {
22
+ score, band: score >= 60 ? 'high' : score >= 20 ? 'moderate' : 'low',
23
+ confidence: 'low',
24
+ basis: 'Bounded heuristic based on lint severity, destructive operations, strongest classified table lock, optional transaction flag and supplied table statistics. Not a prediction of downtime.',
25
+ breakdown: { severity: clamp(severityPoints), destructive: destructivePoints, lock: lockPoints, transaction: transactionPoints, tableSize: tableSizePoints },
26
+ unknownLocks,
27
+ limitations: ['No production workload or lock wait measurements', 'Table statistics are optional estimates', 'Lock classifications may be conservative']
28
+ };
29
+ }
@@ -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
+ };
@@ -0,0 +1,65 @@
1
+ export const alterTableRules = {
2
+ id: 'PG003-PG005',
3
+ name: 'safe-alter-table',
4
+ check(stmt) {
5
+ if (!stmt.AlterTableStmt) return [];
6
+ const tableName = stmt.AlterTableStmt.relation?.relname || 'unknown_table';
7
+ const issues = [];
8
+
9
+ for (const cmdWrapper of stmt.AlterTableStmt.cmds || []) {
10
+ const cmd = cmdWrapper.AlterTableCmd;
11
+ if (!cmd) continue;
12
+
13
+ if (cmd.subtype === 'AT_AlterColumnType') {
14
+ issues.push({
15
+ ruleId: 'PG003',
16
+ severity: 'ERROR',
17
+ message: `Changing column type on "${tableName}" may rewrite the table and requires an ACCESS EXCLUSIVE lock; some type changes avoid a rewrite.`,
18
+ fix: `Create a new column, dual-write in app code, backfill rows, then swap columns.`
19
+ });
20
+ }
21
+
22
+ if (cmd.subtype === 'AT_AddColumn' && cmd.def?.ColumnDef) {
23
+ const constraints = cmd.def.ColumnDef.constraints || [];
24
+ const isNotNull = constraints.some((c) => c.Constraint?.contype === 'CONSTR_NOTNULL');
25
+ const hasDefault = constraints.some((c) => c.Constraint?.contype === 'CONSTR_DEFAULT');
26
+
27
+ if (isNotNull && !hasDefault) {
28
+ issues.push({
29
+ ruleId: 'PG004',
30
+ severity: 'ERROR',
31
+ message: `Adding NOT NULL column "${cmd.def.ColumnDef.colname}" without DEFAULT can fail on non-empty tables and requires a careful backfill.`,
32
+ fix: `Add column as nullable, backfill values in batches, then add a NOT NULL constraint.`
33
+ });
34
+ }
35
+ }
36
+
37
+ if (cmd.subtype === 'AT_AddConstraint' && cmd.def?.Constraint?.contype === 'CONSTR_FOREIGN') {
38
+ if (!cmd.def.Constraint.skip_validation) {
39
+ issues.push({
40
+ ruleId: 'PG005',
41
+ severity: 'ERROR',
42
+ message: `Adding FOREIGN KEY on "${tableName}" without NOT VALID blocks writes while validating existing rows.`,
43
+ fix: `Add "NOT VALID" to the constraint, then run ALTER TABLE ... VALIDATE CONSTRAINT separately.`
44
+ });
45
+ }
46
+ }
47
+ }
48
+ return issues;
49
+ }
50
+ };
51
+
52
+ export const renameRule = {
53
+ id: 'PG006',
54
+ name: 'ban-rename',
55
+ check(stmt) {
56
+ if (!stmt.RenameStmt) return null;
57
+ const target = stmt.RenameStmt.subname || stmt.RenameStmt.relation?.relname || 'object';
58
+ return {
59
+ ruleId: 'PG006',
60
+ severity: 'ERROR',
61
+ message: `Renaming "${target}" can break deployed application instances expecting the old name.`,
62
+ fix: `Add a new column/table, dual-write or sync via trigger, and drop the old one in a later release.`
63
+ };
64
+ }
65
+ };
@@ -0,0 +1,18 @@
1
+ export const concurrentIndexRule = {
2
+ id: 'PG001',
3
+ name: 'require-concurrent-index',
4
+ check(stmt) {
5
+ if (!stmt.IndexStmt) return null;
6
+
7
+ if (!stmt.IndexStmt.concurrent) {
8
+ const tableName = stmt.IndexStmt.relation?.relname || 'unknown_table';
9
+ return {
10
+ ruleId: this.id,
11
+ severity: 'ERROR',
12
+ message: `CREATE INDEX on "${tableName}" acquires a SHARE lock and blocks writes.`,
13
+ fix: `Use CREATE INDEX CONCURRENTLY and execute outside a transaction block.`
14
+ };
15
+ }
16
+ return null;
17
+ }
18
+ };
@@ -0,0 +1,40 @@
1
+ /** Conservative, schema-independent data-loss and constraint checks. */
2
+ export const dataIntegrityRules = {
3
+ id: 'PG023-PG025',
4
+ name: 'data-integrity-safeguards',
5
+ check(stmt) {
6
+ const issues = [];
7
+ if (stmt.TruncateStmt) {
8
+ const tables = (stmt.TruncateStmt.relations || [])
9
+ .map(entry => entry.RangeVar?.relname)
10
+ .filter(Boolean);
11
+ issues.push({
12
+ ruleId: 'PG023', severity: 'ERROR',
13
+ message: `TRUNCATE${tables.length ? ` on ${tables.join(', ')}` : ''} removes all rows and takes an ACCESS EXCLUSIVE lock.`,
14
+ fix: 'Require an explicit data-retention approval and backup/recovery plan; use a reviewed, bounded DELETE only when appropriate.'
15
+ });
16
+ }
17
+ const alter = stmt.AlterTableStmt;
18
+ if (!alter) return issues;
19
+ const table = alter.relation?.relname || 'unknown_table';
20
+ for (const wrapper of alter.cmds || []) {
21
+ const cmd = wrapper.AlterTableCmd;
22
+ if (!cmd) continue;
23
+ if (cmd.subtype === 'AT_DropConstraint') {
24
+ issues.push({
25
+ ruleId: 'PG024', severity: 'WARNING',
26
+ message: `Dropping constraint "${cmd.name || 'unknown'}" on "${table}" may remove a data-integrity guarantee or dependent objects.`,
27
+ fix: 'Review constraint dependencies, application validation, and the replacement constraint before dropping it.'
28
+ });
29
+ }
30
+ if (cmd.subtype === 'AT_SetNotNull') {
31
+ issues.push({
32
+ ruleId: 'PG025', severity: 'WARNING',
33
+ message: `Setting column "${cmd.name || 'unknown'}" NOT NULL on "${table}" may scan existing rows and fail if NULL values remain; a validated proving CHECK constraint can avoid the scan on supported versions.`,
34
+ fix: 'Backfill NULLs in batches, validate a CHECK (column IS NOT NULL) constraint, then SET NOT NULL; verify version and lock requirements.'
35
+ });
36
+ }
37
+ }
38
+ return issues;
39
+ }
40
+ };
@@ -0,0 +1,12 @@
1
+ export const dropColumnRule = {
2
+ id: 'PG002', name: 'ban-direct-drop-column',
3
+ check(stmt) {
4
+ if (!stmt.AlterTableStmt) return [];
5
+ const table = stmt.AlterTableStmt.relation?.relname || 'unknown_table';
6
+ return (stmt.AlterTableStmt.cmds || []).filter(w => w.AlterTableCmd?.subtype === 'AT_DropColumn').map(w => ({
7
+ ruleId: 'PG002', severity: 'ERROR',
8
+ message: `Dropping column "${table}.${w.AlterTableCmd.name}" can break older application instances.`,
9
+ fix: 'Stop referencing the column in all deployed application versions before dropping it in a later release.'
10
+ }));
11
+ }
12
+ };
@@ -0,0 +1,57 @@
1
+ /** Conservative AST-based operational risk checks. No database access. */
2
+ const VOLATILE_DEFAULT_FUNCTIONS = new Set([
3
+ 'random', 'clock_timestamp', 'timeofday', 'nextval',
4
+ 'gen_random_uuid', 'uuid_generate_v4'
5
+ ]);
6
+
7
+ function functionNames(node, names = new Set()) {
8
+ if (!node || typeof node !== 'object') return names;
9
+ if (Array.isArray(node)) {
10
+ for (const item of node) functionNames(item, names);
11
+ return names;
12
+ }
13
+ const call = node.FuncCall;
14
+ if (call?.funcname) {
15
+ const parts = call.funcname.map(x => x.String?.sval).filter(Boolean);
16
+ if (parts.length) names.add(parts.at(-1).toLowerCase());
17
+ }
18
+ for (const value of Object.values(node)) functionNames(value, names);
19
+ return names;
20
+ }
21
+
22
+ export const operationalRiskRules = {
23
+ id: 'PG021-PG022',
24
+ name: 'operational-lock-and-rewrite-risk',
25
+ check(stmt) {
26
+ const alter = stmt.AlterTableStmt;
27
+ if (!alter) return [];
28
+ const table = alter.relation?.relname || 'unknown_table';
29
+ const issues = [];
30
+ for (const wrapper of alter.cmds || []) {
31
+ const cmd = wrapper.AlterTableCmd;
32
+ if (!cmd) continue;
33
+ if (cmd.subtype === 'AT_AddColumn' && cmd.def?.ColumnDef) {
34
+ const column = cmd.def.ColumnDef;
35
+ const defaults = (column.constraints || []).filter(x => x.Constraint?.contype === 'CONSTR_DEFAULT');
36
+ const functions = new Set();
37
+ for (const def of defaults) functionNames(def.Constraint.raw_expr, functions);
38
+ const matched = [...functions].filter(x => VOLATILE_DEFAULT_FUNCTIONS.has(x));
39
+ if (matched.length) {
40
+ issues.push({
41
+ ruleId: 'PG021', severity: 'ERROR',
42
+ message: `Adding column "${column.colname}" on "${table}" with volatile DEFAULT (${matched.join(', ')}) may rewrite existing rows and hold an ACCESS EXCLUSIVE lock.`,
43
+ fix: 'Add the column without a volatile default, backfill in controlled batches, then set the default for new rows.'
44
+ });
45
+ }
46
+ }
47
+ if (cmd.subtype === 'AT_SetLogged') {
48
+ issues.push({
49
+ ruleId: 'PG022', severity: 'ERROR',
50
+ message: `ALTER TABLE "${table}" SET LOGGED rewrites the table and requires an ACCESS EXCLUSIVE lock.`,
51
+ fix: 'Schedule a maintenance window or use a carefully validated replacement-table and cutover plan.'
52
+ });
53
+ }
54
+ }
55
+ return issues;
56
+ }
57
+ };