pg-migration-guard

module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2026 License: Apache-2.0

README

Postgres Migration Guard

CI Release Go Reference License

English | 简体中文 | Launch announcement

Ship PostgreSQL migrations with a safety net. Postgres Migration Guard, powered by the mguard CLI, scans raw .sql migrations before deploy and flags changes that can lock large tables, destroy data, break rolling deploys, or create hard-to-roll-back production incidents.

The core rule engine is deterministic and does not require AI. Optional bring-your-own-key AI explanations can make findings easier to understand, but AI never decides severity and never suppresses rule results.

[CRITICAL] MGD001 CREATE INDEX CONCURRENTLY cannot run inside an explicit transaction.
[HIGH]     MGD010 Dropping column legacy_status is destructive.
[HIGH]     MGD030 UPDATE without WHERE can rewrite every row in accounts.

Try It In 30 Seconds

git clone https://github.com/lihua8552-afk/pg-migration-guard.git
cd pg-migration-guard
go run ./cmd/mguard check examples/migrations/001_dangerous.sql --format markdown

Or install the CLI:

go install github.com/lihua8552-afk/pg-migration-guard/cmd/mguard@latest
mguard check migrations --format text --fail-on high

Why Teams Notice It

  • Production-focused migration rules: catches risky indexes, destructive DDL, unsafe DML, table rewrites, invalid SQL, and rolling-deploy incompatibilities.
  • PostgreSQL-aware parsing: uses a PostgreSQL parser backed by WASM with a tokenizer fallback for recoverable parser failures.
  • CI-native outputs: supports text, Markdown, JSON, and SARIF for pull request checks, GitHub summaries, and code scanning dashboards.
  • Optional database metadata: can read table sizes, row estimates, columns, indexes, and constraints through a read-only PostgreSQL connection for more accurate severity.
  • Privacy-conscious AI mode: AI is disabled by default; BYOK providers are optional, and SQL literal redaction is available.
  • GitHub Action included: use the project as a drop-in migration safety gate in pull requests.

Create a config file:

mguard init

Example mguard.yaml:

database:
  dialect: postgres
  dsn_env: DATABASE_URL

migrations:
  paths:
    - migrations
    - db/migrate

risk:
  fail_on: high

ai:
  enabled: false
  provider: openai
  model: ""
  api_key_env: MGUARD_AI_KEY
  base_url: ""
  redact_sql: false

Run against one or more files or directories:

mguard check migrations --format text --fail-on high

GitHub Action

name: Migration Safety

on:
  pull_request:

jobs:
  mguard:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
      - uses: lihua8552-afk/pg-migration-guard@v0.1.1
        with:
          paths: |
            migrations
            db/migrate
          database-url: ${{ secrets.READONLY_DATABASE_URL }}
          fail-on: high
          format: markdown
          comment-pr: "true"
          ai-provider: openai-compatible
          ai-base-url: ${{ secrets.AI_BASE_URL }}
          ai-model: deepseek-chat
          ai-api-key: ${{ secrets.AI_API_KEY }}
          ai-redact: "true"

Optional Database Metadata

mguard can run fully offline. For more accurate risk scoring, set a read-only PostgreSQL DSN:

export DATABASE_URL='postgres://readonly:password@localhost:5432/app?sslmode=require'
mguard check migrations --dsn-env DATABASE_URL

With metadata enabled, mguard reads PostgreSQL catalog views and sets default_transaction_read_only = on. It never executes migrations.

Minimal PostgreSQL role example:

create role mguard_readonly login password 'change-me';
grant connect on database app to mguard_readonly;
grant usage on schema public to mguard_readonly;
grant select on all tables in schema public to mguard_readonly;

AI BYOK

AI explanations are optional. Supported providers are openai, openai-compatible, anthropic, and ollama.

When AI is enabled, mguard sends each finding's rule, severity, file location, SQL statement, reason, and recommendation to the configured provider. Use redact_sql: true or --ai-redact to replace string and numeric SQL literals, including dollar-quoted bodies and E'...'/B'...'/X'...' strings. Table and column names remain visible because they are needed for useful migration advice.

For OpenAI-compatible proxy gateways, set the API key env var, gateway URL, and model:

ai:
  enabled: true
  provider: openai-compatible
  model: deepseek-chat
  api_key_env: MGUARD_AI_KEY
  base_url: https://your-gateway.example.com/v1
  redact_sql: true

base_url may be a /v1 base URL or a full /v1/chat/completions endpoint. You can also pass the same settings from the CLI:

MGUARD_AI_KEY=... mguard check migrations \
  --ai-provider openai-compatible \
  --ai-base-url https://your-gateway.example.com/v1 \
  --ai-model deepseek-chat \
  --ai-redact

Rule Coverage

Rule Detects
MGD000 SQL parser failure
MGD001 CREATE INDEX CONCURRENTLY inside an explicit transaction
MGD002 Plain CREATE INDEX that can block writes
MGD003 Possible duplicate index when metadata shows an equivalent index
MGD010 Destructive DROP COLUMN
MGD011 Irreversible migration without an obvious rollback/down hint
MGD012 Backwards-incompatible column rename
MGD013 Backwards-incompatible table rename
MGD014 Column type change that may rewrite data or take strong locks
MGD015 SET NOT NULL validation risk
MGD016 Adding a NOT NULL column to existing rows
MGD017 Adding unique or primary key constraints
MGD018 Shortening character column length and risking data truncation
MGD020 Destructive DROP TABLE
MGD030 UPDATE or DELETE without WHERE
MGD031 TRUNCATE in a migration

Output Formats

mguard check migrations --format text
mguard check migrations --format markdown
mguard check migrations --format json
mguard check migrations --format sarif

Use SARIF with GitHub code scanning or other security dashboards.

Project Status

mguard is suitable for early CI adoption on raw PostgreSQL .sql migrations. The first release focuses on deterministic safety checks for SQL files. Rails, Prisma, Alembic, and framework-specific migration adapters are good candidates for future work.

Feedback

Tried it on real migrations? Please leave a quick rating or adoption note through the feedback form. The most useful feedback includes:

  • false positives or false negatives, with redacted SQL if possible;
  • missing rules, framework adapters, or CI integrations;
  • what would make the tool trustworthy enough for your release workflow.

Open-ended discussion is welcome in GitHub Discussions.

Development

go test ./...
go vet ./...
staticcheck ./...
govulncheck ./...

Integration tests require PostgreSQL 14+:

MGUARD_TEST_DATABASE_URL='postgres://postgres:postgres@localhost:5432/mguard?sslmode=disable' \
  go test -tags=integration ./...

License

Apache-2.0. See LICENSE.

Directories

Path Synopsis
cmd
mguard command
internal
ai

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL