Database Management Skill
Bonded to: database-management-agent
Quick Start
# 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
- Analyze Requirements: Understand data patterns, volume, access needs
- Select Database: Choose SQL vs NoSQL based on requirements
- Design Schema: Create data models, relationships, constraints
- Optimize Queries: Implement indexes, analyze execution plans
- 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
-- 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
-- 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
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
-- 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
# 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
1---2name: databases3description: Master relational and NoSQL databases. Learn PostgreSQL, MySQL, MongoDB, Redis, and other technologies for data persistence, optimization, and scaling.4sasmp_version: "2.0.0"5bonded_agent: 02-database-management6bond_type: PRIMARY_BOND78# === PRODUCTION-GRADE SKILL CONFIG (SASMP v2.0.0) ===910atomic_operations:11 - DATABASE_SELECTION12 - SCHEMA_DESIGN13 - QUERY_OPTIMIZATION14 - BACKUP_CONFIGURATION1516parameter_validation:17 query:18 type: string19 required: true20 minLength: 521 maxLength: 200022 database_type:23 type: string24 enum: [postgresql, mysql, mongodb, redis, cassandra, elasticsearch]25 required: false26 operation:27 type: string28 enum: [design, optimize, backup, migrate]29 required: false3031retry_logic:32 max_attempts: 333 backoff: exponential34 initial_delay_ms: 20003536logging_hooks:37 on_invoke: "skill.databases.invoked"38 on_success: "skill.databases.completed"39 on_error: "skill.databases.failed"4041exit_codes:42 SUCCESS: 043 INVALID_INPUT: 144 CONNECTION_ERROR: 245 QUERY_ERROR: 346 OPTIMIZATION_FAILED: 447---4849# Database Management Skill5051**Bonded to:** `database-management-agent`5253---5455## Quick Start5657```bash58# Invoke databases skill59"Design a database schema for my e-commerce application"60"Optimize slow queries in PostgreSQL"61"Set up Redis caching for session storage"62```6364---6566## Instructions67681. **Analyze Requirements**: Understand data patterns, volume, access needs692. **Select Database**: Choose SQL vs NoSQL based on requirements703. **Design Schema**: Create data models, relationships, constraints714. **Optimize Queries**: Implement indexes, analyze execution plans725. **Set Up Operations**: Configure backup, replication, monitoring7374---7576## Database Selection Guide7778| Type | Best For | ACID | Scale | Examples |79|------|----------|------|-------|----------|80| Relational | Complex queries, transactions | Full | Vertical | PostgreSQL, MySQL |81| Document | Flexible schema, JSON | Partial | Horizontal | MongoDB |82| Key-Value | Caching, sessions | No | Horizontal | Redis |83| Wide-Column | Time series, analytics | Partial | Horizontal | Cassandra |84| Graph | Relationships | Varies | Varies | Neo4j |85| Search | Full-text search | No | Horizontal | Elasticsearch |8687---8889## Decision Tree9091```92Need ACID transactions?93 │94 ├─→ Yes → Complex queries?95 │ ├─→ Yes → PostgreSQL96 │ └─→ No → MySQL97 │98 └─→ No → Data type?99 ├─→ Documents/JSON → MongoDB100 ├─→ Key-Value pairs → Redis101 ├─→ Time series → Cassandra/TimescaleDB102 └─→ Full-text search → Elasticsearch103```104105---106107## Examples108109### Example 1: Schema Design110```sql111-- E-commerce schema112CREATE TABLE users (113 id UUID PRIMARY KEY DEFAULT gen_random_uuid(),114 email VARCHAR(255) UNIQUE NOT NULL,115 password_hash VARCHAR(255) NOT NULL,116 created_at TIMESTAMPTZ DEFAULT NOW()117);118119CREATE TABLE products (120 id UUID PRIMARY KEY DEFAULT gen_random_uuid(),121 name VARCHAR(255) NOT NULL,122 price DECIMAL(10,2) NOT NULL CHECK (price > 0),123 stock INTEGER NOT NULL DEFAULT 0124);125126CREATE TABLE orders (127 id UUID PRIMARY KEY DEFAULT gen_random_uuid(),128 user_id UUID REFERENCES users(id),129 total DECIMAL(10,2) NOT NULL,130 status VARCHAR(50) DEFAULT 'pending',131 created_at TIMESTAMPTZ DEFAULT NOW()132);133134-- Indexes for common queries135CREATE INDEX idx_orders_user_id ON orders(user_id);136CREATE INDEX idx_orders_created_at ON orders(created_at DESC);137```138139### Example 2: Query Optimization140```sql141-- Before: Full table scan142EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 'abc123';143144-- After: Add index145CREATE INDEX idx_orders_user_id ON orders(user_id);146147-- Optimized query with selected columns148SELECT id, total, status, created_at149FROM orders150WHERE user_id = 'abc123'151ORDER BY created_at DESC152LIMIT 10;153```154155### Example 3: Redis Caching156```python157import redis158import json159160r = redis.Redis(host='localhost', port=6379, decode_responses=True)161162def get_user(user_id: str) -> dict:163 # Try cache first164 cached = r.get(f"user:{user_id}")165 if cached:166 return json.loads(cached)167168 # Cache miss - fetch from DB169 user = db.query(User).get(user_id)170 if user:171 r.setex(f"user:{user_id}", 3600, json.dumps(user.dict()))172 return user.dict()173```174175---176177## Troubleshooting178179### Common Issues180181| Issue | Cause | Solution |182|-------|-------|----------|183| Query timeout | Missing index | Run EXPLAIN ANALYZE, add index |184| Connection refused | Wrong config | Check host, port, credentials |185| Deadlock | Concurrent updates | Use proper isolation, retry logic |186| OOM on query | Large result set | Add LIMIT, use cursors |187188### Debug Commands189190```sql191-- PostgreSQL: Check slow queries192SELECT query, calls, mean_time193FROM pg_stat_statements194ORDER BY mean_time DESC LIMIT 10;195196-- Check active connections197SELECT * FROM pg_stat_activity WHERE state = 'active';198199-- Check table sizes200SELECT relname, pg_size_pretty(pg_total_relation_size(relid))201FROM pg_stat_user_tables202ORDER BY pg_total_relation_size(relid) DESC;203```204205---206207## Test Template208209```python210# tests/test_database.py211import pytest212from sqlalchemy import create_engine213214class TestDatabaseSchema:215 @pytest.fixture216 def engine(self):217 return create_engine("postgresql://test:test@localhost/testdb")218219 def test_users_table_exists(self, engine):220 result = engine.execute("SELECT 1 FROM users LIMIT 1")221 assert result is not None222223 def test_foreign_key_constraint(self, engine):224 with pytest.raises(IntegrityError):225 engine.execute(226 "INSERT INTO orders (user_id, total) VALUES ('invalid-uuid', 100)"227 )228```229230---231232## References233234See `references/` directory for:235- `DATABASE_GUIDE.md` - Detailed database patterns236- Schema templates and examples237238---239240## Resources241242- [PostgreSQL Documentation](https://www.postgresql.org/docs/)243- [MongoDB Manual](https://docs.mongodb.com/manual/)244- [Redis Documentation](https://redis.io/documentation)245- [Use The Index, Luke](https://use-the-index-luke.com/)