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
@@ -0,0 +1,411 @@
1
+ import { parseSqlFile } from './parser.js';
2
+ import { lintStatements } from './engine.js';
3
+ import { advise } from './advisor.js';
4
+ import { lockFor } from './locks.js';
5
+ import { normalizeSuppression } from './config.js';
6
+ import { matchSuppressions } from './suppression-matcher.js';
7
+
8
+ const ADVISORY_RULES = new Set(['PG015', 'PG016', 'PG017']);
9
+
10
+ export function position(sql, offset = 0) {
11
+ const source = String(sql ?? '');
12
+ const numericOffset = Number(offset);
13
+
14
+ const safeOffset = Number.isFinite(numericOffset)
15
+ ? Math.min(
16
+ source.length,
17
+ Math.max(0, Math.floor(numericOffset))
18
+ )
19
+ : 0;
20
+
21
+ const prefix = source.slice(0, safeOffset);
22
+ const lastNewline = prefix.lastIndexOf('\n');
23
+
24
+ return {
25
+ line: prefix.split('\n').length,
26
+ column: safeOffset - lastNewline
27
+ };
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
+
70
+ export function frameworkFor(file) {
71
+ const p = file.replaceAll('\\', '/').toLowerCase();
72
+
73
+ if (/(^|\/)prisma\/migrations\//.test(p)) {
74
+ return 'prisma';
75
+ }
76
+
77
+ if (/(^|\/)drizzle\//.test(p)) {
78
+ return 'drizzle';
79
+ }
80
+
81
+ if (/(^|\/)(?:sql\/)?(?:migrations\/)?(?:v[0-9][a-z0-9_.-]*__[^/]+|r__[^/]+)\.sql$/.test(p) || /(^|\/)db\/migration\/[^/]+\.sql$/.test(p)) {
82
+ return 'flyway';
83
+ }
84
+
85
+ return 'sql';
86
+ }
87
+
88
+ function txType(stmt) {
89
+ const kind = stmt.TransactionStmt?.kind;
90
+
91
+ if (
92
+ kind === 'TRANS_STMT_BEGIN' ||
93
+ kind === 'TRANS_STMT_START'
94
+ ) {
95
+ return 'begin';
96
+ }
97
+
98
+ if ([
99
+ 'TRANS_STMT_COMMIT',
100
+ 'TRANS_STMT_ROLLBACK',
101
+ 'TRANS_STMT_PREPARE'
102
+ ].includes(kind)) {
103
+ return 'end';
104
+ }
105
+
106
+ return null;
107
+ }
108
+
109
+ function concurrently(stmt) {
110
+ return Boolean(
111
+ stmt.IndexStmt?.concurrent ||
112
+ (
113
+ stmt.DropStmt?.removeType === 'OBJECT_INDEX' &&
114
+ stmt.DropStmt.concurrent
115
+ )
116
+ );
117
+ }
118
+
119
+ function ddlTarget(stmt) {
120
+ if (stmt.AlterTableStmt) {
121
+ return stmt.AlterTableStmt.relation?.relname;
122
+ }
123
+
124
+ if (stmt.RenameStmt) {
125
+ return stmt.RenameStmt.relation?.relname;
126
+ }
127
+
128
+ if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') {
129
+ return stmt.DropStmt.objects?.[0]?.List?.items
130
+ ?.map(x => x.String?.sval)
131
+ .join('.');
132
+ }
133
+
134
+ return null;
135
+ }
136
+
137
+ function extras(stmt, postgresVersion) {
138
+ const issues = [];
139
+
140
+ const add = (ruleId, message, fix) => {
141
+ issues.push({ ruleId, message, fix });
142
+ };
143
+
144
+ if (!stmt.AlterTableStmt) {
145
+ return issues;
146
+ }
147
+
148
+ for (const wrapper of stmt.AlterTableStmt.cmds || []) {
149
+ const cmd = wrapper.AlterTableCmd;
150
+
151
+ if (!cmd) continue;
152
+
153
+ if (cmd.subtype === 'AT_SetNotNull') {
154
+ add(
155
+ 'PG013',
156
+ 'SET NOT NULL may scan a large table and requires a strong lock.',
157
+ 'Validate an equivalent CHECK constraint first where supported; test on your PostgreSQL version.'
158
+ );
159
+ }
160
+
161
+ if (
162
+ cmd.subtype === 'AT_AddConstraint' &&
163
+ cmd.def?.Constraint?.contype === 'CONSTR_CHECK' &&
164
+ !cmd.def.Constraint.skip_validation
165
+ ) {
166
+ add(
167
+ 'PG012',
168
+ 'Adding a validated CHECK constraint may scan existing rows.',
169
+ 'Consider NOT VALID followed by a separately scheduled VALIDATE CONSTRAINT.'
170
+ );
171
+ }
172
+
173
+ if (
174
+ cmd.subtype === 'AT_AddConstraint' &&
175
+ cmd.def?.Constraint?.contype === 'CONSTR_UNIQUE'
176
+ ) {
177
+ add(
178
+ 'PG010',
179
+ 'Adding a UNIQUE constraint can require a blocking index build.',
180
+ 'Consider CREATE UNIQUE INDEX CONCURRENTLY then attach the index using a constraint, where applicable.'
181
+ );
182
+ }
183
+
184
+ if (
185
+ cmd.subtype === 'AT_AddColumn' &&
186
+ postgresVersion != null &&
187
+ Number(postgresVersion) < 11
188
+ ) {
189
+ const def = cmd.def?.ColumnDef;
190
+
191
+ if (
192
+ def?.constraints?.some(
193
+ x => x.Constraint?.contype === 'CONSTR_DEFAULT'
194
+ )
195
+ ) {
196
+ add(
197
+ 'PG014',
198
+ 'On PostgreSQL 10, adding a column with a default may rewrite the table.',
199
+ 'Use a nullable column and controlled backfill, or evaluate upgrading PostgreSQL.'
200
+ );
201
+ }
202
+ }
203
+ }
204
+
205
+ return issues;
206
+ }
207
+
208
+ export async function analyzeFiles(
209
+ entries,
210
+ config = {},
211
+ options = {}
212
+ ) {
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');
217
+ const seen = new Map();
218
+
219
+ const version = config.postgresVersion ?? null;
220
+
221
+ const files = [...entries].sort(
222
+ (a, b) => a.file.localeCompare(b.file)
223
+ );
224
+
225
+ for (const { file, sql } of files) {
226
+ const parsed = await parseSqlFile(sql, {
227
+ details: true
228
+ });
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
+ }
241
+ const framework = frameworkFor(file);
242
+ const locate = createPositionTracker(sql);
243
+
244
+ let inTransaction = false;
245
+
246
+ for (const { stmt, offset } of parsed) {
247
+ const loc = locate(offset);
248
+ const transaction = txType(stmt);
249
+
250
+ // Track explicit transaction boundaries.
251
+ if (transaction === 'begin') {
252
+ inTransaction = true;
253
+ }
254
+
255
+ // Findings generated by the main rule engine.
256
+ const ruleIssues = lintStatements(
257
+ [stmt],
258
+ { postgresVersion: version }
259
+ );
260
+
261
+ // Additional compatibility and advisory findings.
262
+ const extraIssues = extras(stmt, version);
263
+
264
+ // PG025 provides more specific SET NOT NULL guidance.
265
+ // Keep PG013 when PG025 is not generated.
266
+ const hasPG025 = ruleIssues.some(
267
+ issue => issue.ruleId === 'PG025'
268
+ );
269
+
270
+ const issues = [
271
+ ...ruleIssues,
272
+ ...extraIssues.filter(
273
+ issue =>
274
+ !(hasPG025 && issue.ruleId === 'PG013')
275
+ )
276
+ ];
277
+
278
+ // Concurrent index operations cannot run inside
279
+ // explicit PostgreSQL transactions.
280
+ if (inTransaction && concurrently(stmt)) {
281
+ issues.push({
282
+ ruleId: 'PG008',
283
+ message:
284
+ 'CONCURRENTLY cannot execute inside an explicit transaction block.',
285
+ fix:
286
+ 'Run concurrent index operations outside BEGIN/COMMIT.'
287
+ });
288
+ }
289
+
290
+ // Prisma-specific migration guidance.
291
+ if (
292
+ framework === 'prisma' &&
293
+ concurrently(stmt)
294
+ ) {
295
+ issues.push({
296
+ ruleId: 'PG015',
297
+ message:
298
+ 'Prisma: use a standalone migration for CONCURRENTLY; combined SQL statements can fail in a transaction context.',
299
+ fix:
300
+ 'Review the generated migration and execution strategy; PostgreSQL forbids CONCURRENTLY inside a transaction.'
301
+ });
302
+ }
303
+
304
+ // Drizzle-specific migration guidance.
305
+ if (
306
+ framework === 'drizzle' &&
307
+ concurrently(stmt)
308
+ ) {
309
+ issues.push({
310
+ ruleId: 'PG016',
311
+ message:
312
+ 'Drizzle node-postgres migrator uses a transaction in the tested version; CONCURRENTLY fails with PostgreSQL 25001.',
313
+ fix:
314
+ 'Execute the concurrent index through a separately managed non-transactional path; do not use the standard transactional migrator.'
315
+ });
316
+ }
317
+
318
+ // Flyway PostgreSQL migrations are normally transactional, unless the
319
+ // deployment configuration opts out. This is advice, not a claim about
320
+ // the actual runner's settings. Avoid inventing a new rule identifier.
321
+ if (framework === 'flyway' && concurrently(stmt)) {
322
+ issues.push({
323
+ ruleId: 'PG017',
324
+ message: 'Flyway: CONCURRENTLY requires non-transactional execution; verify executeInTransaction=false for this migration.',
325
+ fix: 'Configure this migration for non-transactional execution, review mixed statements, and verify Flyway edition/version behavior.'
326
+ });
327
+ }
328
+
329
+ const target = ddlTarget(stmt);
330
+
331
+ // Detect potential cross-file dependencies.
332
+ if (
333
+ target &&
334
+ seen.has(target) &&
335
+ (
336
+ stmt.RenameStmt ||
337
+ stmt.DropStmt?.removeType === 'OBJECT_TABLE'
338
+ )
339
+ ) {
340
+ const previous = seen.get(target);
341
+
342
+ if (previous.file !== file) {
343
+ issues.push({
344
+ ruleId: 'PG017',
345
+ message:
346
+ `Potential cross-file dependency: ${target} was modified earlier in ${previous.file}.`,
347
+ fix:
348
+ 'Review migration order and deployed application compatibility; this is a heuristic, not proof of a conflict.'
349
+ });
350
+ }
351
+ }
352
+
353
+ if (target) {
354
+ seen.set(target, { file });
355
+ }
356
+
357
+ // Convert rule findings into report findings.
358
+ for (const issue of issues) {
359
+ const isAdvisory = ADVISORY_RULES.has(
360
+ issue.ruleId
361
+ );
362
+
363
+ const defaultSeverity = isAdvisory
364
+ ? 'warning'
365
+ : 'error';
366
+
367
+ const severity =
368
+ config.rules?.[issue.ruleId] ??
369
+ (
370
+ isAdvisory
371
+ ? 'warning'
372
+ : (config.severity ?? defaultSeverity)
373
+ );
374
+
375
+ if (severity === 'off') {
376
+ continue;
377
+ }
378
+
379
+ const finding = {
380
+ ...issue,
381
+ severity,
382
+ file,
383
+ line: loc.line,
384
+ column: loc.column,
385
+ framework,
386
+ lock: lockFor(stmt),
387
+ ...(options.advisor
388
+ ? {
389
+ advisor: advise(issue, framework)
390
+ }
391
+ : {})
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);
398
+ }
399
+
400
+ // Close the explicit transaction after processing.
401
+ if (transaction === 'end') {
402
+ inTransaction = Boolean(stmt.TransactionStmt?.chain);
403
+ }
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
+ }
408
+ }
409
+
410
+ return findings;
411
+ }
@@ -0,0 +1,60 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { analyzeFiles } from './analysis.js';
4
+ import { simulateSqlFile } from './simulator.js';
5
+ import { summarizeRisk } from './risk.js';
6
+ import { parseSqlFile } from './parser.js';
7
+ import { lockFor } from './locks.js';
8
+
9
+ export function simulationEntries({ file, migrationsDir }) {
10
+ if (Boolean(file) === Boolean(migrationsDir)) throw new Error('Provide exactly one migration file or --migrations-dir');
11
+ const paths = migrationsDir
12
+ ? fs.readdirSync(migrationsDir, { withFileTypes: true }).filter(x => x.isFile() && x.name.toLowerCase().endsWith('.sql')).map(x => path.join(migrationsDir, x.name)).sort()
13
+ : [file];
14
+ if (!paths.length || paths.length > 100) throw new Error('Expected 1-100 migration SQL files');
15
+ return paths.map(p => ({ file: path.resolve(p), sql: fs.readFileSync(p, 'utf8') }));
16
+ }
17
+
18
+ export async function combinedAssessment({ file, migrationsDir, baseline, postgresVersion = '16', config = {}, run, verifySql }) {
19
+ const entries = simulationEntries({ file, migrationsDir });
20
+ const findings = await analyzeFiles(entries, { ...config, postgresVersion: Number(postgresVersion) }, { advisor: true });
21
+ // Inventory every statement, including operations that do not trigger a lint rule.
22
+ // A zero-findings result must never be mistaken for a zero-lock result.
23
+ const operations = [];
24
+ const indexNames = new Map();
25
+ for (const entry of entries) {
26
+ const statements = await parseSqlFile(entry.sql, { details: true });
27
+ for (const { stmt } of statements) {
28
+ const type = Object.keys(stmt)[0] ?? 'Unknown';
29
+ const lock = lockFor(stmt);
30
+ operations.push({ file: entry.file, type, lock });
31
+ const name = stmt.IndexStmt?.idxname;
32
+ if (name) {
33
+ if (indexNames.has(name)) findings.push({
34
+ ruleId: 'PG018', severity: 'error', file: entry.file, line: 1, column: 1,
35
+ message: `Duplicate CREATE INDEX name ${name}; previously defined in ${indexNames.get(name)}.`,
36
+ fix: 'Give indexes unique names or remove the duplicate migration.',
37
+ lock, framework: 'sql'
38
+ });
39
+ else indexNames.set(name, entry.file);
40
+ }
41
+ }
42
+ }
43
+ // Do not start Docker when the migration set is internally inconsistent.
44
+ const duplicate = findings.some(f => f.ruleId === 'PG018');
45
+ const simulation = duplicate
46
+ ? { passed: false, skipped: true, reason: 'Duplicate index definitions detected before simulation', steps: [] }
47
+ : simulateSqlFile(file, { migrationsDir, baseline, postgresVersion, run, verifySql });
48
+ const risk = summarizeRisk(findings, { operations });
49
+ return {
50
+ schemaVersion: 1, postgresVersion: Number(postgresVersion),
51
+ execution: simulation, lint: { findings, count: findings.length, risk }, operations,
52
+ safetyNote: 'No lint findings does not mean no locks or downtime risk; review operations and production workload.',
53
+ recommendation: !simulation.passed ? 'Migration execution or verification failed; do not deploy.'
54
+ : findings.some(f => f.severity === 'error') ? 'Execution succeeded but static analysis found errors; review before deployment.'
55
+ : findings.length ? 'Execution succeeded with advisories; review locks and production workload.'
56
+ : 'Execution succeeded with no configured findings; this is not a downtime guarantee.',
57
+ passed: simulation.passed && !findings.some(f => f.severity === 'error'),
58
+ confidence: 'limited: disposable database and heuristic linting cannot establish production safety'
59
+ };
60
+ }
package/src/config.js ADDED
@@ -0,0 +1,38 @@
1
+ import fs from 'node:fs';
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
+ }
14
+
15
+ export const DEFAULT_CONFIG = Object.freeze({ severity: 'error', rules: {}, exclude: [], postgresVersion: null });
16
+ export function loadConfig(file = 'pg-safe-migrate.config.json') {
17
+ if (!fs.existsSync(file)) return { ...DEFAULT_CONFIG };
18
+ let parsed;
19
+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); }
20
+ catch (e) { throw new Error(`Invalid configuration ${file}: ${e.message}`); }
21
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') throw new Error('Configuration must be a JSON object.');
22
+ if (parsed.rules !== undefined && (!parsed.rules || Array.isArray(parsed.rules) || typeof parsed.rules !== 'object')) throw new Error('rules must be an object.');
23
+ 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.');
24
+ const rules = parsed.rules || {};
25
+ for (const [id, value] of Object.entries(rules)) {
26
+ if (!/^PG\d{3}$/.test(id) || !['off','warning','error'].includes(value)) throw new Error(`Invalid rule configuration: ${id}=${value}`);
27
+ }
28
+ if (parsed.severity !== undefined && !['warning','error'].includes(parsed.severity)) throw new Error('severity must be warning or error.');
29
+ if (parsed.postgresVersion != null && (!Number.isInteger(parsed.postgresVersion) || parsed.postgresVersion < 10 || parsed.postgresVersion > 99)) throw new Error('postgresVersion must be an integer >= 10.');
30
+ return { ...DEFAULT_CONFIG, ...parsed, rules, suppression: normalizeSuppression(parsed.suppression) };
31
+ }
32
+ export function isExcluded(file, patterns, cwd = process.cwd()) {
33
+ const rel = path.relative(cwd, path.resolve(file)).replaceAll('\\','/');
34
+ return patterns.some(pattern => {
35
+ const normalized = pattern.replaceAll('\\','/').replace(/^\.\//,'').replace(/\/$/,'');
36
+ return rel === normalized || rel.startsWith(normalized + '/') || (normalized.startsWith('*.') && rel.endsWith(normalized.slice(1)));
37
+ });
38
+ }
@@ -0,0 +1,30 @@
1
+ /** Read-only catalog snapshot. Never executes user-supplied SQL or changes session state. */
2
+ export async function inspectDatabase(query, { limit = 50 } = {}) {
3
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new Error('limit must be between 1 and 200');
4
+ const version = await query('SHOW server_version_num');
5
+ const versionNum = Number(version.rows?.[0]?.server_version_num);
6
+ if (!Number.isInteger(versionNum) || versionNum < 100000) throw new Error('Unable to determine PostgreSQL server version');
7
+ const tables = await query(`SELECT n.nspname AS schema_name, c.relname AS table_name,
8
+ c.reltuples::bigint AS estimated_rows, pg_total_relation_size(c.oid) AS bytes
9
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
10
+ WHERE c.relkind IN ('r','p') AND n.nspname NOT IN ('pg_catalog','information_schema')
11
+ AND n.nspname NOT LIKE 'pg_toast%' ORDER BY pg_total_relation_size(c.oid) DESC LIMIT $1`, [limit]);
12
+ return { postgresVersion: Math.floor(versionNum / 10000), source: 'read-only PostgreSQL catalog', confidence: 'estimates', tables: tables.rows.map(r => ({ schema: r.schema_name, table: r.table_name, estimatedRows: Number(r.estimated_rows), bytes: Number(r.bytes) })) };
13
+ }
14
+
15
+ export async function inspectDatabaseUrl(url, options) {
16
+ if (!url) throw new Error('Database URL is required');
17
+ let pg;
18
+ try { pg = await import('pg'); }
19
+ catch { throw new Error('Database inspection requires the optional pg package: npm install pg'); }
20
+ const client = new pg.default.Client({ connectionString: url, connectionTimeoutMillis: 5000, query_timeout: 5000, statement_timeout: 5000, application_name: 'pg-safe-migrate-inspect' });
21
+ try {
22
+ await client.connect();
23
+ // Read-only transaction protects against accidental writes; query budget is bounded.
24
+ await client.query('BEGIN READ ONLY');
25
+ await client.query("SET LOCAL statement_timeout = '5s'");
26
+ const result = await inspectDatabase((sql, params) => client.query(sql, params), options);
27
+ await client.query('ROLLBACK');
28
+ return result;
29
+ } finally { await client.end(); }
30
+ }
@@ -0,0 +1,25 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ function scan(dir) {
4
+ const results = [];
5
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
6
+ const full = path.join(dir, entry.name);
7
+ if (entry.isDirectory()) results.push(...scan(full));
8
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.sql')) results.push(full);
9
+ }
10
+ return results;
11
+ }
12
+ export function findMigrationFiles(targetPath) {
13
+ if (targetPath) {
14
+ if (!fs.existsSync(targetPath)) throw new Error(`Path not found: ${targetPath}`);
15
+ if (fs.statSync(targetPath).isFile()) {
16
+ if (!targetPath.toLowerCase().endsWith('.sql')) throw new Error('Target must be a .sql file.');
17
+ return [targetPath];
18
+ }
19
+ return scan(targetPath).sort();
20
+ }
21
+ const dirs = ['prisma/migrations', 'drizzle', 'migrations', 'db/migrations', 'db/migration', 'sql/migrations', 'sql'];
22
+ const files = [...new Set(dirs.filter(d => fs.existsSync(d) && fs.statSync(d).isDirectory()).flatMap(scan))].sort();
23
+ if (!files.length) throw new Error('No SQL migrations found. Supply a file or directory.');
24
+ return files;
25
+ }
package/src/engine.js ADDED
@@ -0,0 +1,48 @@
1
+
2
+ import { additionalRules } from './rules/additionalRules.js';
3
+ import { concurrentIndexRule } from './rules/concurrentIndex.js';
4
+ import { dropColumnRule } from './rules/dropColumn.js';
5
+ import { alterTableRules, renameRule } from './rules/alterTableRules.js';
6
+ import { versionRules } from './rules/versionRules.js';
7
+ import { operationalRiskRules } from './rules/operationalRiskRules.js';
8
+ import { dataIntegrityRules } from './rules/dataIntegrityRules.js';
9
+
10
+ const ACTIVE_RULES = [
11
+ concurrentIndexRule,
12
+ dropColumnRule,
13
+ alterTableRules,
14
+ renameRule,
15
+ additionalRules,
16
+ versionRules,
17
+ operationalRiskRules,
18
+ dataIntegrityRules
19
+ ];
20
+
21
+ export function lintStatements(stmts, context = {}) {
22
+ const violations = [];
23
+
24
+ for (const stmt of stmts) {
25
+ const findings = [];
26
+
27
+ for (const rule of ACTIVE_RULES) {
28
+ const result = rule.check(stmt, context);
29
+ if (!result) continue;
30
+
31
+ if (Array.isArray(result)) {
32
+ findings.push(...result);
33
+ } else {
34
+ findings.push(result);
35
+ }
36
+ }
37
+
38
+ // PG025 provides more specific guidance for SET NOT NULL.
39
+ // Suppress PG013 only for this statement when PG025 exists.
40
+ const hasPG025 = findings.some(f => f.ruleId === 'PG025');
41
+
42
+ violations.push(
43
+ ...findings.filter(f => !(hasPG025 && f.ruleId === 'PG013'))
44
+ );
45
+ }
46
+
47
+ return violations;
48
+ }
package/src/gitDiff.js ADDED
@@ -0,0 +1,33 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ function git(args, cwd) {
6
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
7
+ }
8
+ function names(args, cwd) {
9
+ return git(args, cwd).split('\0').filter(Boolean);
10
+ }
11
+ export function getChangedSqlFiles(baseBranch, cwd = process.cwd()) {
12
+ let root;
13
+ try { root = git(['rev-parse', '--show-toplevel'], cwd); }
14
+ catch { throw new Error('Not inside a Git repository.'); }
15
+ const changed = new Set();
16
+ if (baseBranch) {
17
+ try {
18
+ git(['rev-parse', '--verify', `${baseBranch}^{commit}`], root);
19
+ for (const f of names(['diff', '--name-only', '-z', '--diff-filter=ACMR', `${baseBranch}...HEAD`, '--'], root)) changed.add(f);
20
+ } catch { throw new Error(`Git base ref not available: ${baseBranch}. Fetch the base branch before running --changed.`); }
21
+ }
22
+ for (const args of [
23
+ ['diff', '--name-only', '-z', '--diff-filter=ACMR', '--cached', '--'],
24
+ ['diff', '--name-only', '-z', '--diff-filter=ACMR', '--'],
25
+ ['ls-files', '--others', '--exclude-standard', '-z']
26
+ ]) {
27
+ try { for (const f of names(args, root)) changed.add(f); }
28
+ catch (e) { throw new Error(`Git change detection failed: ${e.message}`); }
29
+ }
30
+ return [...changed].filter(f => f.toLowerCase().endsWith('.sql'))
31
+ .map(f => path.resolve(root, f))
32
+ .filter(f => fs.existsSync(f) && fs.statSync(f).isFile()).sort();
33
+ }
package/src/github.js ADDED
@@ -0,0 +1,17 @@
1
+ function escapeCommand(s) {
2
+ return String(s).replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
3
+ }
4
+ function escapeProperty(s) {
5
+ return escapeCommand(s).replaceAll(':', '%3A').replaceAll(',', '%2C');
6
+ }
7
+ export function toGitHubAnnotations(findings) {
8
+ return findings.map(f => `::${f.severity === 'error' ? 'error' : 'warning'} file=${escapeProperty(f.file)},line=${Math.max(1, f.line || 1)},col=${Math.max(1, f.column || 1)},title=${escapeProperty(f.ruleId)}::${escapeCommand(f.message)} Fix: ${escapeCommand(f.fix)}`).join('\n') + (findings.length ? '\n' : '');
9
+ }
10
+ export function toMarkdownSummary(findings, filesChecked) {
11
+ const errors = findings.filter(f => f.severity === 'error').length;
12
+ const warnings = findings.length - errors;
13
+ const lines = ['## PostgreSQL migration safety', '', `Checked ${filesChecked} file(s): **${errors} error(s)**, **${warnings} warning(s)**.`, '', '| Rule | Severity | Location | Finding |', '|---|---|---|---|'];
14
+ for (const f of findings) lines.push(`| ${f.ruleId} | ${f.severity} | \`${String(f.file).replaceAll('|', '\\|')}:${f.line}\` | ${f.message.replaceAll('|', '\\|').replaceAll('\n', ' ')} |`);
15
+ lines.push('', '> Static heuristic analysis, not a guarantee of zero downtime.', '');
16
+ return lines.join('\n');
17
+ }