@subodh001/pg-safe-migrate 0.0.0-stage → 1.1.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.
- package/LICENSE +9 -0
- package/README.md +29 -2
- package/bin/cli.js +61 -0
- package/package.json +37 -4
- package/src/detector.js +25 -0
- package/src/engine.js +26 -0
- package/src/gitDiff.js +33 -0
- package/src/parser.js +13 -0
- package/src/rules/alterTableRules.js +65 -0
- package/src/rules/concurrentIndex.js +18 -0
- package/src/rules/dropColumn.js +12 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pg-safe-migrate contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pg-safe-migrate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AST-based PostgreSQL migration **risk** linter for Prisma, Drizzle and SQL folders. Static checks do **not** guarantee zero downtime. PostgreSQL version, table size, locks, transaction boundaries and deployment order matter.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install
|
|
9
|
+
npm test
|
|
10
|
+
node bin/cli.js test/unsafe_migration.sql
|
|
11
|
+
node bin/cli.js --changed
|
|
12
|
+
node bin/cli.js --changed origin/main
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`--changed` includes staged, unstaged and untracked SQL files; with a base ref it also includes added/modified/renamed SQL files from the branch diff. Fetch the base ref in CI. When no argument is supplied the CLI scans all recognized migration directories.
|
|
16
|
+
|
|
17
|
+
## Rules
|
|
18
|
+
|
|
19
|
+
- PG001: CREATE INDEX without CONCURRENTLY (blocks writes)
|
|
20
|
+
- PG002: DROP COLUMN (application compatibility)
|
|
21
|
+
- PG003: ALTER COLUMN TYPE (locking/rewrite risk, depending on change)
|
|
22
|
+
- PG004: ADD NOT NULL column without DEFAULT (backfill/deployment risk)
|
|
23
|
+
- PG005: ADD FOREIGN KEY without NOT VALID (validation lock risk)
|
|
24
|
+
- PG006: RENAME (application compatibility)
|
|
25
|
+
|
|
26
|
+
Exit code 1 indicates issues or an error; 0 means no configured issues detected. Review changes with a DBA before production use. Some safe migration sequences still require lock_timeout, retries, explicit nontransactional execution and coordination across app versions.
|
|
27
|
+
|
|
28
|
+
## Publishing
|
|
29
|
+
|
|
30
|
+
Set the repository URL in package.json, then run `npm ci && npm test && npm pack --dry-run`. Confirm the npm package name is available and publish only after reviewing the package contents.
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import { program } from 'commander';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import { parseSqlFile } from '../src/parser.js';
|
|
6
|
+
import { lintStatements } from '../src/engine.js';
|
|
7
|
+
import { findMigrationFiles } from '../src/detector.js';
|
|
8
|
+
import { getChangedSqlFiles } from '../src/gitDiff.js';
|
|
9
|
+
|
|
10
|
+
program
|
|
11
|
+
.name('pg-safe-migrate')
|
|
12
|
+
.description('Deterministic AST linter for zero-downtime PostgreSQL migrations')
|
|
13
|
+
.version('1.1.1')
|
|
14
|
+
.argument('[target]', 'Path to a .sql file or migrations directory')
|
|
15
|
+
.option('-c, --changed [baseBranch]', 'Lint changed SQL files (optionally compare with a base ref)')
|
|
16
|
+
.action(async (target, options) => {
|
|
17
|
+
try {
|
|
18
|
+
let files = [];
|
|
19
|
+
|
|
20
|
+
if (options.changed) {
|
|
21
|
+
const baseBranch = typeof options.changed === 'string' ? options.changed : undefined;
|
|
22
|
+
files = getChangedSqlFiles(baseBranch);
|
|
23
|
+
if (files.length === 0) {
|
|
24
|
+
console.log(chalk.green('✔ No changed .sql files found.'));
|
|
25
|
+
process.exit(0);
|
|
26
|
+
}
|
|
27
|
+
} else {
|
|
28
|
+
files = findMigrationFiles(target);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let totalIssues = 0;
|
|
32
|
+
|
|
33
|
+
for (const file of files) {
|
|
34
|
+
const sql = fs.readFileSync(file, 'utf-8');
|
|
35
|
+
const stmts = await parseSqlFile(sql);
|
|
36
|
+
const issues = lintStatements(stmts);
|
|
37
|
+
|
|
38
|
+
if (issues.length > 0) {
|
|
39
|
+
totalIssues += issues.length;
|
|
40
|
+
console.log(chalk.bold.underline(`\nFile: ${file}`));
|
|
41
|
+
for (const issue of issues) {
|
|
42
|
+
console.log(chalk.red(` ✖ [${issue.ruleId}] ${issue.message}`));
|
|
43
|
+
console.log(chalk.yellow(` Fix: ${issue.fix}\n`));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (totalIssues === 0) {
|
|
49
|
+
console.log(chalk.green(`✔ Checked ${files.length} migration file(s). No configured migration risks detected (not a downtime guarantee).`));
|
|
50
|
+
process.exit(0);
|
|
51
|
+
} else {
|
|
52
|
+
console.log(chalk.red.bold(`Found ${totalIssues} blocking migration issue(s).`));
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
} catch (err) {
|
|
56
|
+
console.error(chalk.red(`Error: ${err.message}`));
|
|
57
|
+
process.exit(1);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
program.parse();
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@subodh001/pg-safe-migrate",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"description": "PostgreSQL AST migration risk linter for Prisma, Drizzle and SQL",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"pg-safe-migrate": "bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "node --test",
|
|
11
|
+
"lint": "node bin/cli.js",
|
|
12
|
+
"pack:check": "npm pack --dry-run"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"postgresql",
|
|
16
|
+
"postgres",
|
|
17
|
+
"migration",
|
|
18
|
+
"linter",
|
|
19
|
+
"prisma",
|
|
20
|
+
"drizzle",
|
|
21
|
+
"zero-downtime",
|
|
22
|
+
"ast"
|
|
23
|
+
],
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"chalk": "^5.3.0",
|
|
27
|
+
"commander": "^12.1.0",
|
|
28
|
+
"libpg-query": "^16.2.1"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=18.0.0"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin/",
|
|
35
|
+
"src/",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
]
|
|
39
|
+
}
|
package/src/detector.js
ADDED
|
@@ -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'];
|
|
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,26 @@
|
|
|
1
|
+
import { concurrentIndexRule } from './rules/concurrentIndex.js';
|
|
2
|
+
import { dropColumnRule } from './rules/dropColumn.js';
|
|
3
|
+
import { alterTableRules, renameRule } from './rules/alterTableRules.js';
|
|
4
|
+
|
|
5
|
+
const ACTIVE_RULES = [
|
|
6
|
+
concurrentIndexRule,
|
|
7
|
+
dropColumnRule,
|
|
8
|
+
alterTableRules,
|
|
9
|
+
renameRule
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
export function lintStatements(stmts) {
|
|
13
|
+
const violations = [];
|
|
14
|
+
for (const stmt of stmts) {
|
|
15
|
+
for (const rule of ACTIVE_RULES) {
|
|
16
|
+
const result = rule.check(stmt);
|
|
17
|
+
if (!result) continue;
|
|
18
|
+
if (Array.isArray(result)) {
|
|
19
|
+
violations.push(...result);
|
|
20
|
+
} else {
|
|
21
|
+
violations.push(result);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return violations;
|
|
26
|
+
}
|
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/parser.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import pgQuery from 'libpg-query';
|
|
2
|
+
|
|
3
|
+
export async function parseSqlFile(sqlContent) {
|
|
4
|
+
if (!sqlContent || !sqlContent.trim()) {
|
|
5
|
+
return [];
|
|
6
|
+
}
|
|
7
|
+
try {
|
|
8
|
+
const result = await pgQuery.parse(sqlContent);
|
|
9
|
+
return (result.stmts || []).map((s) => s.stmt);
|
|
10
|
+
} catch (err) {
|
|
11
|
+
throw new Error(`SQL Syntax Error: ${err.message}`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -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,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
|
+
};
|