Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Psycopg

БесплатноБез исполняемых скриптовНе проверен

PostgreSQL adapter for Python - customer support tech enablement for database operations, query optimization, and data management

manutejот manutej★ 64 звезды на GitHub

Об этом скилле

Psycopg Skill - Customer Support Tech Enablement

Overview

This skill provides comprehensive guidance on using psycopg3 (and psycopg2 where applicable) for PostgreSQL database operations in customer support contexts. It covers everything from basic connections to advanced features like connection pooling, async operations, bulk data transfers, and performance optimization.

Target Audience

  • Customer Support Engineers working with backend systems
  • Technical Support teams handling data migrations
  • Support teams analyzing customer data and usage patterns
  • Backend developers building support tools and dashboards
  • QA engineers writing integration tests for PostgreSQL-backed applications

Core Competencies

When using this skill, you will be able to:

  1. Establish robust database connections with proper error handling and retry logic
  2. Implement connection pooling for high-performance multi-threaded applications
  3. Execute async database operations for non-blocking I/O in modern Python applications
  4. Perform bulk data operations efficiently using COPY and batch insert techniques
  5. Write secure parameterized queries to prevent SQL injection
  6. Handle transactions with proper commit/rollback semantics
  7. Optimize query performance using prepared statements and binary protocols
  8. Work with JSON/JSONB data for flexible customer data storage
  9. Implement retry patterns for resilient database connections
  10. Test database code effectively using pytest and fixtures

Installation and Setup

Installing Psycopg3

For new projects, always use psycopg3:

# Basic installation (pure Python implementation)
pip install psycopg

# With binary package for better performance
pip install "psycopg[binary]"

# With connection pool support
pip install "psycopg[pool]"

# Complete installation with all extras
pip install "psycopg[binary,pool]"

# For C implementation (fastest, requires build tools)
pip install "psycopg[c]"

Installing Psycopg2 (Legacy Projects)

If you're maintaining legacy code:

# Binary package (recommended for most cases)
pip install psycopg2-binary

# Source package (requires PostgreSQL dev libraries)
pip install psycopg2

Environment Setup for Customer Support

Create a .env file for database credentials:

# Production support database (read-only)
SUPPORT_DB_HOST=support-db.company.com
SUPPORT_DB_PORT=5432
SUPPORT_DB_NAME=support_analytics
SUPPORT_DB_USER=support_readonly
SUPPORT_DB_PASSWORD=secure_password_here

# Development/testing database
DEV_DB_HOST=localhost
DEV_DB_PORT=5432
DEV_DB_NAME=support_dev
DEV_DB_USER=dev_user
DEV_DB_PASSWORD=dev_password

Load with python-dotenv:

from dotenv import load_dotenv
import os

load_dotenv()

DB_CONFIG = {
    'host': os.getenv('SUPPORT_DB_HOST'),
    'port': os.getenv('SUPPORT_DB_PORT'),
    'dbname': os.getenv('SUPPORT_DB_NAME'),
    'user': os.getenv('SUPPORT_DB_USER'),
    'password': os.getenv('SUPPORT_DB_PASSWORD'),
}

Connection Management

Basic Connection (Psycopg3)

import psycopg

# Using connection string
conn = psycopg.connect(
    "postgresql://user:password@localhost:5432/support_db"
)

# Using parameters (recommended for flexibility)
conn = psycopg.connect(
    host="localhost",
    port=5432,
    dbname="support_db",
    user="support_user",
    password="secure_password",
    autocommit=False,  # Explicit transaction management
    connect_timeout=10  # Timeout in seconds
)

# Always use context manager for automatic cleanup
with psycopg.connect(**DB_CONFIG) as conn:
    with conn.cursor() as cur:
        cur.execute("SELECT version()")
        print(cur.fetchone()[0])
# Connection automatically closed

Connection with Retry Logic

For resilient customer support applications:

import psycopg
import time
import logging
from typing import Optional

logger = logging.getLogger(__name__)

def connect_with_retry(
    max_attempts: int = 5,
    retry_delay: float = 2.0,
    backoff_factor: float = 2.0,
    **conn_params
) -> Optional[psycopg.Connection]:
    """
    Establish database connection with exponential backoff retry.

    Args:
        max_attempts: Maximum number of connection attempts
        retry_delay: Initial delay between retries (seconds)
        backoff_factor: Multiplier for exponential backoff
        **conn_params: Connection parameters for psycopg.connect()

    Returns:
        Connection object or None if all attempts fail
    """
    attempt = 0
    current_delay = retry_delay

    while attempt < max_attempts:
        try:
            conn = psycopg.connect(**conn_params)
            logger.info(f"Database connection established on attempt {attempt + 1}")
            return conn
        except psycopg.OperationalError as e:
            attempt += 1
            if attempt >= max_attempts:
                logger.error(f"Failed to connect after {max_attempts} attempts: {e
Полный SKILL.md на GitHub

Установить Psycopg в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.skill-summary.txtEXAMPLES.mdREADME.md

FAQ

Что делает скилл Psycopg?

PostgreSQL adapter for Python - customer support tech enablement for database operations, query optimization, and data management

Как установить скилл Psycopg?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Psycopg запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Psycopg с