AgentSkillsCN

database-design

数据库设计原则与决策方法。包括模式设计、索引策略、ORM 选型,以及无服务器数据库的应用。

SKILL.md
--- frontmatter
name: database-design
description: Database design principles and decision-making. Schema design, indexing strategy, ORM selection, serverless databases.
allowed-tools: Read, Write, Edit, Glob, Grep

Database Design

Learn to THINK, not copy SQL patterns.

🎯 Selective Reading Rule

Read ONLY files relevant to the request! Check the content map, find what you need.

FileDescriptionWhen to Read
database-selection.mdPostgreSQL vs Neon vs Turso vs SQLiteChoosing database
orm-selection.mdDrizzle vs Prisma vs KyselyChoosing ORM
schema-design.mdNormalization, PKs, relationshipsDesigning schema
indexing.mdIndex types, composite indexesPerformance tuning
optimization.mdN+1, EXPLAIN ANALYZEQuery optimization
migrations.mdSafe migrations, serverless DBsSchema changes

⚡ Indexing Strategy (Cheatsheet)

Default to B-Tree. Know when to switch.

Index TypeUse CaseExample
B-TreeEquality (=), Range (<, >), Sorting (ORDER BY)WHERE age > 21
HashExact equality ONLY (Faster than B-Tree, but limited)WHERE uuid = '...'
GINJSONB, Full Text Search, ArraysWHERE data @> '{"tag": "urgent"}'
GiSTGeo-spatial, Nearest NeighborWHERE location <@ box

Composite Index Rule: Order matters! (last_name, first_name) helps WHERE last_name='Bond', but DOES NOT help WHERE first_name='James'. (Leftmost Prefix Rule)

⚖️ Scaling: Partitioning vs Sharding

StrategyWhat is it?ComplexityWhen to use?
PartitioningSplitting one table into chunks on the SAME server.MediumTable > 100GB. Need to delete old data fast (DROP PARTITION).
ShardingSplitting data across DIFFERENT servers.ExtremeWrite QPS > Single Node limit. Massive scale (Petabytes).

🔌 Connection Pooling (Serverless)

Serverless Apps + Postgres = Disaster. Lambda scales to 1,000 instances -> 1,000 DB connections -> DB Crashes.

Solution: Use PgBouncer (or AWS RDS Proxy / Supabase Pooler).

  • Function connects to Proxy (TCP).
  • Proxy holds small pool of persistent connections to DB.
  • Transactional Mode: Connection matches to DB only for duration of transaction. Best for serverless.

⚠️ Core Principle

  • ASK user for database preferences when unclear
  • Choose database/ORM based on CONTEXT
  • Don't default to PostgreSQL for everything

Decision Checklist

Before designing schema:

  • Asked user about database preference?
  • Chosen database for THIS context?
  • Considered deployment environment?
  • Planned index strategy?
  • Defined relationship types?

Anti-Patterns

❌ Default to PostgreSQL for simple apps (SQLite may suffice) ❌ Skip indexing ❌ Use SELECT * in production ❌ Store JSON when structured data is better ❌ Ignore N+1 queries