@subodh001/pg-safe-migrate 2.2.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.
- package/package.json +4 -3
- package/src/analysis.js +1 -1
- package/src/engine.js +9 -3
- package/src/rules/dataIntegrityRules.js +40 -0
- package/src/rules/operationalRiskRules.js +57 -0
- package/src/rules/ruleCatalog.js +33 -0
- package/src/rules/versionCatalog.js +16 -0
- package/src/rules/versionRules.js +49 -0
- package/src/simulator.js +22 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@subodh001/pg-safe-migrate",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "PostgreSQL AST migration risk linter for Prisma, Drizzle and SQL",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -8,10 +8,11 @@
|
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
10
|
"test": "node --test",
|
|
11
|
+
"test:unit": "node scripts/run-unit-tests.cjs",
|
|
12
|
+
"test:integration": "node scripts/test-pg-matrix.cjs",
|
|
11
13
|
"lint": "node bin/cli.js",
|
|
12
14
|
"pack:check": "npm pack --dry-run",
|
|
13
|
-
"test:release": "
|
|
14
|
-
"test:unit": "node --test test/*.test.js test/*.cjs"
|
|
15
|
+
"test:release": "npm run test:unit && node test/release-smoke.cjs"
|
|
15
16
|
},
|
|
16
17
|
"keywords": [
|
|
17
18
|
"postgresql",
|
package/src/analysis.js
CHANGED
package/src/engine.js
CHANGED
|
@@ -2,20 +2,26 @@ import { additionalRules } from './rules/additionalRules.js';
|
|
|
2
2
|
import { concurrentIndexRule } from './rules/concurrentIndex.js';
|
|
3
3
|
import { dropColumnRule } from './rules/dropColumn.js';
|
|
4
4
|
import { alterTableRules, renameRule } from './rules/alterTableRules.js';
|
|
5
|
+
import { versionRules } from './rules/versionRules.js';
|
|
6
|
+
import { operationalRiskRules } from './rules/operationalRiskRules.js';
|
|
7
|
+
import { dataIntegrityRules } from './rules/dataIntegrityRules.js';
|
|
5
8
|
|
|
6
9
|
const ACTIVE_RULES = [
|
|
7
10
|
concurrentIndexRule,
|
|
8
11
|
dropColumnRule,
|
|
9
12
|
alterTableRules,
|
|
10
13
|
renameRule,
|
|
11
|
-
additionalRules
|
|
14
|
+
additionalRules,
|
|
15
|
+
versionRules,
|
|
16
|
+
operationalRiskRules,
|
|
17
|
+
dataIntegrityRules
|
|
12
18
|
];
|
|
13
19
|
|
|
14
|
-
export function lintStatements(stmts) {
|
|
20
|
+
export function lintStatements(stmts, context = {}) {
|
|
15
21
|
const violations = [];
|
|
16
22
|
for (const stmt of stmts) {
|
|
17
23
|
for (const rule of ACTIVE_RULES) {
|
|
18
|
-
const result = rule.check(stmt);
|
|
24
|
+
const result = rule.check(stmt, context);
|
|
19
25
|
if (!result) continue;
|
|
20
26
|
if (Array.isArray(result)) {
|
|
21
27
|
violations.push(...result);
|
|
@@ -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,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
|
+
};
|
package/src/simulator.js
CHANGED
|
@@ -58,13 +58,33 @@ export function simulateSqlFile(file, {
|
|
|
58
58
|
created = true;
|
|
59
59
|
let ready = false;
|
|
60
60
|
for (let attempt = 0; attempt < 30; attempt++) {
|
|
61
|
-
const result = call([
|
|
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 });
|
|
62
69
|
if (result.status === 0) { ready = true; break; }
|
|
63
70
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
|
|
64
71
|
}
|
|
65
72
|
if (!ready) throw new Error('Disposable PostgreSQL did not become ready within 30 seconds');
|
|
66
73
|
const execute = (step, stage) => {
|
|
67
|
-
const result = call([
|
|
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
|
+
});
|
|
68
88
|
return {
|
|
69
89
|
stage, file: step.file, passed: result.status === 0,
|
|
70
90
|
stdout: (result.stdout || '').slice(-4000), stderr: (result.stderr || '').slice(-4000),
|