Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

database-schema-design数据库模式设计

Agent Skill

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

总安装

720

周安装

30

GitHub Stars

1

下载量

240
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:database-schema-design(数据库模式设计)
来源仓库:https://github.com/pixel-process-ug/superkit-agents
仓库路径:skills/database-schema-design
安装命令:
npx skills add https://github.com/pixel-process-ug/superkit-agents --skill database-schema-design
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/pixel-process-ug/superkit-agents --skill database-schema-design

简介

database-schema-design 用于辅助数据库表结构和查询语句编写,适合 SQL 脚本和迁移建议生成。

  • 适用于 schema 分析、索引整理和查询问题排查的场景。
  • 明确数据库类型和连接环境,区分只读分析与写入变更;涉及删除或更新时优先备份保护。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装并使用该技能。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

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:

#QuestionWhat It Determines
1What entities does the system manage?Table names
2What are the relationships between entities?Foreign keys, join tables
3What are the key attributes of each entity?Column definitions
4What are the primary query patterns?Index strategy
5What is the expected data volume? (rows, growth rate)Partitioning, scaling
6What is the read/write ratio?Normalization vs denormalization
7SQL or NoSQL? (or both?)Storage engine selection

Storage Engine Decision Table

FactorChoose SQL (PostgreSQL, MySQL)Choose Document (MongoDB)Choose Key-Value (Redis)
Data shapeStructured, relationalSemi-structured, nestedSimple lookups, caching
Query complexityComplex joins, aggregationsDocument-level queriesKey-based access only
Consistency needsACID requiredEventual consistency OKEphemeral or cached data
Schema evolutionMigrations manageableSchema-free flexibilityNo schema
Scale patternVertical first, then read replicasHorizontal shardingIn-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

DecisionGuidance
Primary keysUUIDs for distributed systems, auto-increment for single-node
Column typesUse the most specific type (timestamptz not varchar for dates)
NullabilityDefault NOT NULL; allow NULL only when absence is meaningful
DefaultsSet sensible defaults (created_at DEFAULT now())
ConstraintsAdd CHECK, UNIQUE, and FK constraints at the schema level
Namingsnake_case, singular table names or plural — be consistent

Normalization Guide

Normal FormRuleViolation ExampleFix
1NFAtomic values, no repeating groupstags VARCHAR "urgent,priority,vip"Separate order_tags table
2NFAll non-key columns depend on entire PKproduct_name in order_items (composite PK)Move to products table
3NFNo transitive dependenciescity depends on zip_code, not user_idSeparate zip_codes table

Rule: Always start normalized. Denormalize only with measured evidence.

Denormalization Decision Table

ScenarioPatternWhen to Apply
Read-heavy dashboardsMaterialized views or summary tablesMeasured slow query
Frequently joined dataEmbed as JSONB columnJoin is >80% of query time
Reporting / analyticsSeparate denormalized reporting tablesOLAP workload
Caching layerComputed columns refreshed on writeHigh-frequency reads

Relationship Patterns

RelationshipImplementationIndex Needed
One-to-OneFK with UNIQUE constraint on childOn FK column
One-to-ManyFK on the "many" sideOn FK column
Many-to-ManyJunction/join table with composite PKOn both FK columns
PolymorphicSeparate FK columns with CHECK constraint (preferred) or type+id patternOn type+id or each FK
Self-referential (trees)parent_id FK to same table; or ltree/materialized pathOn 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 TypeBest ForExample
B-tree (default)Equality and range queriesCREATE INDEX idx_users_email ON users(email)
GINFull-text search, JSONB, arraysCREATE INDEX idx_posts_search ON posts USING GIN(to_tsvector('english', body))
PartialSubset of rows matching conditionCREATE INDEX idx_active_users ON users(email) WHERE active = true
Covering (INCLUDE)Index-only scans avoiding table lookupCREATE INDEX idx_users_email ON users(email) INCLUDE (name)
CompositeMulti-column queriesCREATE INDEX idx_orders ON orders(tenant_id, status)

Composite Index Column Order

PositionColumn TypeReason
FirstHigh-cardinality equality columnsMost selective filter first
MiddleAdditional equality columnsFurther narrows results
LastRange 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 ANALYZEProblemFix
Seq Scan on large tableMissing indexAdd appropriate index
Nested Loop with large outer tableInefficient joinAdd index or restructure query
High actual vs estimated rowsStale statisticsRun ANALYZE on table
Hash Join high memorywork_mem too lowTune work_mem or restructure

N+1 Detection and Prevention

-- 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

RuleRationale
Every migration has a corresponding rollbackSafe to revert
Test rollback in staging before productionVerify reversibility
Data-destructive rollbacks need explicit approvalPrevent accidental data loss
Keep migration files immutable once appliedReproducible state
Backfill large tables in batches (1000 rows)Avoid table locks

Backfill Pattern

-- 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 TypeSafe ApproachDangerous Approach
Add columnAdd nullable or with defaultAdd NOT NULL without default
Remove columnExpand-contract (two deploys)Drop column directly
Rename columnAdd new, copy data, drop oldALTER RENAME (breaks queries)
Add indexCREATE INDEX CONCURRENTLYCREATE INDEX (locks table)
Change column typeAdd new column, migrate dataALTER COLUMN TYPE (locks table)

STOP after migration plan — confirm rollback strategy before finalizing.

Phase 5: Save and Transition

After explicit approval:

  1. Save schema design to docs/database/ or generate migration files
  2. Commit with message: docs(db): add schema design for <feature>

Transition Decision Table

User IntentNext SkillRationale
"Create the migrations"planningPlan migration implementation
"Write specs for this"spec-writingBehavioral specs for data operations
"Implement the schema"test-driven-developmentTDD with migration tests
"Just save the design"NoneSchema design is the deliverable
"Review for performance"performance-optimizationAnalyze query patterns

ORM Guidance

ORMLanguageStrengthWatch Out For
PrismaTypeScriptType-safe schema, migrationsN+1 in nested queries, limited raw SQL
DrizzleTypeScriptSQL-like API, lightweightNewer ecosystem, fewer guides
SQLAlchemyPythonMature, flexible, raw SQL supportComplex session management
GORMGoConvention-based, auto-migrateSilent failures, implicit behavior

ORM Best Practices

  • Always review generated SQL (enable query logging in development)
  • Use eager loading to prevent N+1 queries
  • Write raw SQL for complex queries rather than fighting the ORM
  • Use ORM migrations, not auto-sync in production
  • Test query performance with realistic data volumes

Connection Pooling

  • Use a connection pooler (PgBouncer, built-in pool)
  • Pool size formula: connections = (CPU cores * 2) + disk spindles
  • Use transaction-level pooling for most workloads
  • Application servers should not open raw connections

Anti-Patterns / Common Mistakes

MistakeWhy It Is WrongWhat To Do Instead
No foreign key constraintsOrphaned data, broken relationshipsAlways define FK constraints
VARCHAR for everythingLoses type safety, wastes storageUse specific types (timestamptz, int, uuid)
No indexes on FK columnsSlow joins on related tablesIndex every FK column
Premature denormalizationComplexity without measured benefitStart normalized, denormalize with evidence
Dropping columns directlyBreaks running application codeUse expand-contract pattern
CREATE INDEX without CONCURRENTLYLocks table during index creationAlways use CONCURRENTLY in production
Auto-sync schema in productionUnpredictable destructive changesUse explicit migration files
No rollback plan for migrationsCannot recover from failed deployWrite down migration for every up migration
Nullable columns everywhereLoses data integrity guaranteesDefault NOT NULL, allow NULL intentionally

Anti-Rationalization Guards

  • Do NOT skip the conceptual model — understand entities and relationships first
  • Do NOT add indexes speculatively — measure query patterns first
  • Do NOT denormalize without measured evidence of a performance problem
  • Do NOT create migrations without rollback plans
  • Do NOT skip the discovery phase — understand query patterns and data volume
  • Do NOT drop columns or tables without expand-contract pattern in production

Documentation Lookup (Context7)

Use mcp__context7__resolve-library-id then mcp__context7__query-docs for up-to-date docs. Returned docs override memorized knowledge.

  • prisma — for schema syntax, relations, or migration API
  • typeorm — for entity decorators, repository patterns, or query builder
  • knex — for query builder syntax, migrations, or seed files

Integration Points

SkillRelationship
api-designUpstream: API resources map to database entities
spec-writingUpstream: specs define data persistence requirements
planningDownstream: schema design informs implementation plan
test-driven-developmentDownstream: migration tests written before migration code
performance-optimizationDownstream: query optimization after schema is live
reverse-engineering-specsUpstream: reverse-engineer existing schema behavior
senior-backendParallel: backend specialist for ORM and query patterns

Verification Gate

Before claiming the schema design is complete:

  1. VERIFY all entities and relationships are modeled
  2. VERIFY normalization is at least 3NF (or denormalization is justified)
  3. VERIFY indexes are defined for all query patterns and FK columns
  4. VERIFY migration strategy includes rollback for every step
  5. VERIFY the user has approved the schema design
  6. VERIFY connection pooling strategy is defined for production

Skill Type

Flexible — Adapt storage engine, normalization level, and index strategy to project needs while preserving the conceptual-to-physical modeling progression, migration safety rules, and measured-evidence-before-denormalization principle.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.15%
按下载量换算84

Claude

29.08%
按下载量换算70

Cursor

18.99%
按下载量换算46

Gemini CLI

9.9%
按下载量换算24

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills