Skip to main content
hooksSource-backedReview first Safety Privacy

Database Migration Runner - Hooks

PostToolUse hook that detects writes to migration, schema, and SQL files then runs framework-specific status checks — runs knex migrate:status for Node.js projects and python manage.py showmigrations for Django projects.

by JSONbored·added 2025-09-16·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/hooks, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/database-migration-runner.mdx
Safety notes
Runs automatically after write or edit activity on migration, schema, and SQL files., Invokes knex migrate:status for Knex projects and python manage.py showmigrations for Django projects when the respective framework CLI is available., Scans raw SQL for destructive statements and reports warnings but does not apply migrations itself.
Privacy notes
Reads migration, schema, SQL, package, and framework configuration files to infer migration state., Command output may reveal database names, migration names, table names, or schema details in the local hook output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-16

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

3 safety and 2 privacy notes across 3 risk areas.

3 areas
  • SafetyLocal filesRuns automatically after write or edit activity on migration, schema, and SQL files.
  • SafetyGeneralInvokes knex migrate:status for Knex projects and python manage.py showmigrations for Django projects when the respective framework CLI is available.
  • SafetyExecution & processesScans raw SQL for destructive statements and reports warnings but does not apply migrations itself.
  • PrivacyLocal filesReads migration, schema, SQL, package, and framework configuration files to infer migration state.
  • PrivacyExecution & processesCommand output may reveal database names, migration names, table names, or schema details in the local hook output.

Safety notes

  • Runs automatically after write or edit activity on migration, schema, and SQL files.
  • Invokes knex migrate:status for Knex projects and python manage.py showmigrations for Django projects when the respective framework CLI is available.
  • Scans raw SQL for destructive statements and reports warnings but does not apply migrations itself.

Privacy notes

  • Reads migration, schema, SQL, package, and framework configuration files to infer migration state.
  • Command output may reveal database names, migration names, table names, or schema details in the local hook output.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if it's a migration-related file
if [[ "$FILE_PATH" == *migration* ]] || [[ "$FILE_PATH" == *schema* ]] || [[ "$FILE_PATH" == *.sql ]]; then
  echo "🗃️ Database migration file detected: $FILE_PATH" >&2
  
  # Check for Knex migrations
  if [ -f "package.json" ] && grep -q "knex" package.json; then
    echo "📦 Knex migration framework detected" >&2
    
    # Knex migrations
    if command -v npx &> /dev/null && npx knex --version &> /dev/null 2>&1; then
      echo "🔧 Running Knex migration status check..." >&2
      MIGRATION_STATUS=$(npx knex migrate:status 2>/dev/null || echo "No pending migrations")
      echo "📊 Migration Status: $MIGRATION_STATUS" >&2
      
      # Check for pending migrations
      if echo "$MIGRATION_STATUS" | grep -q "pending"; then
        echo "⚠️ Pending migrations detected. Run 'npx knex migrate:latest' to apply them" >&2
      else
        echo "✅ All migrations are up to date" >&2
      fi
      
    fi
    
  # Django migrations
  elif [ -f "manage.py" ]; then
    echo "🐍 Django project detected" >&2
    if command -v python &> /dev/null; then
      echo "🔧 Checking Django migration status..." >&2
      python manage.py showmigrations --plan 2>/dev/null | tail -5 | head -3 || echo "💡 Run 'python manage.py showmigrations' to check status" >&2
    fi
    
  # Raw SQL files
  elif [[ "$FILE_PATH" == *.sql ]]; then
    echo "📜 Raw SQL migration file detected" >&2
    
    # Check file size and complexity
    if [ -f "$FILE_PATH" ]; then
      LINE_COUNT=$(wc -l < "$FILE_PATH" 2>/dev/null || echo "0")
      echo "📊 SQL file contains $LINE_COUNT lines" >&2
      
      # Check for potentially destructive operations
      if grep -i "DROP\|DELETE\|TRUNCATE" "$FILE_PATH" >/dev/null 2>&1; then
        echo "⚠️ WARNING: Potentially destructive SQL operations detected (DROP/DELETE/TRUNCATE)" >&2
        echo "💡 Consider creating a backup before executing this migration" >&2
      fi
      
      # Check for common patterns
      if grep -i "CREATE TABLE\|ALTER TABLE\|CREATE INDEX" "$FILE_PATH" >/dev/null 2>&1; then
        echo "🏗️ Schema modification statements detected" >&2
      fi
      
      if grep -i "INSERT\|UPDATE" "$FILE_PATH" >/dev/null 2>&1; then
        echo "📝 Data modification statements detected" >&2
      fi
    fi
  fi
  
  # General migration best practices reminder
  echo "📋 Migration Best Practices:" >&2
  echo "   • Always backup database before running migrations" >&2
  echo "   • Test migrations on development/staging first" >&2
  echo "   • Ensure migrations are reversible when possible" >&2
  echo "   • Use transactions for atomic operations" >&2
  
else
  echo "File $FILE_PATH is not a migration file, skipping analysis" >&2
fi

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-migration-runner.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

Features

  • Detects writes to migration, schema, and .sql files via PostToolUse and triggers status checks automatically
  • Runs npx knex migrate:status for Node.js projects that include Knex in package.json
  • Runs python manage.py showmigrations --plan for Django projects when manage.py is present
  • Flags pending Knex migrations and prompts the developer to run npx knex migrate:latest
  • Scans raw SQL files for destructive statements (DROP, DELETE, TRUNCATE) and issues warnings before execution
  • Prints migration best-practice reminders (backup, test on staging, reversible migrations, use transactions)

Use Cases

  • Catching unapplied Knex migrations immediately after a schema file is written during development
  • Verifying Django migration state after editing a models.py or migrations file without leaving Claude Code
  • Flagging accidental DROP or TRUNCATE statements in hand-written SQL before they run in a CI pipeline
  • Keeping development, staging, and production schemas in sync by surfacing pending migrations early

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/database-migration-runner.sh
  3. Make executable: chmod +x .claude/hooks/database-migration-runner.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • jq command-line JSON processor
  • Knex 3.x (Node.js) or Django 5.x (Python) installed in the project
  • Node.js and npx available for Knex projects; Python and manage.py present for Django projects

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-migration-runner.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Hook Script

#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if it's a migration-related file
if [[ "$FILE_PATH" == *migration* ]] || [[ "$FILE_PATH" == *schema* ]] || [[ "$FILE_PATH" == *.sql ]]; then
  echo "🗃️ Database migration file detected: $FILE_PATH" >&2

  # Check for Knex migrations
  if [ -f "package.json" ] && grep -q "knex" package.json; then
    echo "📦 Knex migration framework detected" >&2

    # Knex migrations
    if command -v npx &> /dev/null && npx knex --version &> /dev/null 2>&1; then
      echo "🔧 Running Knex migration status check..." >&2
      MIGRATION_STATUS=$(npx knex migrate:status 2>/dev/null || echo "No pending migrations")
      echo "📊 Migration Status: $MIGRATION_STATUS" >&2

      # Check for pending migrations
      if echo "$MIGRATION_STATUS" | grep -q "pending"; then
        echo "⚠️ Pending migrations detected. Run 'npx knex migrate:latest' to apply them" >&2
      else
        echo "✅ All migrations are up to date" >&2
      fi

    fi

  # Django migrations
  elif [ -f "manage.py" ]; then
    echo "🐍 Django project detected" >&2
    if command -v python &> /dev/null; then
      echo "🔧 Checking Django migration status..." >&2
      python manage.py showmigrations --plan 2>/dev/null | tail -5 | head -3 || echo "💡 Run 'python manage.py showmigrations' to check status" >&2
    fi

  # Raw SQL files
  elif [[ "$FILE_PATH" == *.sql ]]; then
    echo "📜 Raw SQL migration file detected" >&2

    # Check file size and complexity
    if [ -f "$FILE_PATH" ]; then
      LINE_COUNT=$(wc -l < "$FILE_PATH" 2>/dev/null || echo "0")
      echo "📊 SQL file contains $LINE_COUNT lines" >&2

      # Check for potentially destructive operations
      if grep -i "DROP\|DELETE\|TRUNCATE" "$FILE_PATH" >/dev/null 2>&1; then
        echo "⚠️ WARNING: Potentially destructive SQL operations detected (DROP/DELETE/TRUNCATE)" >&2
        echo "💡 Consider creating a backup before executing this migration" >&2
      fi

      # Check for common patterns
      if grep -i "CREATE TABLE\|ALTER TABLE\|CREATE INDEX" "$FILE_PATH" >/dev/null 2>&1; then
        echo "🏗️ Schema modification statements detected" >&2
      fi

      if grep -i "INSERT\|UPDATE" "$FILE_PATH" >/dev/null 2>&1; then
        echo "📝 Data modification statements detected" >&2
      fi
    fi
  fi

  # General migration best practices reminder
  echo "📋 Migration Best Practices:" >&2
  echo "   • Always backup database before running migrations" >&2
  echo "   • Test migrations on development/staging first" >&2
  echo "   • Ensure migrations are reversible when possible" >&2
  echo "   • Use transactions for atomic operations" >&2

else
  echo "File $FILE_PATH is not a migration file, skipping analysis" >&2
fi

exit 0

Examples

Database Migration Runner Hook Script

Complete hook script that detects migration files and checks migration status

#!/usr/bin/env bash
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
if [[ "$FILE_PATH" == *migration* ]] || [[ "$FILE_PATH" == *schema* ]] || [[ "$FILE_PATH" == *.sql ]]; then
  echo "Database migration file detected: $FILE_PATH" >&2
  if [ -f "package.json" ] && grep -q "knex" package.json; then
    if command -v npx &> /dev/null && npx knex --version &> /dev/null 2>&1; then
      echo "Running Knex migration status check..." >&2
      MIGRATION_STATUS=$(npx knex migrate:status 2>/dev/null || echo "No pending migrations")
      echo "Migration Status: $MIGRATION_STATUS" >&2
    fi
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable database migration detection on file write/edit

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-migration-runner.sh",
      "matchers": ["write", "edit"]
    }
  }
}

SQL Migration Analysis

Enhanced hook script that analyzes SQL migration files for destructive operations and schema changes

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *.sql ]]; then
  if [ -f "$FILE_PATH" ]; then
    LINE_COUNT=$(wc -l < "$FILE_PATH" 2>/dev/null || echo "0")
    echo "SQL file contains $LINE_COUNT lines" >&2
    if grep -i "DROP\|DELETE\|TRUNCATE" "$FILE_PATH" >/dev/null 2>&1; then
      echo "WARNING: Potentially destructive SQL operations detected (DROP/DELETE/TRUNCATE)" >&2
      echo "Consider creating a backup before executing this migration" >&2
    fi
    if grep -i "CREATE TABLE\|ALTER TABLE\|CREATE INDEX" "$FILE_PATH" >/dev/null 2>&1; then
      echo "Schema modification statements detected" >&2
    fi
  fi
fi
exit 0

Django Migration Detection

Enhanced hook script for Django migration detection and status checking

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *migration* ]] && [ -f "manage.py" ]; then
  echo "Django project detected" >&2
  if command -v python &> /dev/null; then
    echo "Checking Django migration status..." >&2
    python manage.py showmigrations --plan 2>/dev/null | tail -5 | head -3 || echo "Run 'python manage.py showmigrations' to check status" >&2
  fi
fi
exit 0

Troubleshooting

Hook detects migration file but Knex check fails

Verify package.json contains a knex dependency and run npm install. Check that npx knex --version succeeds. Ensure knexfile.js is present and points to the correct migrations directory.

Knex migration status shows no pending despite new files

Run npx knex migrate:list to verify migration discovery. Check that migration filenames follow the timestamp pattern Knex expects (e.g. 20240101_create_users.js). Confirm knexfile.js migrations path is correct.

PostToolUse hook triggers on non-migration SQL files

Tighten path matching by adding a directory check: [[ "$FILE_PATH" == *migrations/* ]]. Adjust or remove the *.sql pattern if raw SQL files in other directories are causing false positives.

Destructive operation warning for safe rollback scripts

The hook warns on DROP/DELETE/TRUNCATE in any SQL context. Split destructive down-migrations into separately reviewed files, or add a comment like # rollback-safe and update the grep pattern to skip flagged files.

Django migration detection fails in a virtual environment

Use the absolute Python path from which python or which python3 instead of relying on the shell PATH inside the hook. Ensure manage.py is present in the project root and the virtualenv is activated before Claude Code starts.

Source citations

Add this badge to your README

Show that Database Migration Runner - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/database-migration-runner.svg)](https://heyclau.de/entry/hooks/database-migration-runner)

How it compares

Database Migration Runner - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Next steps differ across entries — use the actions in the table below to copy install commands and source links per resource.

Field

PostToolUse hook that detects writes to migration, schema, and SQL files then runs framework-specific status checks — runs knex migrate:status for Node.js projects and python manage.py showmigrations for Django projects.

Open dossier

A PostToolUse hook that runs the matching test runner for a changed file's language — Jest or Vitest for JS/TS, pytest for Python, go test, or Maven/Gradle for Java — scoped to the edited file.

Open dossier

A Stop hook that terminates lingering database connections when a Claude Code session ends — via PostgreSQL pg_terminate_backend, MySQL KILL, Redis CLIENT KILL, and MongoDB connection cleanup.

Open dossier

A PostToolUse hook that reminds you to enable native query logging for PostgreSQL, Prisma, Sequelize, and TypeORM, and flags possible N+1 patterns when you edit SQL or data-access files.

Open dossier
Next stepsDiffers
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-162025-09-162025-09-192025-10-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically after write or edit activity on migration, schema, and SQL files. Invokes knex migrate:status for Knex projects and python manage.py showmigrations for Django projects when the respective framework CLI is available. Scans raw SQL for destructive statements and reports warnings but does not apply migrations itself.Runs your project's test command automatically after each edit; tests execute arbitrary project code, so enable this only in a trusted repo and expect it to run frequently. The script invokes whichever runner it detects (npm test, npx vitest, pytest, go test, mvn/gradle); make sure the right one is installed so it does not run an unexpected command.Runs at session end and forcibly terminates database backends/clients (pg_terminate_backend, KILL, CLIENT KILL); pointed at a shared or production database it can drop other users' connections — scope it to local/dev databases and confirm the target before enabling.Runs automatically after bash, write, or edit activity and inspects files that look like query, model, repository, DAO, or SQL files. Creates .claude/logs/query-performance.log and appends database command or file-analysis events. Uses grep-based heuristics for query warnings and should not be treated as proof of a performance defect.
Privacy notesReads migration, schema, SQL, package, and framework configuration files to infer migration state. Command output may reveal database names, migration names, table names, or schema details in the local hook output.Runs locally and prints test output to the hook; that output can include file paths, test names, and any data your tests log.Uses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.Reads query-related source files and may print file paths, query patterns, and database command strings to local hook output. Stores analyzed file paths and database command text in .claude/logs/query-performance.log. Database command text may include connection names, database names, or other operational details if typed directly into the command.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/database-migration-runner.sh && chmod +x .claude/hooks/database-migration-runner.sh
mkdir -p .claude/hooks && touch .claude/hooks/code-test-runner-hook.sh && chmod +x .claude/hooks/code-test-runner-hook.sh
mkdir -p .claude/hooks && touch .claude/hooks/database-connection-cleanup.sh && chmod +x .claude/hooks/database-connection-cleanup.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-migration-runner.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/code-test-runner-hook.sh",
      "matchers": [
        "write",
        "edit",
        "multiedit"
      ]
    }
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": [
        "bash",
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.