@subodh001/pg-safe-migrate 0.0.0-stage → 1.1.2

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 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,66 @@
1
- # Temporary Holding Version
1
+ # pg-safe-migrate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An AST-based PostgreSQL migration **risk** linter for Prisma, Drizzle, and raw SQL. It flags six common migration patterns that may cause blocking locks or application compatibility failures. **It does not guarantee zero downtime.**
4
+
5
+ ## Quick start
6
+
7
+ ```sh
8
+ npx --yes --package=@subodh001/pg-safe-migrate@1.1.1 pg-safe-migrate --help
9
+ npm install --save-dev @subodh001/pg-safe-migrate
10
+ npx pg-safe-migrate prisma/migrations
11
+ npx pg-safe-migrate drizzle
12
+ npx pg-safe-migrate db/migrations
13
+ npx pg-safe-migrate --changed origin/main
14
+ ```
15
+
16
+ The default scan searches `prisma/migrations`, `drizzle`, `migrations`, and `db/migrations`. For any other directory, provide its path. `--changed` without a base checks staged, unstaged and untracked SQL; with a base, it additionally checks branch changes. For pull requests, fetch the base branch first (`fetch-depth: 0` in GitHub Actions).
17
+
18
+ ## Rules
19
+
20
+ | Rule | Flagged pattern | Reason |
21
+ | --- | --- | --- |
22
+ | PG001 | CREATE INDEX without CONCURRENTLY | Blocks writes during index build |
23
+ | PG002 | DROP COLUMN | May break old app versions |
24
+ | PG003 | ALTER COLUMN TYPE | Strong lock and possible rewrite |
25
+ | PG004 | ADD COLUMN NOT NULL without DEFAULT | Backfill/compatibility risk |
26
+ | PG005 | ADD FOREIGN KEY without NOT VALID | Validation can block writes |
27
+ | PG006 | RENAME | May break old app versions |
28
+
29
+ A passing result means **no configured patterns were found**, not that a migration is production-safe. Evaluate PostgreSQL version, lock timeout, data volume, long-running transactions, ORM transaction wrapping, and deployment sequencing separately.
30
+
31
+ ## GitHub Actions
32
+
33
+ Copy [`examples/consumer-workflow.yml`](examples/consumer-workflow.yml) into your application's `.github/workflows/pg-safe-migrate.yml`. It checks SQL files changed in a PR and doesn't require fixing historical migrations. Pin the package to an audited version, and upgrade deliberately.
34
+
35
+ ## Verify the published CLI
36
+
37
+ From a clean directory:
38
+
39
+ ```sh
40
+ npx --yes --package=@subodh001/pg-safe-migrate@1.1.1 pg-safe-migrate --help
41
+ ```
42
+
43
+ Create `unsafe.sql` containing `CREATE INDEX idx_users_email ON users(email);`, then run:
44
+
45
+ ```sh
46
+ npx --yes --package=@subodh001/pg-safe-migrate@1.1.1 pg-safe-migrate unsafe.sql
47
+ ```
48
+
49
+ Expect `PG001` and exit code 1. The sample `examples/safe.sql` uses `CONCURRENTLY` and should pass PG001; it must run outside a transaction.
50
+
51
+ ## Development
52
+
53
+ ```sh
54
+ npm install
55
+ npm test
56
+ node bin/cli.js test/unsafe_migration.sql
57
+ npm pack --dry-run
58
+ ```
59
+
60
+ For reproducible CI, commit the generated `package-lock.json` and replace `npm install` in the project's CI with `npm ci`.
61
+
62
+ ## Limitations
63
+
64
+ This is a static AST linter, not a database execution simulator. It does not connect to production, estimate lock wait time, validate migration rollback, or understand the live schema. `--changed` checks changed SQL files, not SQL inside changed JavaScript/TypeScript files. Some flagged operations can be acceptable under controlled conditions, and some unflagged operations can still cause downtime.
65
+
66
+ MIT licensed. Issues and edge-case reproductions welcome.
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.2')
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,47 @@
1
1
  {
2
2
  "name": "@subodh001/pg-safe-migrate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.2",
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
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/subodhsingh001/pg-safe-migrate.git"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/subodhsingh001/pg-safe-migrate/issues"
45
+ },
46
+ "homepage": "https://github.com/subodhsingh001/pg-safe-migrate#readme"
47
+ }
@@ -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
+ };