Install command
Not provided
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 the source and read safety notes before installing.
Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.
Decision playbook
Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.
0
78
—
No baseline selected
No major trust-signal divergence detected in the current selection.
Confirm ownership and provenance before trusting install instructions.
Source link availableRequired
Open the canonical repository and verify ownership.
Source provenance statusRequired
Marked as source-backed.
Metadata reviewed
Registry metadata indicates a reviewed listing.
Validate risk disclosures before installation or API wiring.
Safety notes presentRequired
Review the listed safety guidance before running commands.
Privacy notes presentRequired
Review data handling notes before connecting accounts or secrets.
Trust level risk gateRequired
Trust level does not block evaluation.
Check package metadata and artifact integrity signals.
Install payload available
Install or copy payload is available for review.
Package verification flag
No package verification flag provided.
Checksum metadata
No checksum provided for downloaded artifact.
Use compare context to validate trade-offs before adoption.
Compare tray has multiple entries
Add at least one more entry to compare trust differences.
Baseline comparison available
No baseline peer selected yet.
Diverging trust signals identified
No major trust-signal divergence found.
Setup at a glance
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
Current risk score 16/100. Use staged verification before broader rollout.
Validate source and review signals before any execution.
Confirm source provenanceRequired
Source URL/provenance metadata is present.
Confirm metadata review state
Listing has review metadata.
Verify install payload
Install/config payload exists and can be inspected.
Confirm safety, privacy, and package integrity signals.
Review safety notesRequired
Safety notes are present.
Review privacy notesRequired
Privacy notes are present.
Verify package integrity metadata
No package verification/checksum metadata.
Adopt in controlled steps based on the selected plan.
Run in isolated sandbox firstRequired
Use a constrained sandbox and observe behavior across multiple tasks.
Roll out graduallyRequired
Roll out to a small cohort before wider usage.
Set monitoring and fallback
Define rollback path and monitor errors after adoption.
Evidence readiness
Required evidence gates are covered (5/6 signals complete).
Source repository/provenance is listed.
Required in this preset
Review metadata is present.
Required in this preset
Safety notes are present.
Required in this preset
Privacy notes are present.
Optional in this preset
Package integrity metadata is missing.
Optional in this preset
Install payload is available.
Required in this preset
Required evidence gates are covered for this preset.
Decision timeline
5/6 steps complete with no blocking gaps for this preset.
triage
Source/provenance metadata is available.
triage
Review metadata is available.
verify
Safety notes are available.
verify
Privacy notes are available.
verify
Package integrity metadata is missing.
rollout
Install payload is available.
No required blockers for this timeline preset.
Safety & privacy surface
3 safety and 3 privacy notes across 3 risk areas.
#!/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{
"hooks": {
"postToolUse": {
"script": "./.claude/hooks/database-query-performance-logger.sh",
"matchers": [
"bash",
"write",
"edit"
]
}
}
}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:
.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 loadingSELECT *, flags SELECT without a LIMIT/TOP, and notes when WHERE clauses are present so you remember to index those columnspostgresql.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)psql/mysql/sqlite command it sees, to .claude/logs/query-performance.logSELECT *, missing LIMIT) as you write data-access code.claude/settings.local.json~/.claude/settings.json.claude/settings.jsonjq command-line JSON processor (the script parses the hook's JSON stdin with jq){
"hooks": {
"postToolUse": {
"script": "./.claude/hooks/database-query-performance-logger.sh",
"matchers": ["bash", "write", "edit"]
}
}
}
#!/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
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
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"]
}
}
}
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
[](https://heyclau.de/entry/hooks/database-query-performance-logger)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 status | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed |
| Package trust | Package not verified | Package not verified | Package not verified | Package not verified |
| Source provenance | Source-backed | Source-backed | Source-backed | Source-backed |
| Submitter | — | — | — | — |
| Install risk | Review first | Review first | Review first | Review first |
| Notes | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ |
| Brand | — | — | — | — |
| Category | hooks | hooks | hooks | hooks |
| Source | source-backed | source-backed | source-backed | source-backed |
| Author | JSONbored | JSONbored | JSONbored | JSONbored |
| Added | 2025-10-19 | 2025-09-19 | 2025-09-19 | 2025-09-19 |
| Platforms | Claude Code | Claude Code | Claude Code | Claude Code |
| Source repo | — | — | — | — |
| 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. | ✓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 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. | ✓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 | — | | | |
| Config | | | | |
| Citations | ||||
| Claim | Unclaimed | Unclaimed | Unclaimed | Unclaimed |
Source-backed guides for putting this to work.
Fix Claude Code high CPU/memory, hangs, and context bloat with documented commands.
Loading live community signals…
A short, calm digest of reviewed Claude resources. Unsubscribe any time.