schema-design
Patterns for designing database schemas with proper normalization and relationships
What this skill does
# Schema Design Skill
Patterns for designing effective database schemas.
## Core Principles
### 1. Choose Appropriate Primary Keys
```sql
-- UUID (recommended for distributed systems)
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
...
);
-- ULID (sortable, URL-safe)
CREATE TABLE posts (
id CHAR(26) PRIMARY KEY,
...
);
-- Auto-increment (simple, sequential)
CREATE TABLE logs (
id SERIAL PRIMARY KEY,
...
);
```
### 2. Define Clear Relationships
```prisma
// One-to-One
model User {
id String @id @default(uuid())
profile Profile?
}
model Profile {
id String @id @default(uuid())
userId String @unique
user User @relation(fields: [userId], references: [id])
}
// One-to-Many
model User {
id String @id @default(uuid())
posts Post[]
}
model Post {
id String @id @default(uuid())
authorId String
author User @relation(fields: [authorId], references: [id])
}
// Many-to-Many
model Post {
id String @id @default(uuid())
tags Tag[]
}
model Tag {
id String @id @default(uuid())
posts Post[]
}
// Explicit join table (when you need extra fields)
model PostTag {
postId String
tagId String
createdAt DateTime @default(now())
post Post @relation(fields: [postId], references: [id])
tag Tag @relation(fields: [tagId], references: [id])
@@id([postId, tagId])
}
```
### 3. Use Appropriate Data Types
```sql
-- Text
VARCHAR(255) -- Names, emails, short text
TEXT -- Long content, descriptions
CHAR(2) -- Country codes, fixed-length
-- Numbers
INTEGER -- Counts, IDs
BIGINT -- Large numbers, timestamps
DECIMAL(10,2) -- Money, precise decimals
REAL/FLOAT -- Scientific (avoid for money!)
-- Date/Time
TIMESTAMP -- Date + time with timezone
DATE -- Date only
INTERVAL -- Time periods
-- Binary
BYTEA -- Binary data, files
UUID -- Universally unique identifiers
-- JSON
JSONB -- Flexible data, preferences
```
### 4. Add Standard Fields
```prisma
model BaseEntity {
// Primary key
id String @id @default(uuid())
// Timestamps
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Soft delete
deletedAt DateTime?
// Audit (optional)
createdBy String?
updatedBy String?
}
```
## Normalization
### First Normal Form (1NF)
- No repeating groups
- Atomic values in each column
```sql
-- Bad: Multiple values in one column
CREATE TABLE users (
id INT,
phone_numbers VARCHAR(255) -- "123-456, 789-012"
);
-- Good: Separate table
CREATE TABLE users (
id INT PRIMARY KEY
);
CREATE TABLE user_phones (
id INT PRIMARY KEY,
user_id INT REFERENCES users(id),
phone_number VARCHAR(20)
);
```
### Second Normal Form (2NF)
- Must be in 1NF
- No partial dependencies on composite keys
```sql
-- Bad: Partial dependency
CREATE TABLE order_items (
order_id INT,
product_id INT,
product_name VARCHAR(255), -- Depends only on product_id
quantity INT,
PRIMARY KEY (order_id, product_id)
);
-- Good: Separate tables
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE order_items (
order_id INT,
product_id INT REFERENCES products(id),
quantity INT,
PRIMARY KEY (order_id, product_id)
);
```
### Third Normal Form (3NF)
- Must be in 2NF
- No transitive dependencies
```sql
-- Bad: Transitive dependency
CREATE TABLE employees (
id INT PRIMARY KEY,
department_id INT,
department_name VARCHAR(255) -- Depends on department_id, not employee
);
-- Good: Separate tables
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE employees (
id INT PRIMARY KEY,
department_id INT REFERENCES departments(id)
);
```
### When to Denormalize
- **Read-heavy workloads**: Cache computed values
- **Reporting**: Pre-aggregate data
- **Performance**: Avoid expensive joins
- **Audit trails**: Snapshot data at point in time
```sql
-- Denormalized for performance
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
-- Snapshot at order time
user_email VARCHAR(255),
user_name VARCHAR(255),
-- Cached totals
item_count INT,
total_amount DECIMAL(10,2)
);
```
## Common Patterns
### Polymorphic Relations
```prisma
// Option 1: Separate tables
model Comment {
id String @id @default(uuid())
content String
postId String?
articleId String?
post Post? @relation(fields: [postId], references: [id])
article Article? @relation(fields: [articleId], references: [id])
}
// Option 2: Type column + ID
model Comment {
id String @id @default(uuid())
content String
targetType String // "post" | "article"
targetId String
@@index([targetType, targetId])
}
```
### Self-Referential Relations
```prisma
// Hierarchical data (categories, org chart)
model Category {
id String @id @default(uuid())
name String
parentId String?
parent Category? @relation("CategoryHierarchy", fields: [parentId], references: [id])
children Category[] @relation("CategoryHierarchy")
}
// User relationships (followers)
model User {
id String @id @default(uuid())
following Follow[] @relation("Following")
followers Follow[] @relation("Followers")
}
model Follow {
followerId String
followingId String
createdAt DateTime @default(now())
follower User @relation("Following", fields: [followerId], references: [id])
following User @relation("Followers", fields: [followingId], references: [id])
@@id([followerId, followingId])
}
```
### Enums vs Lookup Tables
```prisma
// Enum (fixed, small set)
enum Role {
USER
ADMIN
MODERATOR
}
model User {
role Role @default(USER)
}
// Lookup table (dynamic, many values)
model Status {
id Int @id @default(autoincrement())
name String @unique
orders Order[]
}
model Order {
statusId Int
status Status @relation(fields: [statusId], references: [id])
}
```
## Multi-Tenant Patterns
### Column-Based Isolation
```prisma
model Tenant {
id String @id @default(uuid())
name String
}
model User {
id String @id @default(uuid())
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id])
@@index([tenantId])
}
// Always filter by tenant
const users = await prisma.user.findMany({
where: { tenantId: currentTenant.id },
});
```
### Schema-Based Isolation
```sql
-- One schema per tenant
CREATE SCHEMA tenant_123;
CREATE TABLE tenant_123.users (...);
-- Dynamic schema selection
SET search_path TO tenant_123;
SELECT * FROM users;
```
## Integration
Used by:
- `database-developer` agent
- Prisma/TypeORM stack skills
Related 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.