@subodh001/pg-safe-migrate 1.1.2 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ALL-MILESTONES-TESTING.md +41 -0
- package/README.md +303 -29
- package/bin/cli.js +83 -54
- package/examples/baseline.sql +7 -0
- package/examples/consumer-workflow.yml +35 -0
- package/examples/migrations/001_add_phone.sql +1 -0
- package/examples/migrations/002_add_email_index.sql +1 -0
- package/examples/safe.sql +2 -0
- package/examples/team-policy.json +7 -0
- package/examples/test-unsafe.sql +1 -0
- package/examples/unsafe.sql +2 -0
- package/examples/verify.sql +8 -0
- package/package.json +13 -4
- package/scripts/orm-runner/README.md +35 -0
- package/scripts/orm-runner/package-lock.json +659 -0
- package/scripts/orm-runner/package.json +14 -0
- package/scripts/orm-runner/verify.mjs +360 -0
- package/scripts/test-pg-matrix.cjs +30 -0
- package/src/advisor.js +22 -0
- package/src/analysis.js +258 -0
- package/src/combined.js +60 -0
- package/src/config.js +27 -0
- package/src/db-inspect.js +30 -0
- package/src/engine.js +3 -1
- package/src/github.js +17 -0
- package/src/locks.js +8 -0
- package/src/parser.js +5 -5
- package/src/plans.js +9 -0
- package/src/presets.js +5 -0
- package/src/reports.js +5 -0
- package/src/risk.js +5 -0
- package/src/rules/additionalRules.js +9 -0
- package/src/simulator.js +115 -0
- package/src/team-policy.js +23 -0
package/src/combined.js
ADDED
|
@@ -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);
|
|
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,27 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_CONFIG = Object.freeze({ severity: 'error', rules: {}, exclude: [], postgresVersion: null });
|
|
5
|
+
export function loadConfig(file = 'pg-safe-migrate.config.json') {
|
|
6
|
+
if (!fs.existsSync(file)) return { ...DEFAULT_CONFIG };
|
|
7
|
+
let parsed;
|
|
8
|
+
try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
9
|
+
catch (e) { throw new Error(`Invalid configuration ${file}: ${e.message}`); }
|
|
10
|
+
if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') throw new Error('Configuration must be a JSON object.');
|
|
11
|
+
if (parsed.rules !== undefined && (!parsed.rules || Array.isArray(parsed.rules) || typeof parsed.rules !== 'object')) throw new Error('rules must be an object.');
|
|
12
|
+
if (parsed.exclude !== undefined && (!Array.isArray(parsed.exclude) || parsed.exclude.some(x => typeof x !== 'string'))) throw new Error('exclude must be an array of strings.');
|
|
13
|
+
const rules = parsed.rules || {};
|
|
14
|
+
for (const [id, value] of Object.entries(rules)) {
|
|
15
|
+
if (!/^PG\d{3}$/.test(id) || !['off','warning','error'].includes(value)) throw new Error(`Invalid rule configuration: ${id}=${value}`);
|
|
16
|
+
}
|
|
17
|
+
if (parsed.severity !== undefined && !['warning','error'].includes(parsed.severity)) throw new Error('severity must be warning or error.');
|
|
18
|
+
if (parsed.postgresVersion != null && (!Number.isInteger(parsed.postgresVersion) || parsed.postgresVersion < 10 || parsed.postgresVersion > 99)) throw new Error('postgresVersion must be an integer >= 10.');
|
|
19
|
+
return { ...DEFAULT_CONFIG, ...parsed, rules };
|
|
20
|
+
}
|
|
21
|
+
export function isExcluded(file, patterns, cwd = process.cwd()) {
|
|
22
|
+
const rel = path.relative(cwd, path.resolve(file)).replaceAll('\\','/');
|
|
23
|
+
return patterns.some(pattern => {
|
|
24
|
+
const normalized = pattern.replaceAll('\\','/').replace(/^\.\//,'').replace(/\/$/,'');
|
|
25
|
+
return rel === normalized || rel.startsWith(normalized + '/') || (normalized.startsWith('*.') && rel.endsWith(normalized.slice(1)));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -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
|
+
}
|
package/src/engine.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { additionalRules } from './rules/additionalRules.js';
|
|
1
2
|
import { concurrentIndexRule } from './rules/concurrentIndex.js';
|
|
2
3
|
import { dropColumnRule } from './rules/dropColumn.js';
|
|
3
4
|
import { alterTableRules, renameRule } from './rules/alterTableRules.js';
|
|
@@ -6,7 +7,8 @@ const ACTIVE_RULES = [
|
|
|
6
7
|
concurrentIndexRule,
|
|
7
8
|
dropColumnRule,
|
|
8
9
|
alterTableRules,
|
|
9
|
-
renameRule
|
|
10
|
+
renameRule,
|
|
11
|
+
additionalRules
|
|
10
12
|
];
|
|
11
13
|
|
|
12
14
|
export function lintStatements(stmts) {
|
package/src/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
|
+
}
|
package/src/locks.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Conservative, statement-type classification. Does not model lock duration or contention.
|
|
2
|
+
export function lockFor(stmt) {
|
|
3
|
+
if (stmt.AlterTableStmt || stmt.DropStmt?.removeType === 'OBJECT_TABLE' || stmt.RenameStmt) return { mode: 'ACCESS EXCLUSIVE', confidence: 'heuristic', note: 'May block readers/writers; exact mode varies by subcommand.' };
|
|
4
|
+
if (stmt.IndexStmt) return stmt.IndexStmt.concurrent
|
|
5
|
+
? { mode: 'SHARE UPDATE EXCLUSIVE', confidence: 'heuristic', note: 'Concurrent index builds still acquire locks and can wait.' }
|
|
6
|
+
: { mode: 'SHARE', confidence: 'heuristic', note: 'Ordinary index creation can block writes.' };
|
|
7
|
+
return { mode: 'unknown', confidence: 'unknown', note: 'Not classified.' };
|
|
8
|
+
}
|
package/src/parser.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import pgQuery from 'libpg-query';
|
|
2
2
|
|
|
3
|
-
export async function parseSqlFile(sqlContent) {
|
|
4
|
-
if (!sqlContent || !sqlContent.trim())
|
|
5
|
-
return [];
|
|
6
|
-
}
|
|
3
|
+
export async function parseSqlFile(sqlContent, options = {}) {
|
|
4
|
+
if (!sqlContent || !sqlContent.trim()) return [];
|
|
7
5
|
try {
|
|
8
6
|
const result = await pgQuery.parse(sqlContent);
|
|
9
|
-
|
|
7
|
+
const statements = result.stmts || [];
|
|
8
|
+
if (!options.details) return statements.map(s => s.stmt);
|
|
9
|
+
return statements.map(s => ({stmt:s.stmt,offset:typeof s.stmt_location==='number'?s.stmt_location:0}));
|
|
10
10
|
} catch (err) {
|
|
11
11
|
throw new Error(`SQL Syntax Error: ${err.message}`);
|
|
12
12
|
}
|
package/src/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
|
+
}
|
package/src/reports.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export function toJson(findings, meta = {}) { return JSON.stringify({ tool: 'pg-safe-migrate', ...meta, findings }, null, 2); }
|
|
2
|
+
export function toSarif(findings) {
|
|
3
|
+
const ids = [...new Set(findings.map(f => f.ruleId))].sort();
|
|
4
|
+
return JSON.stringify({ version: '2.1.0', $schema: 'https://json.schemastore.org/sarif-2.1.0.json', runs: [{ tool: { driver: { name: 'pg-safe-migrate', informationUri: 'https://github.com/subodhsingh001/pg-safe-migrate', rules: ids.map(id => ({ id, shortDescription: { text: id } })) } }, results: findings.map(f => ({ ruleId: f.ruleId, level: f.severity === 'warning' ? 'warning' : 'error', message: { text: `${f.message} Fix: ${f.fix}` }, locations: [{ physicalLocation: { artifactLocation: { uri: f.file.replaceAll('\\','/') }, region: { startLine: Math.max(1, f.line || 1), startColumn: Math.max(1, f.column || 1) } } }] })) }] }, null, 2);
|
|
5
|
+
}
|
package/src/risk.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const weights = { error: 20, warning: 5 };
|
|
2
|
+
export function summarizeRisk(findings) {
|
|
3
|
+
const score = Math.min(100, findings.reduce((sum, f) => sum + (weights[f.severity] || 0), 0));
|
|
4
|
+
return { score, band: score >= 60 ? 'high' : score >= 20 ? 'moderate' : 'low', confidence: 'low', basis: 'Heuristic severity counts only; no database statistics or production workload context.' };
|
|
5
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const additionalRules = {
|
|
2
|
+
id: 'PG007-PG011',
|
|
3
|
+
check(stmt) {
|
|
4
|
+
const issues = [];
|
|
5
|
+
if (stmt.DropStmt?.removeType === 'OBJECT_INDEX' && !stmt.DropStmt.concurrent) issues.push({ ruleId: 'PG007', severity: 'ERROR', message: 'DROP INDEX without CONCURRENTLY can block concurrent operations.', fix: 'Consider DROP INDEX CONCURRENTLY outside a transaction (not supported with CASCADE).' });
|
|
6
|
+
if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') issues.push({ ruleId: 'PG011', severity: 'ERROR', message: 'DROP TABLE is destructive and may break running application versions.', fix: 'Remove application dependencies first and verify data retention requirements.' });
|
|
7
|
+
return issues;
|
|
8
|
+
}
|
|
9
|
+
};
|
package/src/simulator.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
const MAX_SQL_BYTES = 1024 * 1024;
|
|
7
|
+
const MAX_FILES = 100;
|
|
8
|
+
const ALLOWED_VERSIONS = new Set(['14', '15', '16', '17', '18']);
|
|
9
|
+
|
|
10
|
+
function readSql(file) {
|
|
11
|
+
const resolved = path.resolve(file);
|
|
12
|
+
const stat = fs.statSync(resolved);
|
|
13
|
+
if (!stat.isFile() || stat.size > MAX_SQL_BYTES) throw new Error('SQL file must be a regular file <= 1 MiB');
|
|
14
|
+
const sql = fs.readFileSync(resolved, 'utf8');
|
|
15
|
+
if (!sql.trim()) throw new Error(`SQL file is empty: ${resolved}`);
|
|
16
|
+
return { file: resolved, sql };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function migrationFiles(dir) {
|
|
20
|
+
const root = path.resolve(dir);
|
|
21
|
+
if (!fs.statSync(root).isDirectory()) throw new Error('migrations-dir must be a directory');
|
|
22
|
+
const files = fs.readdirSync(root, { withFileTypes: true })
|
|
23
|
+
.filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.sql'))
|
|
24
|
+
.map(entry => path.join(root, entry.name)).sort();
|
|
25
|
+
if (!files.length || files.length > MAX_FILES) throw new Error('migrations-dir must contain 1-100 top-level .sql files');
|
|
26
|
+
return files.map(readSql);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Run SQL in a disposable, network-isolated PostgreSQL container.
|
|
30
|
+
* Baseline and target steps are separate. Not a production safety or rollback guarantee.
|
|
31
|
+
*/
|
|
32
|
+
export function simulateSqlFile(file, {
|
|
33
|
+
postgresVersion = '16', timeoutSeconds = 60, baseline,
|
|
34
|
+
migrationsDir, verifySql, run = spawnSync
|
|
35
|
+
} = {}) {
|
|
36
|
+
if (!ALLOWED_VERSIONS.has(String(postgresVersion))) throw new Error('Simulation supports PostgreSQL 14-18');
|
|
37
|
+
if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 10 || timeoutSeconds > 300) throw new Error('timeoutSeconds must be 10-300');
|
|
38
|
+
if (file && migrationsDir) throw new Error('Use either --simulate <file> or --migrations-dir, not both');
|
|
39
|
+
if (!file && !migrationsDir) throw new Error('Provide a SQL file or --migrations-dir');
|
|
40
|
+
const baselineStep = baseline ? readSql(baseline) : null;
|
|
41
|
+
const targets = migrationsDir ? migrationFiles(migrationsDir) : [readSql(file)];
|
|
42
|
+
const verification = verifySql ? readSql(verifySql) : null;
|
|
43
|
+
const name = `pg-safe-sim-${randomUUID().slice(0, 12)}`;
|
|
44
|
+
const image = `postgres:${postgresVersion}`;
|
|
45
|
+
const call = (args, options = {}) => {
|
|
46
|
+
const result = run('docker', args, {
|
|
47
|
+
encoding: 'utf8', timeout: options.timeout ?? 15000,
|
|
48
|
+
input: options.input, maxBuffer: 2 * 1024 * 1024, windowsHide: true
|
|
49
|
+
});
|
|
50
|
+
if (result.error) throw new Error(`Docker ${args[0]} failed: ${result.error.message}`);
|
|
51
|
+
return result;
|
|
52
|
+
};
|
|
53
|
+
let created = false;
|
|
54
|
+
let primaryError;
|
|
55
|
+
try {
|
|
56
|
+
const started = call(['run', '-d', '--name', name, '--network', 'none', '--memory', '512m', '--cpus', '1', '--pids-limit', '128', '--security-opt', 'no-new-privileges', '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', image], { timeout: 120000 });
|
|
57
|
+
if (started.status !== 0) throw new Error(`Docker could not start disposable PostgreSQL: ${(started.stderr || '').trim()}`);
|
|
58
|
+
created = true;
|
|
59
|
+
let ready = false;
|
|
60
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
61
|
+
const result = call(['exec', name, 'pg_isready', '-U', 'postgres'], { timeout: 5000 });
|
|
62
|
+
if (result.status === 0) { ready = true; break; }
|
|
63
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
|
|
64
|
+
}
|
|
65
|
+
if (!ready) throw new Error('Disposable PostgreSQL did not become ready within 30 seconds');
|
|
66
|
+
const execute = (step, stage) => {
|
|
67
|
+
const result = call(['exec', '-i', name, 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'postgres', '-f', '-'], { input: step.sql, timeout: timeoutSeconds * 1000 });
|
|
68
|
+
return {
|
|
69
|
+
stage, file: step.file, passed: result.status === 0,
|
|
70
|
+
stdout: (result.stdout || '').slice(-4000), stderr: (result.stderr || '').slice(-4000),
|
|
71
|
+
exitCode: result.status
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
const steps = [];
|
|
75
|
+
if (baselineStep) {
|
|
76
|
+
const result = execute(baselineStep, 'baseline');
|
|
77
|
+
steps.push(result);
|
|
78
|
+
if (!result.passed) return summary(result, steps, postgresVersion);
|
|
79
|
+
}
|
|
80
|
+
for (const target of targets) {
|
|
81
|
+
const result = execute(target, 'migration');
|
|
82
|
+
steps.push(result);
|
|
83
|
+
if (!result.passed) return summary(result, steps, postgresVersion);
|
|
84
|
+
}
|
|
85
|
+
if (verification) {
|
|
86
|
+
const result = execute(verification, 'verification');
|
|
87
|
+
steps.push(result);
|
|
88
|
+
if (!result.passed) return summary(result, steps, postgresVersion);
|
|
89
|
+
}
|
|
90
|
+
return summary(steps.at(-1), steps, postgresVersion);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
primaryError = error;
|
|
93
|
+
throw error;
|
|
94
|
+
} finally {
|
|
95
|
+
if (created) {
|
|
96
|
+
try {
|
|
97
|
+
const removed = call(['rm', '-f', name], { timeout: 30000 });
|
|
98
|
+
if (removed.status !== 0) throw new Error((removed.stderr || 'docker rm failed').trim());
|
|
99
|
+
} catch (error) {
|
|
100
|
+
const message = `CRITICAL: Disposable container ${name} could not be removed: ${error.message}`;
|
|
101
|
+
if (primaryError) throw new AggregateError([primaryError, error], message);
|
|
102
|
+
throw new Error(message);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function summary(last, steps, postgresVersion) {
|
|
109
|
+
return {
|
|
110
|
+
passed: last.passed, postgresVersion: Number(postgresVersion), isolated: true,
|
|
111
|
+
disposable: true, stage: last.stage, file: last.file,
|
|
112
|
+
stdout: last.stdout, stderr: last.stderr, exitCode: last.exitCode,
|
|
113
|
+
steps, limitation: 'Checks SQL execution against an empty disposable database plus optional baseline; not a downtime, production-data, or rollback guarantee.'
|
|
114
|
+
};
|
|
115
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
|
|
3
|
+
export function loadTeamPolicy(file) {
|
|
4
|
+
const policy = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
5
|
+
if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new Error('Team policy must be a JSON object');
|
|
6
|
+
const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation'];
|
|
7
|
+
for (const key of Object.keys(policy)) if (!allowed.includes(key)) throw new Error(`Unknown team policy key: ${key}`);
|
|
8
|
+
if (policy.maxRiskScore !== undefined && (!Number.isInteger(policy.maxRiskScore) || policy.maxRiskScore < 0 || policy.maxRiskScore > 100)) throw new Error('maxRiskScore must be 0-100');
|
|
9
|
+
if (policy.maxWarnings !== undefined && (!Number.isInteger(policy.maxWarnings) || policy.maxWarnings < 0)) throw new Error('maxWarnings must be >= 0');
|
|
10
|
+
if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => !/^PG\d{3}$/.test(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
|
|
11
|
+
if (policy.requireSimulation !== undefined && typeof policy.requireSimulation !== 'boolean') throw new Error('requireSimulation must be boolean');
|
|
12
|
+
return policy;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function assessTeamPolicy(report, policy) {
|
|
16
|
+
const reasons = [];
|
|
17
|
+
const findings = report.lint.findings;
|
|
18
|
+
if (policy.requireSimulation && !report.execution?.passed) reasons.push('Simulation must pass');
|
|
19
|
+
if (policy.maxRiskScore !== undefined && report.lint.risk.score > policy.maxRiskScore) reasons.push(`Risk score exceeds ${policy.maxRiskScore}`);
|
|
20
|
+
if (policy.maxWarnings !== undefined && findings.filter(f => f.severity === 'warning').length > policy.maxWarnings) reasons.push(`Warnings exceed ${policy.maxWarnings}`);
|
|
21
|
+
for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
|
|
22
|
+
return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)] };
|
|
23
|
+
}
|