← 返回 Skills 市场
urbantech

Database Query Best Practices

作者 Toby Morning · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
158
总下载
0
收藏
1
当前安装
1
版本数
在 OpenClaw 中安装
/install database-query-best-practices
功能描述
Prevent connection pool exhaustion when querying Railway PostgreSQL database. Use when (1) Running database queries from local environment, (2) Diagnosing "t...
使用说明 (SKILL.md)

Database Query Best Practices - Prevent Connection Pool Exhaustion

CRITICAL SKILL - READ THIS BEFORE QUERYING RAILWAY DATABASE

The Problem

When querying Railway production database from local development environment, you may encounter:

psycopg2.OperationalError: sorry, too many clients already

This happens when:

  • Multiple local dev servers are running (npm run dev, npm run develop)
  • Each dev server holds database connections open
  • Connection pool limit is reached (300 total connections)
  • No new connections can be established

ALWAYS Use This Approach

1. Check Connection Pool Status FIRST

Before ANY database query, check active connections:

python3 \x3C\x3C 'EOF'
import psycopg2

DATABASE_URL = "postgresql://postgres:password@host:port/railway"

try:
    conn = psycopg2.connect(DATABASE_URL, connect_timeout=10)
    cur = conn.cursor()

    # Check active connections
    cur.execute("""
        SELECT count(*)
        FROM pg_stat_activity
        WHERE datname = 'railway'
    """)
    active = cur.fetchone()[0]

    # Check pool limit
    cur.execute("SHOW max_connections")
    max_conn = cur.fetchone()[0]

    print(f"Active connections: {active}/{max_conn}")

    if active > int(max_conn) * 0.9:
        print(f"WARNING: Connection pool at {(active/int(max_conn))*100:.1f}% capacity")
        print("Consider closing dev servers before querying")
    else:
        print("Connection pool healthy - safe to query")

    cur.close()
    conn.close()

except Exception as e:
    print(f"Cannot connect: {e}")
    print("\
SOLUTION:")
    print("1. Kill local dev servers: pkill -9 -f 'npm run dev'")
    print("2. Wait 30 seconds for connections to close")
    print("3. Try again")
EOF

2. Always Use Context Managers

NEVER do this:

conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute("SELECT * FROM users")
# Forgot to close! Connection leak!

ALWAYS do this:

import psycopg2

DATABASE_URL = "postgresql://..."

try:
    conn = psycopg2.connect(DATABASE_URL, connect_timeout=30)
    cur = conn.cursor()

    # Do your queries
    cur.execute("SELECT * FROM users")
    results = cur.fetchall()

    # Process results...

finally:
    # ALWAYS close in finally block
    if cur:
        cur.close()
    if conn:
        conn.close()

3. Use Short-Lived Connections

For one-off queries, open connection, query, close immediately:

def get_user_count():
    """Get user count - connection opened and closed in function"""
    conn = None
    try:
        conn = psycopg2.connect(DATABASE_URL, connect_timeout=30)
        cur = conn.cursor()

        cur.execute("SELECT COUNT(*) FROM users")
        count = cur.fetchone()[0]

        cur.close()
        return count

    finally:
        if conn:
            conn.close()  # Connection immediately released

# Good: Connection closed after function returns
user_count = get_user_count()

4. Kill Dev Servers Before Queries

If you need to run database queries, stop dev servers first:

# Stop all dev servers
pkill -9 -f "npm run dev"
pkill -9 -f "npm run develop"

# Wait for connections to close
sleep 10

# Now safe to query
python3 scripts/your_query_script.py

# Restart dev servers after
cd src/backend && npm run dev &
cd AINative-website && npm run dev &

5. Use Railway CLI for Quick Queries (RECOMMENDED)

Instead of Python scripts, use Railway CLI when possible:

# Login to Railway
railway login

# Link to project
railway link

# Run SQL query directly
railway run psql -c "SELECT COUNT(*) FROM users WHERE created_at >= NOW() - INTERVAL '30 days'"

This uses Railway's managed connections and doesn't consume local pool.

Emergency: Connection Pool Full

If you encounter "too many clients already":

Option 1: Kill Local Dev Servers

pkill -9 -f "npm run dev"
pkill -9 -f "npm run develop"
pkill -9 node
sleep 30  # Wait for DB connections to close

Option 2: Check Active Connections on Railway

railway run psql -c "
SELECT
    pid,
    usename,
    application_name,
    client_addr,
    state,
    query_start
FROM pg_stat_activity
WHERE datname = 'railway'
ORDER BY query_start DESC
LIMIT 20"

Option 3: Terminate Idle Connections (LAST RESORT)

railway run psql -c "
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'railway'
  AND state = 'idle'
  AND query_start \x3C NOW() - INTERVAL '10 minutes'"

Pre-Query Checklist

Before running ANY database query, verify:

  • Are local dev servers running? → Stop them first
  • Is connection pool healthy? → Run connection check
  • Using try/finally to close connections? → Yes
  • Using short-lived connections? → Yes
  • Can I use Railway CLI instead? → Prefer this

Summary

The Golden Rule:

ALWAYS close database connections immediately after use. NEVER leave connections open in dev servers during queries.

Best Approach:

  1. Stop dev servers
  2. Query database
  3. Close connection
  4. Restart dev servers

Even Better: Use Railway CLI for ad-hoc queries instead of Python scripts.

安全使用建议
This skill appears to do what it says, but review and be careful before executing its commands: 1) Do NOT run pkill -9 or pkill -9 node unless you understand which processes will be killed — this can terminate unrelated work. 2) The pg_terminate_backend SQL will forcibly drop connections on the database and can impact production; only run it if you have proper authorization and have confirmed impact. 3) Avoid hard-coding DATABASE_URL or credentials in scripts; use environment variables or a secrets manager instead. 4) Prefer Railway CLI for ad-hoc queries as suggested, and test any termination commands on a staging copy first. 5) Ensure you have backups and required permissions before performing emergency operations. If you want, I can rewrite the examples to use environment variables, recommend safer process-stop commands, or add guardrails (confirmation prompts, dry-run checks) to reduce risk.
功能分析
Type: OpenClaw Skill Name: database-query-best-practices Version: 1.0.0 The skill bundle provides legitimate best practices and utility scripts for managing PostgreSQL connection pools, specifically targeting Railway environments. It includes Python and Shell snippets in SKILL.md for monitoring connections, using context managers, and clearing idle connections. While it includes commands to terminate processes (pkill) and database backends (pg_terminate_backend), these are explicitly presented as troubleshooting steps for 'too many clients' errors and are aligned with the stated purpose of the skill.
能力评估
Purpose & Capability
The name and description match the SKILL.md content: all instructions relate to detecting/avoiding connection-pool exhaustion for a Railway-hosted Postgres DB (checking pg_stat_activity, using short-lived connections, using Railway CLI, killing local dev servers). Nothing requested is unrelated to that purpose.
Instruction Scope
The runtime instructions stay within scope (checking active connections, closing connections, using Railway CLI). However, they include potentially destructive operational steps (pkill -9 to kill processes, pkill -9 node, and SQL to pg_terminate_backend) and refer to running queries against production; these are high-impact actions and should be used with caution and proper permissions. The SKILL.md also shows a hard-coded DATABASE_URL example with credentials placeholder which could encourage insecure handling of secrets.
Install Mechanism
Instruction-only skill with no install spec and no shipped code — lowest risk for code being written to disk or arbitrary downloads.
Credentials
The skill requests no environment variables or credentials, which matches the registry metadata. However, the examples show embedding a DATABASE_URL with credentials in scripts; the skill does not instruct secure secret handling (e.g., use env vars or secret managers). Connecting to the DB requires credentials in practice, but those are not requested or described in a secure manner.
Persistence & Privilege
always is false and the skill is user-invocable only. There is no indication it modifies other skills or system-wide settings; it does not request persistent presence or elevated platform privileges.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install database-query-best-practices
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /database-query-best-practices 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
- Initial release with comprehensive guidelines to prevent PostgreSQL connection pool exhaustion on Railway. - Includes critical best practices for checking pool status, closing connections, and using short-lived queries. - Step-by-step instructions for safely querying from local scripts and recommending the use of Railway CLI. - Troubleshooting steps provided for "too many clients" errors and emergency connection termination.
元数据
Slug database-query-best-practices
版本 1.0.0
许可证 MIT-0
累计安装 1
当前安装数 1
历史版本数 1
常见问题

Database Query Best Practices 是什么?

Prevent connection pool exhaustion when querying Railway PostgreSQL database. Use when (1) Running database queries from local environment, (2) Diagnosing "t... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 158 次。

如何安装 Database Query Best Practices?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install database-query-best-practices」即可一键安装,无需额外配置。

Database Query Best Practices 是免费的吗?

是的,Database Query Best Practices 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Database Query Best Practices 支持哪些平台?

Database Query Best Practices 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Database Query Best Practices?

由 Toby Morning(@urbantech)开发并维护,当前版本 v1.0.0。

💬 留言讨论