Psycopg
БесплатноБез исполняемых скриптовНе проверенPostgreSQL adapter for Python - customer support tech enablement for database operations, query optimization, and data management
от 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:
- Establish robust database connections with proper error handling and retry logic
- Implement connection pooling for high-performance multi-threaded applications
- Execute async database operations for non-blocking I/O in modern Python applications
- Perform bulk data operations efficiently using COPY and batch insert techniques
- Write secure parameterized queries to prevent SQL injection
- Handle transactions with proper commit/rollback semantics
- Optimize query performance using prepared statements and binary protocols
- Work with JSON/JSONB data for flexible customer data storage
- Implement retry patterns for resilient database connections
- 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
Установить Psycopg в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
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), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic