database-schema-design
Use when designing database schemas, creating migrations, modeling data relationships, optimizing database queries, adding indexes, or selecting between SQL and NoSQL storage
What this skill does
# Database Schema Design
## Overview
Guide the design, implementation, and optimization of database schemas with sound data modeling, safe migrations, effective indexing, and appropriate query patterns. This skill covers the full lifecycle from conceptual modeling through physical optimization, ensuring schemas that are normalized, performant, and safely evolvable.
**Announce at start:** "I'm using the database-schema-design skill to design the database schema."
## Phase 1: Discovery and Conceptual Model
Ask these questions to understand the data requirements:
| # | Question | What It Determines |
|---|----------|-------------------|
| 1 | What entities does the system manage? | Table names |
| 2 | What are the relationships between entities? | Foreign keys, join tables |
| 3 | What are the key attributes of each entity? | Column definitions |
| 4 | What are the primary query patterns? | Index strategy |
| 5 | What is the expected data volume? (rows, growth rate) | Partitioning, scaling |
| 6 | What is the read/write ratio? | Normalization vs denormalization |
| 7 | SQL or NoSQL? (or both?) | Storage engine selection |
### Storage Engine Decision Table
| Factor | Choose SQL (PostgreSQL, MySQL) | Choose Document (MongoDB) | Choose Key-Value (Redis) |
|--------|-------------------------------|--------------------------|-------------------------|
| Data shape | Structured, relational | Semi-structured, nested | Simple lookups, caching |
| Query complexity | Complex joins, aggregations | Document-level queries | Key-based access only |
| Consistency needs | ACID required | Eventual consistency OK | Ephemeral or cached data |
| Schema evolution | Migrations manageable | Schema-free flexibility | No schema |
| Scale pattern | Vertical first, then read replicas | Horizontal sharding | In-memory, limited size |
STOP after discovery — present the conceptual model (entities, relationships, cardinality) for confirmation.
## Phase 2: Logical Model Design
Translate the conceptual model into tables, columns, types, and constraints.
### Column Design Rules
| Decision | Guidance |
|----------|----------|
| Primary keys | UUIDs for distributed systems, auto-increment for single-node |
| Column types | Use the most specific type (`timestamptz` not `varchar` for dates) |
| Nullability | Default NOT NULL; allow NULL only when absence is meaningful |
| Defaults | Set sensible defaults (`created_at DEFAULT now()`) |
| Constraints | Add CHECK, UNIQUE, and FK constraints at the schema level |
| Naming | `snake_case`, singular table names or plural — be consistent |
### Normalization Guide
| Normal Form | Rule | Violation Example | Fix |
|-------------|------|-------------------|-----|
| **1NF** | Atomic values, no repeating groups | `tags VARCHAR "urgent,priority,vip"` | Separate `order_tags` table |
| **2NF** | All non-key columns depend on entire PK | `product_name` in `order_items` (composite PK) | Move to `products` table |
| **3NF** | No transitive dependencies | `city` depends on `zip_code`, not `user_id` | Separate `zip_codes` table |
**Rule:** Always start normalized. Denormalize only with measured evidence.
### Denormalization Decision Table
| Scenario | Pattern | When to Apply |
|----------|---------|--------------|
| Read-heavy dashboards | Materialized views or summary tables | Measured slow query |
| Frequently joined data | Embed as JSONB column | Join is >80% of query time |
| Reporting / analytics | Separate denormalized reporting tables | OLAP workload |
| Caching layer | Computed columns refreshed on write | High-frequency reads |
### Relationship Patterns
| Relationship | Implementation | Index Needed |
|-------------|---------------|-------------|
| One-to-One | FK with UNIQUE constraint on child | On FK column |
| One-to-Many | FK on the "many" side | On FK column |
| Many-to-Many | Junction/join table with composite PK | On both FK columns |
| Polymorphic | Separate FK columns with CHECK constraint (preferred) or type+id pattern | On type+id or each FK |
| Self-referential (trees) | `parent_id` FK to same table; or `ltree`/materialized path | On parent_id or path |
STOP after logical model — present the table definitions for review.
## Phase 3: Physical Model and Indexing
### Index Type Decision Table
| Index Type | Best For | Example |
|-----------|---------|---------|
| **B-tree** (default) | Equality and range queries | `CREATE INDEX idx_users_email ON users(email)` |
| **GIN** | Full-text search, JSONB, arrays | `CREATE INDEX idx_posts_search ON posts USING GIN(to_tsvector('english', body))` |
| **Partial** | Subset of rows matching condition | `CREATE INDEX idx_active_users ON users(email) WHERE active = true` |
| **Covering (INCLUDE)** | Index-only scans avoiding table lookup | `CREATE INDEX idx_users_email ON users(email) INCLUDE (name)` |
| **Composite** | Multi-column queries | `CREATE INDEX idx_orders ON orders(tenant_id, status)` |
### Composite Index Column Order
| Position | Column Type | Reason |
|----------|------------|--------|
| First | High-cardinality equality columns | Most selective filter first |
| Middle | Additional equality columns | Further narrows results |
| Last | Range columns (dates, numbers) | Range scan on remaining rows |
**Rule:** A composite index on `(A, B, C)` supports queries on `A`, `A+B`, `A+B+C` — but NOT `B` alone or `C` alone.
### Query Optimization Checklist
| Signal in EXPLAIN ANALYZE | Problem | Fix |
|--------------------------|---------|-----|
| Seq Scan on large table | Missing index | Add appropriate index |
| Nested Loop with large outer table | Inefficient join | Add index or restructure query |
| High actual vs estimated rows | Stale statistics | Run `ANALYZE` on table |
| Hash Join high memory | `work_mem` too low | Tune `work_mem` or restructure |
### N+1 Detection and Prevention
```sql
-- N+1 problem (bad):
SELECT * FROM users;
-- Then for EACH user: SELECT * FROM orders WHERE user_id = ?;
-- Fixed with join:
SELECT u.*, o.* FROM users u LEFT JOIN orders o ON o.user_id = u.id;
-- Fixed with batch load:
SELECT * FROM orders WHERE user_id = ANY($1);
```
STOP after physical model — present indexes and optimization strategy for review.
## Phase 4: Migration Strategy
### Zero-Downtime Migration (Expand-Contract)
Never make a breaking change in a single migration. Use two phases:
**Expand phase** (backward compatible):
1. Add new column/table (nullable or with default)
2. Deploy code that writes to both old and new
3. Backfill existing data in batches
4. Deploy code that reads from new
**Contract phase** (after all code uses new schema):
1. Remove code that writes to old
2. Drop old column/table
### Migration Safety Rules
| Rule | Rationale |
|------|-----------|
| Every migration has a corresponding rollback | Safe to revert |
| Test rollback in staging before production | Verify reversibility |
| Data-destructive rollbacks need explicit approval | Prevent accidental data loss |
| Keep migration files immutable once applied | Reproducible state |
| Backfill large tables in batches (1000 rows) | Avoid table locks |
### Backfill Pattern
```sql
-- Backfill in chunks of 1000
UPDATE users SET display_name = username
WHERE display_name IS NULL
AND id IN (SELECT id FROM users WHERE display_name IS NULL LIMIT 1000);
```
### Migration Type Decision Table
| Change Type | Safe Approach | Dangerous Approach |
|------------|---------------|-------------------|
| Add column | Add nullable or with default | Add NOT NULL without default |
| Remove column | Expand-contract (two deploys) | Drop column directly |
| Rename column | Add new, copy data, drop old | ALTER RENAME (breaks queries) |
| Add index | `CREATE INDEX CONCURRENTLY` | `CREATE INDEX` (locks table) |
| Change column type | Add new column, migrate data | `ALTER COLUMN TYPE` (locks table) |
STOP after migration plan — confirm rollback strategy before finalizing.
## Phase 5: Save and Transition
After expliRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.