databases
Master relational and NoSQL databases. Learn PostgreSQL, MySQL, MongoDB, Redis, and other technologies for data persistence, optimization, and scaling.
What this skill does
# Database Management Skill
**Bonded to:** `database-management-agent`
---
## Quick Start
```bash
# Invoke databases skill
"Design a database schema for my e-commerce application"
"Optimize slow queries in PostgreSQL"
"Set up Redis caching for session storage"
```
---
## Instructions
1. **Analyze Requirements**: Understand data patterns, volume, access needs
2. **Select Database**: Choose SQL vs NoSQL based on requirements
3. **Design Schema**: Create data models, relationships, constraints
4. **Optimize Queries**: Implement indexes, analyze execution plans
5. **Set Up Operations**: Configure backup, replication, monitoring
---
## Database Selection Guide
| Type | Best For | ACID | Scale | Examples |
|------|----------|------|-------|----------|
| Relational | Complex queries, transactions | Full | Vertical | PostgreSQL, MySQL |
| Document | Flexible schema, JSON | Partial | Horizontal | MongoDB |
| Key-Value | Caching, sessions | No | Horizontal | Redis |
| Wide-Column | Time series, analytics | Partial | Horizontal | Cassandra |
| Graph | Relationships | Varies | Varies | Neo4j |
| Search | Full-text search | No | Horizontal | Elasticsearch |
---
## Decision Tree
```
Need ACID transactions?
│
├─→ Yes → Complex queries?
│ ├─→ Yes → PostgreSQL
│ └─→ No → MySQL
│
└─→ No → Data type?
├─→ Documents/JSON → MongoDB
├─→ Key-Value pairs → Redis
├─→ Time series → Cassandra/TimescaleDB
└─→ Full-text search → Elasticsearch
```
---
## Examples
### Example 1: Schema Design
```sql
-- E-commerce schema
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE products (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
price DECIMAL(10,2) NOT NULL CHECK (price > 0),
stock INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id),
total DECIMAL(10,2) NOT NULL,
status VARCHAR(50) DEFAULT 'pending',
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indexes for common queries
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_orders_created_at ON orders(created_at DESC);
```
### Example 2: Query Optimization
```sql
-- Before: Full table scan
EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 'abc123';
-- After: Add index
CREATE INDEX idx_orders_user_id ON orders(user_id);
-- Optimized query with selected columns
SELECT id, total, status, created_at
FROM orders
WHERE user_id = 'abc123'
ORDER BY created_at DESC
LIMIT 10;
```
### Example 3: Redis Caching
```python
import redis
import json
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
def get_user(user_id: str) -> dict:
# Try cache first
cached = r.get(f"user:{user_id}")
if cached:
return json.loads(cached)
# Cache miss - fetch from DB
user = db.query(User).get(user_id)
if user:
r.setex(f"user:{user_id}", 3600, json.dumps(user.dict()))
return user.dict()
```
---
## Troubleshooting
### Common Issues
| Issue | Cause | Solution |
|-------|-------|----------|
| Query timeout | Missing index | Run EXPLAIN ANALYZE, add index |
| Connection refused | Wrong config | Check host, port, credentials |
| Deadlock | Concurrent updates | Use proper isolation, retry logic |
| OOM on query | Large result set | Add LIMIT, use cursors |
### Debug Commands
```sql
-- PostgreSQL: Check slow queries
SELECT query, calls, mean_time
FROM pg_stat_statements
ORDER BY mean_time DESC LIMIT 10;
-- Check active connections
SELECT * FROM pg_stat_activity WHERE state = 'active';
-- Check table sizes
SELECT relname, pg_size_pretty(pg_total_relation_size(relid))
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC;
```
---
## Test Template
```python
# tests/test_database.py
import pytest
from sqlalchemy import create_engine
class TestDatabaseSchema:
@pytest.fixture
def engine(self):
return create_engine("postgresql://test:test@localhost/testdb")
def test_users_table_exists(self, engine):
result = engine.execute("SELECT 1 FROM users LIMIT 1")
assert result is not None
def test_foreign_key_constraint(self, engine):
with pytest.raises(IntegrityError):
engine.execute(
"INSERT INTO orders (user_id, total) VALUES ('invalid-uuid', 100)"
)
```
---
## References
See `references/` directory for:
- `DATABASE_GUIDE.md` - Detailed database patterns
- Schema templates and examples
---
## Resources
- [PostgreSQL Documentation](https://www.postgresql.org/docs/)
- [MongoDB Manual](https://docs.mongodb.com/manual/)
- [Redis Documentation](https://redis.io/documentation)
- [Use The Index, Luke](https://use-the-index-luke.com/)
Related 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.