Install command
Provided
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 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
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
1 safety and 1 privacy notes across 1 risk area. Review closely: credentials & tokens.
#!/usr/bin/env bash
echo "🗄️ Starting database connection cleanup..." >&2
# PostgreSQL cleanup
if pgrep postgres >/dev/null 2>&1; then
echo "🐘 PostgreSQL: Checking connections..." >&2
# Check if psql is available and we can connect
if command -v psql &> /dev/null; then
# Count active connections
ACTIVE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
IDLE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
echo "📊 PostgreSQL: $ACTIVE_CONNECTIONS active, $IDLE_CONNECTIONS idle connections" >&2
# Terminate long-running idle connections (older than 5 minutes)
if [ "$IDLE_CONNECTIONS" -gt 0 ]; then
TERMINATED=$(psql -t -c "SELECT count(*) FROM (SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid()) t;" 2>/dev/null | xargs || echo "0")
if [ "$TERMINATED" -gt 0 ]; then
echo "✅ PostgreSQL: Terminated $TERMINATED idle connections" >&2
fi
fi
else
echo "⚠️ PostgreSQL running but psql not available" >&2
fi
fi
# MySQL cleanup
if pgrep mysql >/dev/null 2>&1 || pgrep mysqld >/dev/null 2>&1; then
echo "🐬 MySQL: Checking connections..." >&2
if command -v mysql &> /dev/null; then
PROCESSLIST=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | grep -c "Sleep" || echo "0")
TOTAL_CONNECTIONS=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | wc -l || echo "0")
echo "📊 MySQL: $TOTAL_CONNECTIONS total connections, $PROCESSLIST sleeping" >&2
# Kill long-running sleeping connections (optional, requires PROCESS privilege)
# mysql -e "KILL CONNECTION_ID;" 2>/dev/null || true
else
echo "⚠️ MySQL running but mysql client not available" >&2
fi
fi
# MongoDB cleanup
if pgrep mongod >/dev/null 2>&1; then
echo "🍃 MongoDB: Checking connections..." >&2
if command -v mongosh &> /dev/null; then
CONNECTIONS=$(mongosh --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
echo "📊 MongoDB: $CONNECTIONS active operations" >&2
elif command -v mongo &> /dev/null; then
CONNECTIONS=$(mongo --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
echo "📊 MongoDB: $CONNECTIONS active operations" >&2
else
echo "⚠️ MongoDB running but mongo client not available" >&2
fi
fi
# Redis cleanup
if pgrep redis-server >/dev/null 2>&1; then
echo "📮 Redis: Checking connections..." >&2
if command -v redis-cli &> /dev/null; then
CLIENT_COUNT=$(redis-cli CLIENT LIST 2>/dev/null | wc -l || echo "0")
echo "📊 Redis: $CLIENT_COUNT connected clients" >&2
# Optionally close idle clients
# redis-cli CLIENT KILL TYPE normal SKIPME yes 2>/dev/null || true
else
echo "⚠️ Redis running but redis-cli not available" >&2
fi
fi
# Check for database connection strings in environment
if [ -f ".env" ]; then
DB_VARS=$(grep -E "(DATABASE_URL|MONGODB_URI|REDIS_URL|POSTGRES|MYSQL)" .env 2>/dev/null | wc -l || echo "0")
if [ "$DB_VARS" -gt 0 ]; then
echo "📋 Found $DB_VARS database configuration variables in .env" >&2
fi
fi
echo "✅ Database connection cleanup completed" >&2
exit 0{
"hooks": {
"stop": {
"script": "./.claude/hooks/database-connection-cleanup.sh"
}
}
}.claude/settings.local.json~/.claude/settings.json.claude/settings.json{
"hooks": {
"stop": {
"script": "./.claude/hooks/database-connection-cleanup.sh"
}
}
}
#!/usr/bin/env bash
echo "🗄️ Starting database connection cleanup..." >&2
# PostgreSQL cleanup
if pgrep postgres >/dev/null 2>&1; then
echo "🐘 PostgreSQL: Checking connections..." >&2
# Check if psql is available and we can connect
if command -v psql &> /dev/null; then
# Count active connections
ACTIVE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
IDLE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
echo "📊 PostgreSQL: $ACTIVE_CONNECTIONS active, $IDLE_CONNECTIONS idle connections" >&2
# Terminate long-running idle connections (older than 5 minutes)
if [ "$IDLE_CONNECTIONS" -gt 0 ]; then
TERMINATED=$(psql -t -c "SELECT count(*) FROM (SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid()) t;" 2>/dev/null | xargs || echo "0")
if [ "$TERMINATED" -gt 0 ]; then
echo "✅ PostgreSQL: Terminated $TERMINATED idle connections" >&2
fi
fi
else
echo "⚠️ PostgreSQL running but psql not available" >&2
fi
fi
# MySQL cleanup
if pgrep mysql >/dev/null 2>&1 || pgrep mysqld >/dev/null 2>&1; then
echo "🐬 MySQL: Checking connections..." >&2
if command -v mysql &> /dev/null; then
PROCESSLIST=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | grep -c "Sleep" || echo "0")
TOTAL_CONNECTIONS=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | wc -l || echo "0")
echo "📊 MySQL: $TOTAL_CONNECTIONS total connections, $PROCESSLIST sleeping" >&2
# Kill long-running sleeping connections (optional, requires PROCESS privilege)
# mysql -e "KILL CONNECTION_ID;" 2>/dev/null || true
else
echo "⚠️ MySQL running but mysql client not available" >&2
fi
fi
# MongoDB cleanup
if pgrep mongod >/dev/null 2>&1; then
echo "🍃 MongoDB: Checking connections..." >&2
if command -v mongosh &> /dev/null; then
CONNECTIONS=$(mongosh --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
echo "📊 MongoDB: $CONNECTIONS active operations" >&2
elif command -v mongo &> /dev/null; then
CONNECTIONS=$(mongo --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
echo "📊 MongoDB: $CONNECTIONS active operations" >&2
else
echo "⚠️ MongoDB running but mongo client not available" >&2
fi
fi
# Redis cleanup
if pgrep redis-server >/dev/null 2>&1; then
echo "📮 Redis: Checking connections..." >&2
if command -v redis-cli &> /dev/null; then
CLIENT_COUNT=$(redis-cli CLIENT LIST 2>/dev/null | wc -l || echo "0")
echo "📊 Redis: $CLIENT_COUNT connected clients" >&2
# Optionally close idle clients
# redis-cli CLIENT KILL TYPE normal SKIPME yes 2>/dev/null || true
else
echo "⚠️ Redis running but redis-cli not available" >&2
fi
fi
# Check for database connection strings in environment
if [ -f ".env" ]; then
DB_VARS=$(grep -E "(DATABASE_URL|MONGODB_URI|REDIS_URL|POSTGRES|MYSQL)" .env 2>/dev/null | wc -l || echo "0")
if [ "$DB_VARS" -gt 0 ]; then
echo "📋 Found $DB_VARS database configuration variables in .env" >&2
fi
fi
echo "✅ Database connection cleanup completed" >&2
exit 0
Complete hook script that closes database connections when session ends
#!/usr/bin/env bash
echo "Starting database connection cleanup..." >&2
if pgrep postgres >/dev/null 2>&1; then
if command -v psql &> /dev/null; then
IDLE=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
if [ "$IDLE" -gt 0 ]; then
psql -t -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid();" 2>/dev/null || true
echo "Terminated idle PostgreSQL connections" >&2
fi
fi
fi
exit 0
Complete hook configuration for .claude/settings.json to enable database connection cleanup on session stop
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "./.claude/hooks/database-connection-cleanup.sh"
}
]
}
]
}
}
Enhanced hook script with connection count threshold before cleanup
#!/usr/bin/env bash
echo "Starting database cleanup..." >&2
if pgrep postgres >/dev/null 2>&1 && command -v psql &> /dev/null; then
ACTIVE=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
IDLE=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
echo "PostgreSQL: $ACTIVE active, $IDLE idle connections" >&2
if [ "$IDLE" -gt 10 ]; then
psql -t -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid();" 2>/dev/null || true
fi
fi
exit 0
Enhanced hook script for Redis connection cleanup with idle client detection
#!/usr/bin/env bash
echo "Starting database cleanup..." >&2
if pgrep redis-server >/dev/null 2>&1 && command -v redis-cli &> /dev/null; then
CLIENT_COUNT=$(redis-cli CLIENT LIST 2>/dev/null | wc -l || echo "0")
IDLE_CLIENTS=$(redis-cli CLIENT LIST 2>/dev/null | grep -c "idle=" || echo "0")
echo "Redis: $CLIENT_COUNT connected clients, $IDLE_CLIENTS idle" >&2
if [ "$IDLE_CLIENTS" -gt 5 ]; then
redis-cli CLIENT KILL TYPE normal SKIPME yes 2>/dev/null || true
echo "Cleaned up idle Redis connections" >&2
fi
fi
exit 0
Enhanced hook script that discovers databases from .env and performs cleanup
#!/usr/bin/env bash
echo "Starting database cleanup..." >&2
if [ -f ".env" ]; then
DB_VARS=$(grep -E "(DATABASE_URL|MONGODB_URI|REDIS_URL|POSTGRES|MYSQL)" .env 2>/dev/null | wc -l || echo "0")
if [ "$DB_VARS" -gt 0 ]; then
echo "Found $DB_VARS database configuration variables" >&2
fi
fi
if pgrep postgres >/dev/null 2>&1 && command -v psql &> /dev/null; then
psql -t -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid();" 2>/dev/null || true
fi
exit 0
Verify psql client is in PATH and can connect without password. Check pg_hba.conf allows local connections. Ensure user has permission to query pg_stat_activity and call pg_terminate_backend. Test manually: psql -c SELECT count(*) FROM pg_stat_activity. Check PostgreSQL version: upgrade to PostgreSQL 17+ for latest features.
Hook reports connections but does not stop database servers. Use pgrep to verify process detection works. Check connection cleanup SQL executes successfully. Monitor stderr for command errors. Verify hook script has executable permissions: chmod +x.
Check state filter in pg_stat_activity query matches your PostgreSQL version. Verify 5-minute threshold is appropriate for your workflow. Use psql directly to debug query results: psql -c SELECT state, count(*) FROM pg_stat_activity GROUP BY state. Check PostgreSQL version compatibility.
Grant PROCESS privilege to MySQL user: GRANT PROCESS ON . TO user@localhost. Verify mysql client connects with correct credentials from .env or environment variables. Check MySQL version: upgrade to MySQL 8.0+ for latest features. Test connection manually: mysql -e SHOW PROCESSLIST.
Use mongosh for MongoDB 7.0+ or mongo for older versions. Configure connection string with credentials. Check authentication database matches user creation. Verify network access if using remote MongoDB. Test manually: mongosh --eval db.currentOp().inprog.length. Check MongoDB version compatibility.
Verify Redis server is running: redis-cli ping. Check Redis connection configuration and authentication if required. Verify redis-cli is in PATH. Test connection manually: redis-cli CLIENT LIST. Check Redis version: upgrade to Redis 7.0+ for latest features.
Add state filter to only terminate idle connections: WHERE state = idle. Increase timeout threshold from 5 minutes to 15 minutes. Add application process exclusion: AND application_name != your_app. Use pg_terminate_backend only for idle connections, not active ones.
Check process detection: verify pgrep commands for each database type. Ensure database client tools are installed for all detected databases. Check hook script logic: verify all database cleanup sections execute. Test each database type individually to isolate issues.
Show that Database Connection Cleanup - 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-connection-cleanup)Database Connection Cleanup - 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 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 | A Stop hook that syncs your changed files to cloud storage when a Claude Code session ends, using rclone to push to S3, Google Cloud Storage, or any of its 70+ supported backends. Open dossier | Detects unused CSS selectors when stylesheets are modified to keep CSS lean using PurgeCSS, PostCSS, and content analysis. This hook runs on CSS/SCSS file write/edit operations and analyzes stylesheets to identify unused selectors, generate optimized output, and report before/after size metrics. 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-09-19 | 2025-10-19 | 2025-09-19 | 2025-09-19 |
| Platforms | Claude Code | Claude Code | Claude Code | Claude Code |
| Source repo | — | — | — | — |
| Safety notes | ✓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. | ✓Runs automatically at session end and can create compressed archives of modified git files. Uploads backups through AWS CLI, Google Cloud SDK, or rclone when those tools and bucket variables are configured. Writes a temporary archive under /tmp when using the rclone fallback and removes it after the copy attempt. | ✓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 | ✓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. | ✓Sends modified file contents to the configured cloud storage destination. Uses locally configured cloud credentials and bucket environment variables but does not define or manage them. Backup archives may include source code, docs, generated files, and any unignored local changes listed by git diff. | ✓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 |
Loading live community signals…
A short, calm digest of reviewed Claude resources. Unsubscribe any time.