SKILL.md--- name: db-connection description: | Use when setting up database connections, especially for Neon PostgreSQL. Triggers for: Neon Postgres connection, connection pooling configuration, connection string management, SSL configuration, or SQLAlchemy engine setup. NOT for: CRUD operations (use @sqlmodel-crud) or migration scripts (use @db-migration). --- # Database Connection Skill Expert database connection management for Python/FastAPI with Neon PostgreSQL, connection pooling, and SSL configuration. ## Quick Reference | Task | File/Method | |------|-------------| | Get engine | `get_engine()` | | Get session | `get_session()` | | Connection string | `DB_URL` from settings | | Health check | `check_connection()` | ## Project Structure ``` backend/ ├── app/ │ ├── db/ │ │ ├── __init__.py │ │ ├── connection.py # Engine and session setup │ │ └── session.py # Dependency injection │ └── config/ │ └── settings.py # Environment config ├── alembic/ │ └── env.py # Uses connection from here └── .env.example ``` ## Connection Configuration ### Settings with DB URL ```python # backend/app/config/settings.py from functools import lru_cache from pydantic import Field, SecretStr from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", extra="ignore", ) # Database Configuration DB_URL: SecretStr = Field( ..., description="PostgreSQL connection URL", examples=["postgresql://user:pass@ep-xxx.us-east-1.aws.neon.tech/dbname?sslmode=require"], ) DB_POOL_SIZE: int = Field(default=5, ge=1, le=100) DB_MAX_OVERFLOW: int = Field(default=10, ge=0, le=100) DB_POOL_TIMEOUT: int = Field(default=30, ge=1, le=300) DB_POOL_RECYCLE: int = Field(default=1800, ge=300) DB_ECHO: bool = False @lru_cache def get_settings() -> Settings: return Settings() ``` ### Environment Variables ```bash # .env.example # Database (Neon PostgreSQL) # Get this from Neon Dashboard > Connection Details # Format: postgresql://user:pass@host/dbname?sslmode=require DB_URL="postgresql://username:password@ep-xxx.region.neon.tech/dbname?sslmode=require" # Connection Pool Settings DB_POOL_SIZE=5 DB_MAX_OVERFLOW=10 DB_POOL_TIMEOUT=30 DB_POOL_RECYCLE=1800 # Debug (set to true for development) DB_ECHO=false ``` ## SQLAlchemy Engine Setup ### Connection Module ```python # backend/app/db/connection.py from sqlalchemy import create_engine, event from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker, Session from typing import Generator import logging from app.config.settings import get_settings logger = logging.getLogger(__name__) def get_db_url() -> str: """Get database URL from settings.""" settings = get_settings() db_url = settings.DB_URL # SecretStr has get_secret_value() method if hasattr(db_url, 'get_secret_value'): return db_url.get_secret_value() return str(db_url) def creat