Skip to main content
hooksSource-backedReview first Safety Privacy

Prisma Schema Sync - Hooks

Automatically generates Prisma client and creates migrations when schema.prisma is modified.

by JSONbored·added 2025-09-19·
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://www.prisma.io/docs, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/prisma-schema-sync.mdx
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

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

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
3 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://www.prisma.io/docshttps://www.prisma.io/docs/orm/prisma-migratehttps://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/bin/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 this is a Prisma schema file
if [[ "$FILE_PATH" == *schema.prisma ]]; then
    echo "🔄 Prisma Schema Sync - Processing schema changes..."
    echo "📄 Schema file: $FILE_PATH"
    
    # Check if Prisma is available
    if ! command -v npx >/dev/null 2>&1; then
        echo "⚠️ npx not found. Please install Node.js and npm"
        exit 1
    fi
    
    # Step 1: Validate schema
    echo "🔍 Validating Prisma schema..."
    if npx prisma validate; then
        echo "✅ Schema validation passed"
    else
        echo "❌ Schema validation failed - Please fix errors before proceeding"
        exit 1
    fi
    
    # Step 2: Format schema
    echo "📝 Formatting Prisma schema..."
    if npx prisma format; then
        echo "✅ Schema formatted successfully"
    else
        echo "⚠️ Schema formatting failed"
    fi
    
    # Step 3: Generate Prisma client
    echo "🏗️ Generating Prisma client..."
    if npx prisma generate; then
        echo "✅ Prisma client generated successfully"
    else
        echo "❌ Prisma client generation failed"
        exit 1
    fi
    
    # Step 4: Create migration (dev mode only)
    if [ "$NODE_ENV" != "production" ]; then
        echo "🗄️ Creating database migration..."
        MIGRATION_NAME="auto_migration_$(date +%Y%m%d_%H%M%S)"
        
        if npx prisma migrate dev --name "$MIGRATION_NAME" --create-only; then
            echo "✅ Migration created: $MIGRATION_NAME"
            echo "⚠️ Please review the migration before applying it to your database"
            echo "💡 Apply with: npx prisma migrate dev"
        else
            echo "⚠️ Migration creation skipped or failed"
        fi
    else
        echo "ℹ️ Production environment - skipping migration creation"
    fi
    
    echo ""
    echo "💡 Prisma Sync Tips:"
    echo "  • Review generated migrations before applying"
    echo "  • Use 'npx prisma studio' to explore your database"
    echo "  • Run 'npx prisma db push' for prototyping"
    echo "  • Use 'npx prisma migrate reset' to reset development database"
    
    echo ""
    echo "🎯 Prisma schema sync complete!"
    
else
    echo "ℹ️ File is not a Prisma schema file: $FILE_PATH"
fi

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/prisma-schema-sync.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

Features

  • Automatic Prisma client generation including Prisma client generation (npx prisma generate command execution with proper configuration, TypeScript type generation with type-safe database access and full type safety, client regeneration on schema changes with automatic detection, client caching and optimization with incremental generation), TypeScript type generation (database model types with full type safety and IntelliSense support, relation types with relationship mapping and foreign key types, enum types with enum value types and type-safe enums, scalar types with database column types and type mapping), client optimization (client code generation optimization with tree shaking, client bundle size optimization with code splitting, client performance optimization with query optimization), and client validation (client generation validation with error checking, client type checking with TypeScript validation, client compatibility verification with schema compatibility)
  • Database migration creation including migration generation (npx prisma migrate dev command execution with --create-only flag, migration file creation with timestamp-based naming and descriptive names, migration SQL generation with DDL statements for schema changes, migration naming with auto-generated names and custom naming), migration safety checks (migration validation before creation with schema validation, migration conflict detection with conflict identification, migration rollback support with rollback capability, migration status checking with migration history), migration management (migration file organization with directory structure, migration history tracking with migration logs, migration dependency management with dependency resolution), and migration deployment (migration application with npx prisma migrate deploy for production, migration rollback support with rollback commands, migration status verification with status checking)
  • Schema validation and formatting including schema validation (npx prisma validate command execution with comprehensive validation, schema syntax validation with Prisma schema language validation, schema relationship validation with foreign key validation, schema constraint validation with constraint checking), schema formatting (npx prisma format command execution with consistent formatting, schema file formatting with consistent style and indentation, schema indentation and spacing with proper formatting, schema comment preservation with comment retention), schema linting (schema best practices checking with Prisma best practices, schema optimization suggestions with performance recommendations, schema consistency validation with consistency checking), and schema error reporting (validation error reporting with detailed error messages, formatting error reporting with formatting issues, schema error suggestions with actionable recommendations)
  • TypeScript type generation including model type generation (database model types with full type safety and IntelliSense support, model field types with database column mapping and type inference, model relation types with relationship mapping and foreign key types), enum type generation (enum types with enum value types and type-safe enums, enum type safety with TypeScript enums and compile-time checking), scalar type generation (scalar types with database column types and type mapping, custom scalar types with type mapping and custom type definitions), and type safety features (type-safe database queries with compile-time type checking, type-safe relations with relationship type safety, type-safe migrations with migration type safety)
  • Database synchronization including schema synchronization (schema.prisma to database synchronization with bidirectional sync, database schema introspection with npx prisma db pull for existing databases, schema diff generation with npx prisma migrate diff for change detection, schema push with npx prisma db push for rapid prototyping), database connection management (database connection validation with connection testing, database connection testing with connectivity checks, database connection error handling with error recovery), database state management (database state checking with state verification, database migration status with migration tracking, database schema version tracking with version management), and database synchronization reporting (synchronization status reporting with status updates, schema diff reporting with change summaries, synchronization error reporting with error details)
  • Migration safety checks including migration validation (migration file validation with file integrity checking, migration SQL validation with SQL syntax validation, migration dependency validation with dependency checking), migration conflict detection (migration conflict identification with conflict detection, migration merge conflict detection with merge conflict handling, migration resolution suggestions with conflict resolution), migration rollback support (migration rollback capability with rollback commands, migration rollback safety with safety checks, migration rollback verification with verification steps), and migration status checking (migration status tracking with status monitoring, migration history with historical tracking, migration deployment status with deployment tracking)
  • Development workflow integration including continuous synchronization (real-time schema synchronization on file changes, immediate client regeneration on schema updates, automatic migration creation on schema changes), workflow automation (automated Prisma workflow without manual intervention, schema validation automation with automatic validation, client generation automation with automatic generation), and workflow optimization (schema change detection with change tracking, incremental client generation with optimization, migration creation optimization with smart migration naming)
  • Production safety and environment detection including environment detection (NODE_ENV detection with environment variable checking, production environment detection with safety checks, development environment detection with development features), production safety (migration creation skipping in production with safety checks, production deployment safety with deployment validation, production database protection with database safety), and environment-specific behavior (development mode features with full automation, production mode safety with restricted operations, environment-specific configuration with environment-based settings)

Use Cases

  • Keep Prisma client in sync with schema changes automatically regenerating Prisma client when schema changes, ensuring TypeScript types are always up-to-date, and maintaining type safety across the application
  • Automatically create database migrations automatically generating migration files when schema changes, providing migration SQL for database updates, and enabling version-controlled database schema management
  • Validate Prisma schema syntax on changes automatically validating schema syntax and relationships, catching schema errors early in development, and preventing invalid schema deployments
  • Generate TypeScript types for database models automatically generating TypeScript types from Prisma schema, providing type-safe database access, and enabling IntelliSense support for database queries
  • Format Prisma schema files consistently automatically formatting schema files for consistency, maintaining code style standards, and improving schema readability
  • Development workflow integration seamlessly integrating Prisma schema synchronization into development workflows without manual client generation or migration creation

Prisma Schema Commands Compared

This hook runs on schema.prisma changes. Which Prisma command it should trigger depends on your stage — here's how the core commands differ:

Command What it does Creates migration history? Typical stage
prisma generate Regenerates the Prisma Client and TypeScript types from the schema No After any schema change
prisma migrate dev Creates and applies a new migration from schema changes Yes (versioned SQL files) Development
prisma migrate deploy Applies pending committed migrations without generating new ones Applies existing CI/CD and production
prisma db push Pushes the schema straight to the database, no migration files No Early prototyping only

Rule of thumb: always generate so types stay correct; use migrate dev while iterating, migrate deploy in pipelines, and reserve db push for throwaway prototypes where migration history doesn't matter.

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/prisma-schema-sync.sh
  3. Make executable: chmod +x .claude/hooks/prisma-schema-sync.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
  • Prisma installed (@prisma/client, prisma packages)
  • Node.js and npm installed
  • jq (optional, for JSON parsing)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/prisma-schema-sync.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Hook Script

#!/bin/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 this is a Prisma schema file
if [[ "$FILE_PATH" == *schema.prisma ]]; then
    echo "🔄 Prisma Schema Sync - Processing schema changes..."
    echo "📄 Schema file: $FILE_PATH"

    # Check if Prisma is available
    if ! command -v npx >/dev/null 2>&1; then
        echo "⚠️ npx not found. Please install Node.js and npm"
        exit 1
    fi

    # Step 1: Validate schema
    echo "🔍 Validating Prisma schema..."
    if npx prisma validate; then
        echo "✅ Schema validation passed"
    else
        echo "❌ Schema validation failed - Please fix errors before proceeding"
        exit 1
    fi

    # Step 2: Format schema
    echo "📝 Formatting Prisma schema..."
    if npx prisma format; then
        echo "✅ Schema formatted successfully"
    else
        echo "⚠️ Schema formatting failed"
    fi

    # Step 3: Generate Prisma client
    echo "🏗️ Generating Prisma client..."
    if npx prisma generate; then
        echo "✅ Prisma client generated successfully"
    else
        echo "❌ Prisma client generation failed"
        exit 1
    fi

    # Step 4: Create migration (dev mode only)
    if [ "$NODE_ENV" != "production" ]; then
        echo "🗄️ Creating database migration..."
        MIGRATION_NAME="auto_migration_$(date +%Y%m%d_%H%M%S)"

        if npx prisma migrate dev --name "$MIGRATION_NAME" --create-only; then
            echo "✅ Migration created: $MIGRATION_NAME"
            echo "⚠️ Please review the migration before applying it to your database"
            echo "💡 Apply with: npx prisma migrate dev"
        else
            echo "⚠️ Migration creation skipped or failed"
        fi
    else
        echo "ℹ️ Production environment - skipping migration creation"
    fi

    echo ""
    echo "💡 Prisma Sync Tips:"
    echo "  • Review generated migrations before applying"
    echo "  • Use 'npx prisma studio' to explore your database"
    echo "  • Run 'npx prisma db push' for prototyping"
    echo "  • Use 'npx prisma migrate reset' to reset development database"

    echo ""
    echo "🎯 Prisma schema sync complete!"

else
    echo "ℹ️ File is not a Prisma schema file: $FILE_PATH"
fi

exit 0

Examples

Prisma Schema Sync Hook Script

Complete hook script that performs Prisma schema synchronization

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
if [[ "$FILE_PATH" == *schema.prisma ]]; then
  echo "🔄 Prisma Schema Sync - Processing schema changes..."
  if command -v npx >/dev/null 2>&1; then
    echo "🔍 Validating Prisma schema..."
    if npx prisma validate; then
      echo "✅ Schema validation passed"
      echo "🏗️ Generating Prisma client..."
      npx prisma generate
    else
      echo "❌ Schema validation failed"
      exit 1
    fi
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable Prisma schema synchronization

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/prisma-schema-sync.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Schema Validation and Formatting

Enhanced hook script with schema validation, formatting, and client generation

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *schema.prisma ]]; then
  if command -v npx >/dev/null 2>&1; then
    echo "🔍 Validating Prisma schema..."
    if npx prisma validate; then
      echo "📝 Formatting Prisma schema..."
      npx prisma format
      echo "🏗️ Generating Prisma client..."
      if npx prisma generate; then
        echo "✅ Prisma client generated successfully"
      else
        echo "❌ Prisma client generation failed"
        exit 1
      fi
    else
      echo "❌ Schema validation failed"
      exit 1
    fi
  fi
fi
exit 0

Migration Creation with Environment Detection

Enhanced hook script with environment detection and migration creation

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *schema.prisma ]]; then
  if [ "$NODE_ENV" != "production" ]; then
    if command -v npx >/dev/null 2>&1; then
      echo "🔍 Validating Prisma schema..."
      if npx prisma validate; then
        echo "🏗️ Generating Prisma client..."
        npx prisma generate
        echo "🗄️ Creating database migration..."
        MIGRATION_NAME="auto_migration_$(date +%Y%m%d_%H%M%S)"
        if npx prisma migrate dev --name "$MIGRATION_NAME" --create-only; then
          echo "✅ Migration created: $MIGRATION_NAME"
          echo "⚠️ Please review the migration before applying it"
        fi
      fi
    fi
  else
    echo "ℹ️ Production environment - skipping migration creation"
  fi
fi
exit 0

Database Connection Validation

Enhanced hook script with database connection validation before operations

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *schema.prisma ]]; then
  if command -v npx >/dev/null 2>&1; then
    if [ -f ".env" ] && grep -q 'DATABASE_URL' .env; then
      echo "🔍 Testing database connection..."
      if npx prisma db pull --schema=prisma/schema.prisma >/dev/null 2>&1; then
        echo "✅ Database connection successful"
        echo "🔍 Validating Prisma schema..."
        if npx prisma validate; then
          echo "🏗️ Generating Prisma client..."
          npx prisma generate
        fi
      else
        echo "⚠️ Database connection failed - skipping migration creation"
        echo "💡 Verify DATABASE_URL in .env file"
      fi
    else
      echo "⚠️ DATABASE_URL not found in .env - skipping database operations"
    fi
  fi
fi
exit 0

Troubleshooting

npx prisma generate fails with 'generator not found' error

Prisma client not installed or wrong version. Run: 'npm install @prisma/client' matching schema generator. Verify: 'npx prisma version' showing versions. Re-generate with full schema path. Verify Prisma installation. Test with various Prisma versions.

Migration creation hangs waiting for database connection that fails

DATABASE_URL missing or incorrect in .env. Verify: 'echo $DATABASE_URL' showing connection. Test: 'npx prisma db pull' for connectivity. Or use '--skip-generate' flag bypassing DB. Verify database connection. Test with various database configurations.

Auto-migration creates duplicate migrations for identical schema changes

Timestamp-based naming always creates new migration. Add check: 'git diff prisma/schema.prisma | grep "^+model"' detecting real changes. Or use 'npx prisma migrate diff' to compare first. Verify schema changes. Test with various migration scenarios.

prisma format changes schema but hook shows no modifications

Formatting occurs after file write completing hook execution. Move format before validation: reorder script or use: 'npx prisma format && npx prisma validate' ensuring formatted state checked. Verify script order. Test with various schema formats.

Hook runs in production despite NODE_ENV check skipping migrations

NODE_ENV not set in deployment defaulting to undefined. Export: 'export NODE_ENV=production' in shell profile. Or check: 'if [ "$NODE_ENV" = "production" ] || [ -z "$NODE_ENV" ]'. Verify environment variables. Test with various environment configurations.

Prisma client generation fails with type errors

Schema syntax errors or missing dependencies. Run 'npx prisma validate' to identify issues. Check @prisma/client version matches prisma version. Verify TypeScript configuration. Test with various schema configurations.

Migration files created but not applied to database

Migration created with --create-only flag requires manual application. Apply with 'npx prisma migrate dev' or 'npx prisma migrate deploy' for production. Verify migration status. Test with various migration scenarios.

Schema validation passes but client generation fails

Generator configuration issues or missing dependencies. Check generator block in schema.prisma. Verify @prisma/client installation. Check node_modules/.prisma directory. Verify generator configuration. Test with various generator settings.

Source citations

Add this badge to your README

Show that Prisma Schema Sync - 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/prisma-schema-sync.svg)](https://heyclau.de/entry/hooks/prisma-schema-sync)

How it compares

Prisma Schema Sync - 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

Automatically generates Prisma client and creates migrations when schema.prisma is modified.

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

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

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
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-192025-10-192025-09-192025-09-16
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths 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.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 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 notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.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.Uses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.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.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/prisma-schema-sync.sh && chmod +x .claude/hooks/prisma-schema-sync.sh
mkdir -p .claude/hooks && touch .claude/hooks/database-connection-cleanup.sh && chmod +x .claude/hooks/database-connection-cleanup.sh
mkdir -p .claude/hooks && touch .claude/hooks/database-migration-runner.sh && chmod +x .claude/hooks/database-migration-runner.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/prisma-schema-sync.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": [
        "bash",
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-migration-runner.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Signals

Loading live community signals…

More like this, weekly

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