Skip to main content
hooksSource-backedReview first Safety Privacy

Database Query Performance Logger - Hooks

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.

by JSONbored·added 2025-10-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://code.claude.com/docs/en/hooks, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/database-query-performance-logger.mdx
Safety notes
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 notes
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.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-10-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

Config edit

Copy-ready — paste the snippet to get started.

Install command

Not 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 3 privacy notes across 3 risk areas.

3 areas
  • SafetyLocal filesRuns automatically after bash, write, or edit activity and inspects files that look like query, model, repository, DAO, or SQL files.
  • SafetyLocal filesCreates .claude/logs/query-performance.log and appends database command or file-analysis events.
  • SafetyGeneralUses grep-based heuristics for query warnings and should not be treated as proof of a performance defect.
  • PrivacyLocal filesReads query-related source files and may print file paths, query patterns, and database command strings to local hook output.
  • PrivacyLocal filesStores analyzed file paths and database command text in .claude/logs/query-performance.log.
  • PrivacyExecution & processesDatabase command text may include connection names, database names, or other operational details if typed directly into the command.

Safety notes

  • 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 notes

  • 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.

Schema details

Install type
config
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://code.claude.com/docs/en/hookshttps://code.claude.com/docs/en/hooks-guidehttps://www.postgresql.org/docs/current/runtime-config-logging.htmlhttps://www.prisma.io/docs/orm/prisma-client/observability-and-logging/logginghttps://sequelize.org/docs/v6/getting-started/https://github.com/typeorm/typeorm/blob/master/docs/docs/logging.mdhttps://github.com/flyerhzm/bullet
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 // ""')
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""')

# Configuration
SLOW_QUERY_THRESHOLD_MS=${SLOW_QUERY_THRESHOLD_MS:-1000}
LOG_FILE=".claude/logs/query-performance.log"

# Create log directory if it doesn't exist
mkdir -p "$(dirname "$LOG_FILE")"

# Function to check for query files
check_query_file() {
  local file=$1
  
  if [ -z "$file" ]; then
    return 1
  fi
  
  # Check if file contains SQL or database queries
  if [[ "$file" == *.sql ]] || \
     [[ "$file" == *query* ]] || \
     [[ "$file" == *model* ]] || \
     [[ "$file" == *repository* ]] || \
     [[ "$file" == *dao* ]]; then
    return 0
  fi
  
  return 1
}

# Function to analyze query patterns
analyze_query_patterns() {
  local file=$1
  
  echo "🔍 Analyzing query patterns in: $file" >&2
  
  if [ ! -f "$file" ]; then
    return
  fi
  
  # Check for N+1 query patterns (loops with queries)
  if grep -n "for\|while\|forEach" "$file" | head -5 | grep -q .; then
    if grep -i "SELECT\|query\|find" "$file" >/dev/null 2>&1; then
      echo "⚠️ Potential N+1 query pattern detected" >&2
      echo "💡 Consider using JOIN or eager loading instead of queries in loops" >&2
    fi
  fi
  
  # Check for SELECT * patterns
  if grep -i "SELECT \*" "$file" >/dev/null 2>&1; then
    echo "⚠️ SELECT * detected - consider specifying columns explicitly" >&2
    echo "💡 Reduces data transfer and improves performance" >&2
  fi
  
  # Check for missing LIMIT clauses
  if grep -i "SELECT" "$file" | grep -iv "LIMIT\|TOP" >/dev/null 2>&1; then
    echo "💡 Consider adding LIMIT clauses to prevent unbounded result sets" >&2
  fi
  
  # Check for unindexed WHERE clauses
  if grep -i "WHERE" "$file" >/dev/null 2>&1; then
    echo "📊 WHERE clauses detected - ensure columns are indexed" >&2
  fi
  
  # Log analysis timestamp
  echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] Analyzed: $file" >> "$LOG_FILE"
}

# Function to check for slow query logs
check_slow_query_logs() {
  echo "📈 Checking for slow query logs..." >&2
  
  # PostgreSQL slow query log
  if [ -f "postgresql.conf" ] || [ -f "pg_log/postgresql.log" ]; then
    echo "🐘 PostgreSQL detected" >&2
    echo "💡 Enable slow query logging: log_min_duration_statement = $SLOW_QUERY_THRESHOLD_MS" >&2
  fi
  
  # MySQL slow query log
  if [ -f "my.cnf" ] || [ -f "/etc/mysql/my.cnf" ]; then
    echo "🐬 MySQL detected" >&2
    echo "💡 Enable slow query log: slow_query_log = 1" >&2
  fi
  
  # Check for ORM query logging
  if [ -f "package.json" ]; then
    if grep -q "sequelize\|typeorm\|prisma" package.json 2>/dev/null; then
      echo "📦 ORM detected - query logging available" >&2
      echo "💡 Enable logging in ORM configuration for query performance insights" >&2
    fi
  fi
}

# Main execution
if check_query_file "$FILE_PATH"; then
  echo "🗃️ Database query file detected: $FILE_PATH" >&2
  analyze_query_patterns "$FILE_PATH"
  check_slow_query_logs
  
  # Performance tips
  echo "" >&2
  echo "🎯 Query Performance Best Practices:" >&2
  echo "   • Use indexes on frequently queried columns" >&2
  echo "   • Avoid N+1 queries with eager loading" >&2
  echo "   • Use EXPLAIN/ANALYZE to understand query plans" >&2
  echo "   • Monitor slow queries > ${SLOW_QUERY_THRESHOLD_MS}ms" >&2
  echo "   • Use connection pooling for better resource management" >&2
  
elif [[ "$COMMAND" == *"psql"* ]] || [[ "$COMMAND" == *"mysql"* ]] || [[ "$COMMAND" == *"sqlite"* ]]; then
  echo "🗃️ Database command detected" >&2
  echo "⏱️ Query execution started at: $(date)" >&2
  echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] Database command: $COMMAND" >> "$LOG_FILE"
fi

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

About this resource

What it does

This is a PostToolUse hook (a bash script) that runs after bash, write, or edit. It does not connect to a database, time queries, or run EXPLAIN — it inspects the file you just touched with grep and prints text reminders. Specifically:

  • N+1 heuristic: for files that look like queries, models, repositories, DAOs, or .sql, it greps for loops (for/while/forEach) combined with SELECT/query/find and prints a "possible N+1" reminder to use a JOIN or eager loading
  • SQL anti-pattern hints (grep-based): flags SELECT *, flags SELECT without a LIMIT/TOP, and notes when WHERE clauses are present so you remember to index those columns
  • Enable-logging reminders: if it finds postgresql.conf, my.cnf, or a package.json referencing Prisma/Sequelize/TypeORM, it prints how to turn on that stack's native query logging (PostgreSQL log_min_duration_statement, MySQL slow_query_log, or the ORM's logging option)
  • Best-practices checklist: prints a short static list (indexing, eager loading, EXPLAIN/ANALYZE, connection pooling) as guidance — these are reminders, not measurements
  • Local log: appends the analyzed file path, and any psql/mysql/sqlite command it sees, to .claude/logs/query-performance.log

Use Cases

  • Catching easy-to-miss query anti-patterns (N+1 loops, SELECT *, missing LIMIT) as you write data-access code
  • Reminding you to enable native query logging for your database or ORM during development
  • Keeping a local record of which query files you edited and which database commands you ran

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/database-query-performance-logger.sh
  3. Make executable: chmod +x .claude/hooks/database-query-performance-logger.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
  • Bash shell available
  • jq command-line JSON processor (the script parses the hook's JSON stdin with jq)
  • A project using PostgreSQL, MySQL, SQLite, Prisma, Sequelize, or TypeORM (the script detects these by file presence — no specific version, extension, or database connection is required, since it never queries the database itself)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": ["bash", "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 // ""')
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""')

# Configuration
SLOW_QUERY_THRESHOLD_MS=${SLOW_QUERY_THRESHOLD_MS:-1000}
LOG_FILE=".claude/logs/query-performance.log"

# Create log directory if it doesn't exist
mkdir -p "$(dirname "$LOG_FILE")"

# Function to check for query files
check_query_file() {
  local file=$1

  if [ -z "$file" ]; then
    return 1
  fi

  # Check if file contains SQL or database queries
  if [[ "$file" == *.sql ]] || \
     [[ "$file" == *query* ]] || \
     [[ "$file" == *model* ]] || \
     [[ "$file" == *repository* ]] || \
     [[ "$file" == *dao* ]]; then
    return 0
  fi

  return 1
}

# Function to analyze query patterns
analyze_query_patterns() {
  local file=$1

  echo "🔍 Analyzing query patterns in: $file" >&2

  if [ ! -f "$file" ]; then
    return
  fi

  # Check for N+1 query patterns (loops with queries)
  if grep -n "for\|while\|forEach" "$file" | head -5 | grep -q .; then
    if grep -i "SELECT\|query\|find" "$file" >/dev/null 2>&1; then
      echo "⚠️ Potential N+1 query pattern detected" >&2
      echo "💡 Consider using JOIN or eager loading instead of queries in loops" >&2
    fi
  fi

  # Check for SELECT * patterns
  if grep -i "SELECT \*" "$file" >/dev/null 2>&1; then
    echo "⚠️ SELECT * detected - consider specifying columns explicitly" >&2
    echo "💡 Reduces data transfer and improves performance" >&2
  fi

  # Check for missing LIMIT clauses
  if grep -i "SELECT" "$file" | grep -iv "LIMIT\|TOP" >/dev/null 2>&1; then
    echo "💡 Consider adding LIMIT clauses to prevent unbounded result sets" >&2
  fi

  # Check for unindexed WHERE clauses
  if grep -i "WHERE" "$file" >/dev/null 2>&1; then
    echo "📊 WHERE clauses detected - ensure columns are indexed" >&2
  fi

  # Log analysis timestamp
  echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] Analyzed: $file" >> "$LOG_FILE"
}

# Function to check for slow query logs
check_slow_query_logs() {
  echo "📈 Checking for slow query logs..." >&2

  # PostgreSQL slow query log
  if [ -f "postgresql.conf" ] || [ -f "pg_log/postgresql.log" ]; then
    echo "🐘 PostgreSQL detected" >&2
    echo "💡 Enable slow query logging: log_min_duration_statement = $SLOW_QUERY_THRESHOLD_MS" >&2
  fi

  # MySQL slow query log
  if [ -f "my.cnf" ] || [ -f "/etc/mysql/my.cnf" ]; then
    echo "🐬 MySQL detected" >&2
    echo "💡 Enable slow query log: slow_query_log = 1" >&2
  fi

  # Check for ORM query logging
  if [ -f "package.json" ]; then
    if grep -q "sequelize\|typeorm\|prisma" package.json 2>/dev/null; then
      echo "📦 ORM detected - query logging available" >&2
      echo "💡 Enable logging in ORM configuration for query performance insights" >&2
    fi
  fi
}

# Main execution
if check_query_file "$FILE_PATH"; then
  echo "🗃️ Database query file detected: $FILE_PATH" >&2
  analyze_query_patterns "$FILE_PATH"
  check_slow_query_logs

  # Performance tips
  echo "" >&2
  echo "🎯 Query Performance Best Practices:" >&2
  echo "   • Use indexes on frequently queried columns" >&2
  echo "   • Avoid N+1 queries with eager loading" >&2
  echo "   • Use EXPLAIN/ANALYZE to understand query plans" >&2
  echo "   • Monitor slow queries > ${SLOW_QUERY_THRESHOLD_MS}ms" >&2
  echo "   • Use connection pooling for better resource management" >&2

elif [[ "$COMMAND" == *"psql"* ]] || [[ "$COMMAND" == *"mysql"* ]] || [[ "$COMMAND" == *"sqlite"* ]]; then
  echo "🗃️ Database command detected" >&2
  echo "⏱️ Query execution started at: $(date)" >&2
  echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] Database command: $COMMAND" >> "$LOG_FILE"
fi

exit 0

Examples

Database Query Performance Logger Hook Script

Complete hook script that detects query files and analyzes performance patterns

#!/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 // ""')
SLOW_QUERY_THRESHOLD_MS=${SLOW_QUERY_THRESHOLD_MS:-1000}
LOG_FILE=".claude/logs/query-performance.log"
mkdir -p "$(dirname "$LOG_FILE")"
if [[ "$FILE_PATH" == *.sql ]] || [[ "$FILE_PATH" == *query* ]] || [[ "$FILE_PATH" == *model* ]]; then
  echo "Database query file detected: $FILE_PATH" >&2
  if grep -n "for\|while\|forEach" "$FILE_PATH" | head -5 | grep -q .; then
    if grep -i "SELECT\|query\|find" "$FILE_PATH" >/dev/null 2>&1; then
      echo "Potential N+1 query pattern detected" >&2
      echo "Consider using JOIN or eager loading instead of queries in loops" >&2
    fi
  fi
  if grep -i "SELECT \\*" "$FILE_PATH" >/dev/null 2>&1; then
    echo "SELECT * detected - consider specifying columns explicitly" >&2
  fi
  echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] Analyzed: $FILE_PATH" >> "$LOG_FILE"
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable query performance logging on file write/edit

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": ["bash", "write", "edit"]
    }
  }
}

SQL Query Analysis

Enhanced hook script that analyzes SQL queries for missing LIMIT clauses and unindexed WHERE clauses

#!/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 grep -i "SELECT" "$FILE_PATH" | grep -iv "LIMIT\|TOP" >/dev/null 2>&1; then
    echo "Consider adding LIMIT clauses to prevent unbounded result sets" >&2
  fi
  if grep -i "WHERE" "$FILE_PATH" >/dev/null 2>&1; then
    echo "WHERE clauses detected - ensure columns are indexed" >&2
  fi
fi
exit 0

ORM Query Logging Detection

Enhanced hook script that detects ORM frameworks and suggests query logging configuration

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -f "package.json" ]; then
  if grep -q "prisma" package.json 2>/dev/null; then
    echo "Prisma detected - enable query logging in PrismaClient configuration" >&2
    echo "log: [{ emit: 'stdout', level: 'query' }]" >&2
  elif grep -q "sequelize" package.json 2>/dev/null; then
    echo "Sequelize detected - enable query logging in Sequelize configuration" >&2
    echo "logging: console.log" >&2
  elif grep -q "typeorm" package.json 2>/dev/null; then
    echo "TypeORM detected - enable query logging in DataSource configuration" >&2
    echo "logging: ['query', 'error']" >&2
  fi
fi
exit 0

PostgreSQL Slow Query Configuration

Enhanced hook script that suggests PostgreSQL slow query logging and pg_stat_statements configuration

#!/usr/bin/env bash
SLOW_QUERY_THRESHOLD_MS=${SLOW_QUERY_THRESHOLD_MS:-1000}
if [ -f "postgresql.conf" ] || [ -f "pg_log/postgresql.log" ]; then
  echo "PostgreSQL detected" >&2
  echo "Enable slow query logging: log_min_duration_statement = $SLOW_QUERY_THRESHOLD_MS" >&2
  echo "Enable pg_stat_statements: shared_preload_libraries = 'pg_stat_statements'" >&2
fi
exit 0

Troubleshooting

Hook triggers on every file but query analysis shows nothing

Verify file path matching patterns in check_query_file. Add specific matchers for your ORM/query files. Check grep patterns match your SQL syntax (PostgreSQL vs MySQL syntax differences). Verify file extensions match your project structure.

N+1 detection gives false positives on batch operations

Hook flags loops with queries regardless of batching. Add @performance-safe comments to suppress warnings. Refine regex to detect batch/eager loading keywords like includes(), with(), or join(). Consider adding batch operation detection patterns.

Slow query threshold environment variable not respected

Export SLOW_QUERY_THRESHOLD_MS before hook runs. Check bash environment inheritance from shell config. Set in .clauderc: export SLOW_QUERY_THRESHOLD_MS=500 for global override. Verify environment variable is accessible in hook execution context.

Query log file grows too large in active development

Implement log rotation: mv query-performance.log query-performance.$(date +%Y%m%d).log periodically. Use logrotate or cleanup hook. Add log size check with truncation at 10MB threshold. Consider log retention policies.

ORM query logging suggestions appear but feature is enabled

Hook checks package.json presence, not active config. Suppress by adding ORM_LOGGING_ENABLED=true env var. Update hook to detect active logging from config files (ormconfig.json, database.yml). Verify ORM configuration files are accessible.

PostgreSQL pg_stat_statements not detected

Verify pg_stat_statements extension is installed: CREATE EXTENSION pg_stat_statements. Check postgresql.conf includes shared_preload_libraries = pg_stat_statements. Restart PostgreSQL after configuration changes. Verify PostgreSQL version 17+ compatibility.

Prisma query logging not working despite configuration

Verify Prisma 5.x compatibility. Check PrismaClient log configuration includes query level. Ensure log output is visible in development environment. Test with simple query to verify logging is active.

TypeORM query logging shows no output

Verify TypeORM 0.3.x compatibility. Check DataSource logging configuration includes query level. Ensure logging is enabled in development environment. Verify DataSource is properly initialized with logging options.

Source citations

Add this badge to your README

Show that Database Query Performance Logger - 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-query-performance-logger.svg)](https://heyclau.de/entry/hooks/database-query-performance-logger)

How it compares

Database Query Performance Logger - 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

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

Claude Code PostToolUse hook recipe that runs an installed Python linter after Write/Edit tool calls touch a .py 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

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

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-10-192025-09-192025-09-192025-09-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns 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.Hooks run local shell commands automatically after matching tool calls; review the script before enabling it in a shared repository. The hook executes whichever supported linter is first available on PATH and can fail the hook if that linter exits non-zero. Project-level hooks in .claude/settings.json are shared through git, so treat hook configuration as executable project policy.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 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 notesReads 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.The hook reads the edited Python file path from Claude Code's hook JSON input and passes that path to local lint tools. Lint output may include source lines, file paths, comments, TODOs, and other local code details in the Claude Code session.Uses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.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.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/python-linter-integration.sh && chmod +x .claude/hooks/python-linter-integration.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/prisma-schema-sync.sh && chmod +x .claude/hooks/prisma-schema-sync.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": [
        "bash",
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/python-linter-integration.sh"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/prisma-schema-sync.sh",
      "matchers": [
        "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.