@subodh001/pg-safe-migrate 2.0.0 → 2.3.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.
@@ -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
+ };
@@ -0,0 +1,33 @@
1
+ /** Public metadata for implemented safety diagnostics. This does not change lint behavior. */
2
+ const definitions = [
3
+ ['PG001','Non-concurrent index creation','locking','ERROR',null,'Use CREATE INDEX CONCURRENTLY outside a transaction.'],
4
+ ['PG002','Dropping a column','data-loss','ERROR',null,'Deprecate consumers before removing the column.'],
5
+ ['PG003','Changing a column type','rewrite','ERROR',null,'Check binary compatibility; consider expand/backfill/contract.'],
6
+ ['PG004','Adding NOT NULL column without default','constraint','ERROR',null,'Add nullable, backfill, then enforce NOT NULL.'],
7
+ ['PG005','Adding validated foreign key','locking','ERROR',null,'Add NOT VALID then VALIDATE CONSTRAINT separately.'],
8
+ ['PG006','Renaming an object','compatibility','ERROR',null,'Use an expand/contract deployment.'],
9
+ ['PG007','Dropping index without CONCURRENTLY','locking','ERROR',null,'Use DROP INDEX CONCURRENTLY where supported.'],
10
+ ['PG008','Concurrent index operation inside transaction','compatibility','ERROR',null,'Run outside BEGIN/COMMIT.'],
11
+ ['PG011','Dropping a table','data-loss','ERROR',null,'Verify retention and application dependencies.'],
12
+ ['PG015','Prisma concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
13
+ ['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.'],
15
+ ['PG019','MERGE requires PostgreSQL 15+','version','ERROR',15,'Use a compatible INSERT ... ON CONFLICT pattern where applicable.'],
16
+ ['PG020','UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+','version','ERROR',15,'Use a version-compatible uniqueness strategy.'],
17
+ ['PG021','Volatile default may rewrite table','rewrite','ERROR',null,'Add column, backfill in batches, then set default.'],
18
+ ['PG022','SET LOGGED rewrites table','rewrite','ERROR',null,'Schedule controlled maintenance and evaluate alternatives.'],
19
+ ['PG023','TRUNCATE removes table rows','data-loss','ERROR',null,'Confirm retention, backups and downstream dependencies.'],
20
+ ['PG024','Dropping a constraint','constraint','WARNING',null,'Review dependent queries and data-integrity requirements.'],
21
+ ['PG025','SET NOT NULL may scan table','constraint','WARNING',null,'Backfill and validate a CHECK constraint first where appropriate.']
22
+ ];
23
+
24
+ export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,minPostgresVersion,recommendation})));
25
+
26
+ export function getRule(id) {
27
+ return RULE_CATALOG.find(rule => rule.id === String(id).toUpperCase()) ?? null;
28
+ }
29
+
30
+ export function searchRules(query = '') {
31
+ const needle = String(query).trim().toLowerCase();
32
+ return RULE_CATALOG.filter(rule => Object.values(rule).some(value => value != null && String(value).toLowerCase().includes(needle)));
33
+ }
@@ -0,0 +1,16 @@
1
+ /** Compatibility facts used by the static version rules (not a complete SQL feature matrix). */
2
+ export const VERSION_FEATURES = Object.freeze({
3
+ merge: Object.freeze({ minVersion: 15, ruleId: 'PG019', label: 'MERGE statement' }),
4
+ nullsNotDistinct: Object.freeze({ minVersion: 15, ruleId: 'PG020', label: 'UNIQUE NULLS NOT DISTINCT' })
5
+ });
6
+
7
+ export function getVersionCompatibility(feature, targetVersion) {
8
+ const definition = VERSION_FEATURES[feature];
9
+ if (!definition) throw new RangeError(`Unknown PostgreSQL feature: ${feature}`);
10
+ if (targetVersion == null) return { ...definition, supported: null };
11
+ const version = Number(targetVersion);
12
+ if (!Number.isInteger(version) || version < 10 || version > 99) {
13
+ throw new RangeError('PostgreSQL target version must be an integer from 10 to 99');
14
+ }
15
+ return { ...definition, supported: version >= definition.minVersion };
16
+ }
@@ -0,0 +1,49 @@
1
+ import { getVersionCompatibility } from './versionCatalog.js';
2
+
3
+ /** Static PostgreSQL feature compatibility checks; they do not execute SQL. */
4
+ export const versionRules = {
5
+ id: 'PG019',
6
+ name: 'postgres-version-compatibility',
7
+ check(stmt, context = {}) {
8
+ const version = context.postgresVersion;
9
+ if (version == null) return [];
10
+ const major = Number(version);
11
+ if (!Number.isInteger(major) || major < 10 || major > 99) return [];
12
+
13
+ const issues = [];
14
+ if (stmt.MergeStmt && !getVersionCompatibility('merge', major).supported) {
15
+ issues.push({
16
+ ruleId: 'PG019',
17
+ message: `MERGE requires PostgreSQL 15 or later; target version is ${major}.`,
18
+ fix: 'Use a version-compatible INSERT ... ON CONFLICT or UPDATE/INSERT strategy, or upgrade PostgreSQL.'
19
+ });
20
+ }
21
+
22
+ // libpg-query versions may use snake_case or camelCase AST fields.
23
+ const hasNullsNotDistinct = (node) =>
24
+ node?.nullsNotDistinct === true || node?.nulls_not_distinct === true;
25
+ const isUnique = (node) => node?.contype === 'CONSTR_UNIQUE';
26
+
27
+ const uniqueIndex = stmt.IndexStmt;
28
+ const uniqueConstraint = stmt.AlterTableStmt?.cmds?.some(cmd => {
29
+ const constraint = cmd.AlterTableCmd?.def?.Constraint;
30
+ return isUnique(constraint) && hasNullsNotDistinct(constraint);
31
+ }) ?? false;
32
+ const createTableConstraint = stmt.CreateStmt?.tableElts?.some(el => {
33
+ const constraint = el.Constraint;
34
+ return isUnique(constraint) && hasNullsNotDistinct(constraint);
35
+ }) ?? false;
36
+ const usesNullsNotDistinct =
37
+ (uniqueIndex?.unique === true && hasNullsNotDistinct(uniqueIndex)) ||
38
+ uniqueConstraint || createTableConstraint;
39
+
40
+ if (usesNullsNotDistinct && !getVersionCompatibility('nullsNotDistinct', major).supported) {
41
+ issues.push({
42
+ ruleId: 'PG020',
43
+ message: `UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15 or later; target version is ${major}.`,
44
+ fix: 'Use a PostgreSQL 14-compatible uniqueness strategy after reviewing NULL semantics, or upgrade PostgreSQL.'
45
+ });
46
+ }
47
+ return issues;
48
+ }
49
+ };
@@ -0,0 +1,135 @@
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([
62
+ 'exec', name,
63
+ 'pg_isready',
64
+ '-h', '127.0.0.1',
65
+ '-p', '5432',
66
+ '-U', 'postgres',
67
+ '-d', 'postgres'
68
+ ], { timeout: 5000 });
69
+ if (result.status === 0) { ready = true; break; }
70
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
71
+ }
72
+ if (!ready) throw new Error('Disposable PostgreSQL did not become ready within 30 seconds');
73
+ const execute = (step, stage) => {
74
+ const result = call([
75
+ 'exec', '-i', name,
76
+ 'psql',
77
+ '-h', '127.0.0.1',
78
+ '-p', '5432',
79
+ '-X',
80
+ '-v', 'ON_ERROR_STOP=1',
81
+ '-U', 'postgres',
82
+ '-d', 'postgres',
83
+ '-f', '-'
84
+ ], {
85
+ input: step.sql,
86
+ timeout: timeoutSeconds * 1000
87
+ });
88
+ return {
89
+ stage, file: step.file, passed: result.status === 0,
90
+ stdout: (result.stdout || '').slice(-4000), stderr: (result.stderr || '').slice(-4000),
91
+ exitCode: result.status
92
+ };
93
+ };
94
+ const steps = [];
95
+ if (baselineStep) {
96
+ const result = execute(baselineStep, 'baseline');
97
+ steps.push(result);
98
+ if (!result.passed) return summary(result, steps, postgresVersion);
99
+ }
100
+ for (const target of targets) {
101
+ const result = execute(target, 'migration');
102
+ steps.push(result);
103
+ if (!result.passed) return summary(result, steps, postgresVersion);
104
+ }
105
+ if (verification) {
106
+ const result = execute(verification, 'verification');
107
+ steps.push(result);
108
+ if (!result.passed) return summary(result, steps, postgresVersion);
109
+ }
110
+ return summary(steps.at(-1), steps, postgresVersion);
111
+ } catch (error) {
112
+ primaryError = error;
113
+ throw error;
114
+ } finally {
115
+ if (created) {
116
+ try {
117
+ const removed = call(['rm', '-f', name], { timeout: 30000 });
118
+ if (removed.status !== 0) throw new Error((removed.stderr || 'docker rm failed').trim());
119
+ } catch (error) {
120
+ const message = `CRITICAL: Disposable container ${name} could not be removed: ${error.message}`;
121
+ if (primaryError) throw new AggregateError([primaryError, error], message);
122
+ throw new Error(message);
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ function summary(last, steps, postgresVersion) {
129
+ return {
130
+ passed: last.passed, postgresVersion: Number(postgresVersion), isolated: true,
131
+ disposable: true, stage: last.stage, file: last.file,
132
+ stdout: last.stdout, stderr: last.stderr, exitCode: last.exitCode,
133
+ steps, limitation: 'Checks SQL execution against an empty disposable database plus optional baseline; not a downtime, production-data, or rollback guarantee.'
134
+ };
135
+ }
@@ -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
+ }