db-connection
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).
What this skill does
# 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:[email protected]/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:[email protected]/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 create_sqlalchemy_engine() -> Engine:
"""Create SQLAlchemy engine with optimal settings for Neon/PostgreSQL."""
settings = get_settings()
db_url = get_db_url()
engine = create_engine(
db_url,
pool_size=settings.DB_POOL_SIZE,
max_overflow=settings.DB_MAX_OVERFLOW,
pool_timeout=settings.DB_POOL_TIMEOUT,
pool_recycle=settings.DB_POOL_RECYCLE,
echo=settings.DB_ECHO,
# PostgreSQL-specific settings
pool_pre_ping=True, # Verify connections before use
isolation_level="AUTOCOMMIT",
)
# Enable connection health checks
@event.listens_for(engine, "connect")
def set_session_vars(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
# Set session characteristics
cursor.execute("SET statement_timeout = '30s'")
cursor.execute("SET idle_in_transaction_session_timeout = '60000'")
cursor.close()
logger.info(f"Database engine created with pool_size={settings.DB_POOL_SIZE}")
return engine
def get_engine() -> Engine:
"""Get or create database engine (singleton pattern)."""
return create_sqlalchemy_engine()
```
### Session Management
```python
# backend/app/db/session.py
from sqlalchemy.orm import sessionmaker, Session
from typing import Generator
from app.db.connection import get_engine
# Create session factory
SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=get_engine(),
)
def get_db() -> Generator[Session, None, None]:
"""
Database session dependency for FastAPI.
Usage:
@router.get("/users/")
def get_users(db: Session = Depends(get_db)):
...
"""
db = SessionLocal()
try:
yield db
finally:
db.close()
async def get_async_db() -> Generator[Session, None, None]:
"""
Async database session dependency (for async routes).
Note: Use with SQLModel async sessions or asyncpg.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()
```
## Neon PostgreSQL Setup
### Neon Connection String Format
```
postgresql://[user]:[password]@[host]/[dbname]?sslmode=require
```
Components:
- **user**: Database username (from Neon)
- **password**: Database password (from Neon)
- **host**: Endpoint ID + region, e.g., `ep-xxx-12345.us-east-1.aws.neon.tech`
- **dbname**: Your database name
- **sslmode**: Must be `require` for Neon
### Getting Connection Details from Neon
1. Go to [Neon Dashboard](https://console.neon.tech)
2. Select your project
3. Go to **Connection Details**
4. Copy the connection string
5. Add to Vercel/Dashboard environment variables
### Connection Pooling for Neon
```python
# For serverless/edge functions, use lower pool sizes
# backend/app/db/connection.py
def create_serverless_engine() -> Engine:
"""Create engine optimized for serverless/Vercel functions."""
settings = get_settings()
# Smaller pool for serverless to avoid connection limits
return create_engine(
get_db_url(),
pool_size=2, # Keep small for serverless
max_overflow=0, # No overflow in serverless
pool_timeout=10, # Faster timeout
pool_recycle=300, # Recycle more frequently
pool_pre_ping=True,
echo=settings.DB_ECHO,
)
```
## FastAPI Integration
### Application Setup
```python
# backend/app/main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.db.connection import get_engine
from app.db.session import get_db
from app.config.settings import get_settings
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: Verify database connection
settings = get_settings()
engine = get_engine()
try:
with engine.connect() as conn:
conn.execute("SELECT 1")
logger.info("Database connection verified successfully")
except Exception as e:
logger.error(f"Database connection failed: {e}")
raise
yield
# Shutdown: Close all connections
engine.dispose()
logger.info("Database connections closed")
app = FastAPI(lifespan=lifespan)
# Dependency injection works with any route
@app.get("/users/")
def get_users(db=Depends(get_db)):
return db.query(User).all()
```
### Database Health Check
```python
# backend/app/api/health.py
from fastapi import APIRouter, Depends
from sqlalchemy import text
from sqlalchemy.orm import Session
from app.db.session import get_db
router = APIRouter()
@router.get("/health/db")
def database_health(db: Session = Depends(get_db)) -> dict:
"""
Check database connectivity.
Returns:
{
"status": "healthy",
"latency_ms": <response_time>,
"database": <db_name>
}
"""
import time
start = time.time()
result = db.execute(text("SELECT 1"))
latency_ms = (time.time() - start) * 1000
return {
"status": "healthy",
"latency_ms": round(latency_ms, 2),
"database": "postgresql",
}
```
## SSL Configuration
### Required SSL Settings
```python
# Neon requires SSL - this is the default behavior
# No additional configuration needed when using ?sslmode=require
# VerifRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.