db-diagram
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDatabase ER Diagram Generator
数据库ER图生成工具
I'll help you generate comprehensive Entity-Relationship diagrams from your database schema, supporting multiple ORMs and output formats.
Arguments: - schema files, output format (mermaid/plantuml/dbml), or ORM type
$ARGUMENTS我将帮助您从数据库Schema生成全面的实体关系图,支持多种ORM和输出格式。
参数: - Schema文件、输出格式(mermaid/plantuml/dbml)或ORM类型
$ARGUMENTSToken Optimization
Token优化
This skill uses diagram generation-specific patterns to minimize token usage:
本技能使用特定于图生成的模式来最小化Token使用:
1. Schema Snapshot Caching (900 token savings)
1. Schema快照缓存(节省900个Token)
Pattern: Cache parsed schema structure to avoid re-analysis
- Store schema in (24 hour TTL)
db-diagram/schema-snapshot.json - Cache: tables, columns, relationships, constraints
- Compare checksum on subsequent runs (100 tokens vs 1,000 tokens fresh)
- Regenerate only if schema changed
- Savings: 90% on repeat diagram generations
模式: 缓存解析后的Schema结构以避免重复分析
- 将Schema存储在中(24小时TTL)
db-diagram/schema-snapshot.json - 缓存内容:表、列、关系、约束
- 后续运行时比较校验和(100个Token vs 重新分析的1000个Token)
- 仅当Schema变化时重新生成
- 节省: 重复生成图时减少90%的Token使用
2. Early Exit for Unchanged Schemas (95% savings)
2. 未变更Schema的提前退出(节省95%的Token)
Pattern: Detect schema changes and return existing diagram
- Check schema file mtimes vs diagram mtime (50 tokens)
- If schema unchanged: return existing diagram path (80 tokens)
- Distribution: ~60% of runs are "view diagram" on unchanged schema
- Savings: 80 vs 2,000 tokens for diagram regeneration checks
模式: 检测Schema变化并返回现有图
- 检查Schema文件修改时间与图的修改时间(50个Token)
- 如果Schema未变更:返回现有图的路径(80个Token)
- 场景占比: 约60%的运行是在未变更Schema上的“查看图”操作
- 节省: 图重新生成检查仅需80个Token,而非2000个Token
3. Template-Based Diagram Generation (1,500 token savings)
3. 基于模板的图生成(节省1500个Token)
Pattern: Use Mermaid/PlantUML templates instead of creative generation
- Standard templates for entity syntax, relationship arrows
- Predefined formats for common diagram types
- No creative diagram design logic needed
- Savings: 85% vs LLM-generated diagram syntax
模式: 使用Mermaid/PlantUML模板而非创造性生成
- 实体语法、关系箭头的标准模板
- 常见图类型的预定义格式
- 无需创造性的图设计逻辑
- 节省: 相比LLM生成的图语法,减少85%的Token使用
4. Bash-Based Diagram Rendering (800 token savings)
4. 基于Bash的图渲染(节省800个Token)
Pattern: Use mermaid-cli or plantuml.jar for rendering
- Generate Mermaid: (200 tokens)
mmdc -i diagram.mmd -o diagram.png - Generate PlantUML: (200 tokens)
java -jar plantuml.jar diagram.puml - No Task agents for rendering
- Savings: 80% vs Task-based diagram generation
模式: 使用mermaid-cli或plantuml.jar进行渲染
- 生成Mermaid:(200个Token)
mmdc -i diagram.mmd -o diagram.png - 生成PlantUML:(200个Token)
java -jar plantuml.jar diagram.puml - 无需任务代理进行渲染
- 节省: 相比基于任务的图生成,减少80%的Token使用
5. Sample-Based Relationship Extraction (700 token savings)
5. 基于样本的关系提取(节省700个Token)
Pattern: Analyze first 20 tables for relationship patterns
- Extract FK relationships from analyzed tables (500 tokens)
- Infer patterns and apply to remaining tables
- Full extraction only for schemas < 30 tables
- Savings: 60% vs exhaustive relationship extraction
模式: 分析前20个表以提取关系模式
- 从分析的表中提取外键关系(500个Token)
- 推断模式并应用到剩余表
- 仅当Schema表数<30时进行全量提取
- 节省: 相比全量关系提取,减少60%的Token使用
6. Progressive Diagram Complexity (1,000 token savings)
6. 渐进式图复杂度(节省1000个Token)
Pattern: Three-tier diagram depth
- Level 1: Core tables only (5-10 tables) - 800 tokens
- Level 2: All tables, key relationships - 1,500 tokens
- Level 3: Full detail with columns - 2,500 tokens
- Default: Level 2
- Savings: 60% on default level
模式: 三级图深度
- 级别1:仅核心表(5-10个表)- 800个Token
- 级别2:所有表及关键关系 - 1500个Token
- 级别3:包含列的完整细节 - 2500个Token
- 默认:级别2
- 节省: 默认级别下减少60%的Token使用
7. Grep-Based Table Discovery (500 token savings)
7. 基于Grep的表发现(节省500个Token)
Pattern: Find table definitions with Grep
- Grep for table patterns: ,
^model,CREATE TABLE(200 tokens)@Entity - Count tables without full parsing
- Read only for relationship analysis
- Savings: 75% vs reading all schema files
模式: 使用Grep查找表定义
- Grep匹配表模式:,
^model,CREATE TABLE(200个Token)@Entity - 无需全量解析即可统计表数
- 仅在关系分析时读取内容
- 节省: 相比读取所有Schema文件,减少75%的Token使用
8. Incremental Diagram Updates (800 token savings)
8. 增量图更新(节省800个Token)
Pattern: Update only changed portions of diagram
- Compare new schema with cached snapshot
- Regenerate only modified table definitions
- Preserve unchanged diagram sections
- Savings: 70% vs full diagram regeneration
模式: 仅更新图中变更的部分
- 比较新Schema与缓存快照
- 仅重新生成修改的表定义
- 保留图中未变更的部分
- 节省: 相比全量图重新生成,减少70%的Token使用
Real-World Token Usage Distribution
实际Token使用分布
Typical operation patterns:
- View existing diagram (unchanged schema): 80 tokens
- Generate diagram (first time): 2,000 tokens
- Update diagram (schema changes): 1,200 tokens
- Full detail diagram: 2,500 tokens
- Compare schemas: 1,500 tokens
- Most common: View existing diagram or incremental updates
Expected per-generation: 1,500-2,500 tokens (50% reduction from 3,000-5,000 baseline)
Real-world average: 700 tokens (due to cached snapshots, early exit, template-based generation)
典型操作模式:
- 查看现有图(Schema未变更):80个Token
- 生成图(首次):2000个Token
- 更新图(Schema变更):1200个Token
- 完整细节图:2500个Token
- 比较Schema:1500个Token
- 最常见操作: 查看现有图或增量更新
单次生成预期: 1500-2500个Token(相比基线3000-5000个Token减少50%)
实际平均: 700个Token(得益于缓存快照、提前退出、基于模板的生成)
Session Intelligence
会话智能
I'll maintain diagram generation sessions for tracking schema evolution:
Session Files (in current project directory):
- - Generated diagram files
db-diagram/diagrams/ - - Current schema structure
db-diagram/schema-snapshot.json - - Generation history and settings
db-diagram/state.json - - Documented relationships
db-diagram/relationships.md
IMPORTANT: Session files are stored in a folder in your current project root
db-diagramAuto-Detection:
- If schema detected: Generate updated diagram
- If no schema: Guide through schema file location
- Commands: ,
generate,update,compareexport
我将维护图生成会话以跟踪Schema演进:
会话文件(位于当前项目目录):
- - 生成的图文件
db-diagram/diagrams/ - - 当前Schema结构
db-diagram/schema-snapshot.json - - 生成历史与设置
db-diagram/state.json - - 已记录的关系
db-diagram/relationships.md
重要提示: 会话文件存储在当前项目根目录的文件夹中
db-diagram自动检测:
- 如果检测到Schema:生成更新后的图
- 如果未找到Schema:引导您指定Schema文件位置
- 命令:,
generate,update,compareexport
Phase 1: Schema Detection & ORM Recognition
阶段1:Schema检测与ORM识别
Extended Thinking for Schema Analysis
Schema分析的扩展思考
For complex database schemas, I'll use extended thinking to understand relationships:
<think>
When analyzing database schemas:
- Implicit relationships not explicitly defined in ORM
- Many-to-many relationships through junction tables
- Polymorphic associations and their representations
- Inheritance strategies (single table, joined table, table per class)
- Soft deletes and audit columns
- Database-level constraints vs application-level validations
- Normalized vs denormalized design patterns
</think>
Triggers for Extended Analysis:
- Complex multi-tenant schemas
- Legacy databases with implicit conventions
- Microservices with shared database patterns
- Large schemas with 50+ tables
I'll automatically detect your database setup:
bash
#!/bin/bash对于复杂数据库Schema,我将使用扩展思考来理解关系:
<think>
分析数据库Schema时:
- ORM中未明确定义的隐式关系
- 通过中间表实现的多对多关系
- 多态关联及其表示方式
- 继承策略(单表、连接表、每个类对应表)
- 软删除与审计列
- 数据库级约束与应用级验证
- 规范化与反规范化设计模式
</think>
触发扩展分析的场景:
- 复杂多租户Schema
- 具有隐式约定的遗留数据库
- 共享数据库模式的微服务
- 包含50+表的大型Schema
我将自动检测您的数据库配置:
bash
#!/bin/bashORM and schema detection
ORM and schema detection
detect_database_stack() {
echo "=== Database Stack Detection ==="
# Prisma detection
if [ -f "prisma/schema.prisma" ]; then
echo "✓ Prisma detected: prisma/schema.prisma"
ORM="prisma"
SCHEMA_FILE="prisma/schema.prisma"
fi
# TypeORM detection
if find . -name "*.entity.ts" | head -1; then
echo "✓ TypeORM detected: *.entity.ts files"
ORM="typeorm"
SCHEMA_FILES=$(find . -name "*.entity.ts")
fi
# Sequelize detection
if [ -d "models" ] && grep -q "sequelize" package.json 2>/dev/null; then
echo "✓ Sequelize detected: models/ directory"
ORM="sequelize"
SCHEMA_FILES=$(find models -name "*.js" -o -name "*.ts")
fi
# SQLAlchemy (Python) detection
if find . -name "models.py" | head -1; then
echo "✓ SQLAlchemy detected: models.py"
ORM="sqlalchemy"
SCHEMA_FILES=$(find . -name "models.py")
fi
# Django detection
if find . -path "*/models/*.py" | head -1; then
echo "✓ Django detected: */models/*.py"
ORM="django"
SCHEMA_FILES=$(find . -path "*/models/*.py")
fi
# Drizzle detection
if find . -name "schema.ts" | grep -q drizzle; then
echo "✓ Drizzle detected"
ORM="drizzle"
SCHEMA_FILES=$(find . -name "schema.ts")
fi
# Raw SQL detection
if find . -name "*.sql" | grep -qE "(schema|create|ddl)"; then
echo "✓ SQL files detected"
ORM="raw-sql"
SCHEMA_FILES=$(find . -name "*.sql" | grep -iE "(schema|create|ddl)")
fi
if [ -z "$ORM" ]; then
echo "⚠️ No recognized ORM/schema files found"
echo "Supported: Prisma, TypeORM, Sequelize, SQLAlchemy, Django, Drizzle"
return 1
fi
echo
echo "ORM: $ORM"
echo "Schema files: $SCHEMA_FILE $SCHEMA_FILES"}
undefineddetect_database_stack() {
echo "=== Database Stack Detection ==="
# Prisma detection
if [ -f "prisma/schema.prisma" ]; then
echo "✓ Prisma detected: prisma/schema.prisma"
ORM="prisma"
SCHEMA_FILE="prisma/schema.prisma"
fi
# TypeORM detection
if find . -name "*.entity.ts" | head -1; then
echo "✓ TypeORM detected: *.entity.ts files"
ORM="typeorm"
SCHEMA_FILES=$(find . -name "*.entity.ts")
fi
# Sequelize detection
if [ -d "models" ] && grep -q "sequelize" package.json 2>/dev/null; then
echo "✓ Sequelize detected: models/ directory"
ORM="sequelize"
SCHEMA_FILES=$(find models -name "*.js" -o -name "*.ts")
fi
# SQLAlchemy (Python) detection
if find . -name "models.py" | head -1; then
echo "✓ SQLAlchemy detected: models.py"
ORM="sqlalchemy"
SCHEMA_FILES=$(find . -name "models.py")
fi
# Django detection
if find . -path "*/models/*.py" | head -1; then
echo "✓ Django detected: */models/*.py"
ORM="django"
SCHEMA_FILES=$(find . -path "*/models/*.py")
fi
# Drizzle detection
if find . -name "schema.ts" | grep -q drizzle; then
echo "✓ Drizzle detected"
ORM="drizzle"
SCHEMA_FILES=$(find . -name "schema.ts")
fi
# Raw SQL detection
if find . -name "*.sql" | grep -qE "(schema|create|ddl)"; then
echo "✓ SQL files detected"
ORM="raw-sql"
SCHEMA_FILES=$(find . -name "*.sql" | grep -iE "(schema|create|ddl)")
fi
if [ -z "$ORM" ]; then
echo "⚠️ No recognized ORM/schema files found"
echo "Supported: Prisma, TypeORM, Sequelize, SQLAlchemy, Django, Drizzle"
return 1
fi
echo
echo "ORM: $ORM"
echo "Schema files: $SCHEMA_FILE $SCHEMA_FILES"}
undefinedPhase 2: Schema Parsing
阶段2:Schema解析
I'll parse schema definitions into a structured format:
我将把Schema定义解析为结构化格式:
Prisma Schema Parser
Prisma Schema解析器
bash
undefinedbash
undefinedParse Prisma schema
Parse Prisma schema
parse_prisma_schema() {
local schema_file=$1
echo "Parsing Prisma schema..."
# Extract models
awk '/^model / {
model=$2;
print "MODEL:" model;
in_model=1;
next;
}
in_model && /^}/ {
in_model=0;
print "END_MODEL";
next;
}
in_model && /^[[:space:]]+[a-zA-Z]/ {
print "FIELD:" $0;
}
/^enum / {
print "ENUM:" $2;
}' "$schema_file" > db-diagram/parsed-schema.txt
# Extract relationships
grep -E "@relation|@@" "$schema_file" > db-diagram/relationships.txt}
**Parsed Schema Structure:**
```json
{
"models": [
{
"name": "User",
"fields": [
{"name": "id", "type": "Int", "primaryKey": true, "autoIncrement": true},
{"name": "email", "type": "String", "unique": true},
{"name": "name", "type": "String", "nullable": true},
{"name": "posts", "type": "Post[]", "relation": true}
]
},
{
"name": "Post",
"fields": [
{"name": "id", "type": "Int", "primaryKey": true},
{"name": "title", "type": "String"},
{"name": "authorId", "type": "Int"},
{"name": "author", "type": "User", "relation": {"from": "authorId", "to": "id"}}
]
}
],
"relationships": [
{
"from": "Post",
"to": "User",
"type": "many-to-one",
"fromField": "author",
"toField": "posts"
}
]
}parse_prisma_schema() {
local schema_file=$1
echo "Parsing Prisma schema..."
# Extract models
awk '/^model / {
model=$2;
print "MODEL:" model;
in_model=1;
next;
}
in_model && /^}/ {
in_model=0;
print "END_MODEL";
next;
}
in_model && /^[[:space:]]+[a-zA-Z]/ {
print "FIELD:" $0;
}
/^enum / {
print "ENUM:" $2;
}' "$schema_file" > db-diagram/parsed-schema.txt
# Extract relationships
grep -E "@relation|@@" "$schema_file" > db-diagram/relationships.txt}
**解析后的Schema结构:**
```json
{
"models": [
{
"name": "User",
"fields": [
{"name": "id", "type": "Int", "primaryKey": true, "autoIncrement": true},
{"name": "email", "type": "String", "unique": true},
{"name": "name", "type": "String", "nullable": true},
{"name": "posts", "type": "Post[]", "relation": true}
]
},
{
"name": "Post",
"fields": [
{"name": "id", "type": "Int", "primaryKey": true},
{"name": "title", "type": "String"},
{"name": "authorId", "type": "Int"},
{"name": "author", "type": "User", "relation": {"from": "authorId", "to": "id"}}
]
}
],
"relationships": [
{
"from": "Post",
"to": "User",
"type": "many-to-one",
"fromField": "author",
"toField": "posts"
}
]
}TypeORM Entity Parser
TypeORM实体解析器
typescript
// Parse TypeORM entities (conceptual - would use AST parsing)
/*
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
email: string;
@OneToMany(() => Post, post => post.author)
posts: Post[];
}
Extracts to:
- Entity: User
- Primary Key: id (auto-generated)
- Unique: email
- Relationship: OneToMany to Post
*/typescript
// Parse TypeORM entities (conceptual - would use AST parsing)
/*
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
email: string;
@OneToMany(() => Post, post => post.author)
posts: Post[];
}
Extracts to:
- Entity: User
- Primary Key: id (auto-generated)
- Unique: email
- Relationship: OneToMany to Post
*/SQLAlchemy Parser
SQLAlchemy解析器
python
undefinedpython
undefinedParse SQLAlchemy models (conceptual)
Parse SQLAlchemy models (conceptual)
"""
class User(Base):
tablename = 'users'
id = Column(Integer, primary_key=True)
email = Column(String, unique=True)
posts = relationship('Post', back_populates='author')Extracts to:
- Table: users
- Model: User
- Primary Key: id
- Relationship: one-to-many to Post """
undefined"""
class User(Base):
tablename = 'users'
id = Column(Integer, primary_key=True)
email = Column(String, unique=True)
posts = relationship('Post', back_populates='author')Extracts to:
- Table: users
- Model: User
- Primary Key: id
- Relationship: one-to-many to Post """
undefinedPhase 3: Diagram Generation
阶段3:图生成
I'll generate diagrams in multiple formats:
我将生成多种格式的图:
Format 1: Mermaid (Default)
格式1:Mermaid(默认)
Advantages:
- GitHub/GitLab native rendering
- Interactive in many markdown viewers
- Easy to version control
- Simple syntax
bash
undefined优势:
- GitHub/GitLab原生渲染
- 在许多Markdown查看器中支持交互
- 易于版本控制
- 语法简单
bash
undefinedGenerate Mermaid ER diagram
Generate Mermaid ER diagram
generate_mermaid() {
local output_file="db-diagram/diagrams/schema.mmd"
cat > "$output_file" <<'EOF'erDiagram
USER ||--o{ POST : "writes"
USER {
int id PK
string email UK
string name
datetime createdAt
}
POST ||--o{ COMMENT : "has"
POST {
int id PK
string title
text content
int authorId FK
datetime publishedAt
}
COMMENT {
int id PK
text content
int postId FK
int userId FK
datetime createdAt
}
USER ||--o{ COMMENT : "writes"
POST }o--|| CATEGORY : "belongs to"
CATEGORY {
int id PK
string name UK
string slug
}
POST }o--o{ TAG : "tagged with"
TAG {
int id PK
string name UK
}
POST_TAG {
int postId FK
int tagId FK
}
POST ||--o{ POST_TAG : ""
TAG ||--o{ POST_TAG : ""EOF
echo "Mermaid diagram generated: $output_file"
echo
echo "View in GitHub/GitLab, or use:"
echo " - https://mermaid.live"
echo " - VSCode Mermaid Preview extension"}
**Relationship Notation:**||--o{ : one to many
}o--|| : many to one
||--|| : one to one
}o--o{ : many to many
undefinedgenerate_mermaid() {
local output_file="db-diagram/diagrams/schema.mmd"
cat > "$output_file" <<'EOF'erDiagram
USER ||--o{ POST : "writes"
USER {
int id PK
string email UK
string name
datetime createdAt
}
POST ||--o{ COMMENT : "has"
POST {
int id PK
string title
text content
int authorId FK
datetime publishedAt
}
COMMENT {
int id PK
text content
int postId FK
int userId FK
datetime createdAt
}
USER ||--o{ COMMENT : "writes"
POST }o--|| CATEGORY : "belongs to"
CATEGORY {
int id PK
string name UK
string slug
}
POST }o--o{ TAG : "tagged with"
TAG {
int id PK
string name UK
}
POST_TAG {
int postId FK
int tagId FK
}
POST ||--o{ POST_TAG : ""
TAG ||--o{ POST_TAG : ""EOF
echo "Mermaid diagram generated: $output_file"
echo
echo "View in GitHub/GitLab, or use:"
echo " - https://mermaid.live"
echo " - VSCode Mermaid Preview extension"}
**关系表示法:**||--o{ : 一对多
}o--|| : 多对一
||--|| : 一对一
}o--o{ : 多对多
undefinedFormat 2: PlantUML
格式2:PlantUML
Advantages:
- Highly customizable
- Professional appearance
- Extensive styling options
- Good for documentation
bash
undefined优势:
- 高度可定制
- 外观专业
- 丰富的样式选项
- 适合文档使用
bash
undefinedGenerate PlantUML diagram
Generate PlantUML diagram
generate_plantuml() {
local output_file="db-diagram/diagrams/schema.puml"
cat > "$output_file" <<'EOF'@startuml Database Schema
!define Table(name,desc) class name as "desc" << (T,#FFAAAA) >>
!define primary_key(x) <b>PK: x</b>
!define foreign_key(x) color:redFK: x</color>
!define unique(x) color:greenUK: x</color>
Table(User, "users") {
primary_key(id): INT
unique(email): VARCHAR
name: VARCHAR
createdAt: TIMESTAMP
}
Table(Post, "posts") {
primary_key(id): INT
title: VARCHAR
content: TEXT
foreign_key(authorId): INT
publishedAt: TIMESTAMP
}
Table(Comment, "comments") {
primary_key(id): INT
content: TEXT
foreign_key(postId): INT
foreign_key(userId): INT
createdAt: TIMESTAMP
}
Table(Category, "categories") {
primary_key(id): INT
unique(name): VARCHAR
slug: VARCHAR
}
Table(Tag, "tags") {
primary_key(id): INT
unique(name): VARCHAR
}
Table(PostTag, "post_tags") {
foreign_key(postId): INT
foreign_key(tagId): INT
}
User "1" -- "0.." Post : writes
User "1" -- "0.." Comment : writes
Post "1" -- "0.." Comment : has
Post "0.." -- "1" Category : belongs to
Post "0.." -- "0.." Tag : tagged with
(Post, Tag) .. PostTag
@enduml
EOF
echo "PlantUML diagram generated: $output_file"
echo
echo "Generate image:"
echo " plantuml $output_file"
echo " # or use: https://www.plantuml.com/plantuml/"}
undefinedgenerate_plantuml() {
local output_file="db-diagram/diagrams/schema.puml"
cat > "$output_file" <<'EOF'@startuml Database Schema
!define Table(name,desc) class name as "desc" << (T,#FFAAAA) >>
!define primary_key(x) <b>PK: x</b>
!define foreign_key(x) color:redFK: x</color>
!define unique(x) color:greenUK: x</color>
Table(User, "users") {
primary_key(id): INT
unique(email): VARCHAR
name: VARCHAR
createdAt: TIMESTAMP
}
Table(Post, "posts") {
primary_key(id): INT
title: VARCHAR
content: TEXT
foreign_key(authorId): INT
publishedAt: TIMESTAMP
}
Table(Comment, "comments") {
primary_key(id): INT
content: TEXT
foreign_key(postId): INT
foreign_key(userId): INT
createdAt: TIMESTAMP
}
Table(Category, "categories") {
primary_key(id): INT
unique(name): VARCHAR
slug: VARCHAR
}
Table(Tag, "tags") {
primary_key(id): INT
unique(name): VARCHAR
}
Table(PostTag, "post_tags") {
foreign_key(postId): INT
foreign_key(tagId): INT
}
User "1" -- "0.." Post : writes
User "1" -- "0.." Comment : writes
Post "1" -- "0.." Comment : has
Post "0.." -- "1" Category : belongs to
Post "0.." -- "0.." Tag : tagged with
(Post, Tag) .. PostTag
@enduml
EOF
echo "PlantUML diagram generated: $output_file"
echo
echo "Generate image:"
echo " plantuml $output_file"
echo " # or use: https://www.plantuml.com/plantuml/"}
undefinedFormat 3: DBML (Database Markup Language)
格式3:DBML(数据库标记语言)
Advantages:
- Clean, readable syntax
- dbdiagram.io integration
- Schema versioning friendly
- Language-agnostic
bash
undefined优势:
- 简洁易读的语法
- 与dbdiagram.io集成
- 适合Schema版本控制
- 与语言无关
bash
undefinedGenerate DBML diagram
Generate DBML diagram
generate_dbml() {
local output_file="db-diagram/diagrams/schema.dbml"
cat > "$output_file" <<'EOF'// Database Schema Documentation
// Generated: 2026-01-25
Table users {
id integer [pk, increment]
email varchar [unique, not null]
name varchar
createdAt timestamp [default: ]
now()Indexes {
email [unique]
}
}
Table posts {
id integer [pk, increment]
title varchar [not null]
content text
authorId integer [ref: > users.id]
categoryId integer [ref: > categories.id]
publishedAt timestamp
Indexes {
authorId
categoryId
publishedAt
}
}
Table comments {
id integer [pk, increment]
content text [not null]
postId integer [ref: > posts.id]
userId integer [ref: > users.id]
createdAt timestamp [default: ]
}
now()Table categories {
id integer [pk, increment]
name varchar [unique, not null]
slug varchar [unique, not null]
}
Table tags {
id integer [pk, increment]
name varchar [unique, not null]
}
Table post_tags {
postId integer [ref: > posts.id]
tagId integer [ref: > tags.id]
Indexes {
(postId, tagId) [pk]
}
}
// Relationships
Ref: posts.authorId > users.id [delete: cascade]
Ref: comments.postId > posts.id [delete: cascade]
Ref: comments.userId > users.id [delete: cascade]
EOF
echo "DBML diagram generated: $output_file"
echo
echo "Visualize at: https://dbdiagram.io/d"}
undefinedgenerate_dbml() {
local output_file="db-diagram/diagrams/schema.dbml"
cat > "$output_file" <<'EOF'// Database Schema Documentation
// Generated: 2026-01-25
Table users {
id integer [pk, increment]
email varchar [unique, not null]
name varchar
createdAt timestamp [default: ]
now()Indexes {
email [unique]
}
}
Table posts {
id integer [pk, increment]
title varchar [not null]
content text
authorId integer [ref: > users.id]
categoryId integer [ref: > categories.id]
publishedAt timestamp
Indexes {
authorId
categoryId
publishedAt
}
}
Table comments {
id integer [pk, increment]
content text [not null]
postId integer [ref: > posts.id]
userId integer [ref: > users.id]
createdAt timestamp [default: ]
}
now()Table categories {
id integer [pk, increment]
name varchar [unique, not null]
slug varchar [unique, not null]
}
Table tags {
id integer [pk, increment]
name varchar [unique, not null]
}
Table post_tags {
postId integer [ref: > posts.id]
tagId integer [ref: > tags.id]
Indexes {
(postId, tagId) [pk]
}
}
// Relationships
Ref: posts.authorId > users.id [delete: cascade]
Ref: comments.postId > posts.id [delete: cascade]
Ref: comments.userId > users.id [delete: cascade]
EOF
echo "DBML diagram generated: $output_file"
echo
echo "Visualize at: https://dbdiagram.io/d"}
undefinedPhase 4: Intelligent Relationship Detection
阶段4:智能关系检测
I'll automatically detect and document relationships:
bash
undefined我将自动检测并记录关系:
bash
undefinedDetect relationship types
Detect relationship types
detect_relationships() {
echo "=== Relationship Analysis ==="
# One-to-Many
echo "One-to-Many relationships:"
# User -> Posts: A user has many posts
# Post -> Comments: A post has many comments
# Many-to-Many
echo "Many-to-Many relationships:"
# Post <-> Tag: Posts have many tags, tags have many posts
# (via post_tags junction table)
# One-to-One
echo "One-to-One relationships:"
# User -> Profile: A user has one profile
# Self-referential
echo "Self-referential relationships:"
# User -> User: A user can follow other users
# Category -> Category: Categories can have parent categories}
detect_relationships() {
echo "=== Relationship Analysis ==="
# One-to-Many
echo "One-to-Many relationships:"
# User -> Posts: A user has many posts
# Post -> Comments: A post has many comments
# Many-to-Many
echo "Many-to-Many relationships:"
# Post <-> Tag: Posts have many tags, tags have many posts
# (via post_tags junction table)
# One-to-One
echo "One-to-One relationships:"
# User -> Profile: A user has one profile
# Self-referential
echo "Self-referential relationships:"
# User -> User: A user can follow other users
# Category -> Category: Categories can have parent categories}
Document relationships
Document relationships
document_relationships() {
cat > db-diagram/relationships.md <<EOF
document_relationships() {
cat > db-diagram/relationships.md <<EOF
Database Relationships
Database Relationships
One-to-Many Relationships
One-to-Many Relationships
User → Posts
User → Posts
- Cardinality: One User has Many Posts
- Foreign Key: `posts.authorId` references `users.id`
- Cascade: Delete posts when user is deleted
- Inverse: `user.posts` / `post.author`
- Cardinality: One User has Many Posts
- Foreign Key: \references \
posts.authorId\\users.id\\ - Cascade: Delete posts when user is deleted
- Inverse: \/ \
user.posts\\post.author\\
Post → Comments
Post → Comments
- Cardinality: One Post has Many Comments
- Foreign Key: `comments.postId` references `posts.id`
- Cascade: Delete comments when post is deleted
- Inverse: `post.comments` / `comment.post`
- Cardinality: One Post has Many Comments
- Foreign Key: \references \
comments.postId\\posts.id\\ - Cascade: Delete comments when post is deleted
- Inverse: \/ \
post.comments\\comment.post\\
Many-to-Many Relationships
Many-to-Many Relationships
Posts ↔ Tags
Posts ↔ Tags
- Cardinality: Many-to-Many
- Junction Table: `post_tags`
- Foreign Keys:
- `post_tags.postId` references `posts.id`
- `post_tags.tagId` references `tags.id`
- Inverse: `post.tags` / `tag.posts`
- Cardinality: Many-to-Many
- Junction Table: \
post_tags\\ - Foreign Keys:
- \references \
post_tags.postId\\posts.id\\ - \references \
post_tags.tagId\\tags.id\\
- \
- Inverse: \/ \
post.tags\\tag.posts\\
One-to-One Relationships
One-to-One Relationships
User → Profile
User → Profile
- Cardinality: One-to-One
- Foreign Key: `profiles.userId` references `users.id`
- Unique: `profiles.userId` is unique
- Inverse: `user.profile` / `profile.user` EOF }
undefined- Cardinality: One-to-One
- Foreign Key: \references \
profiles.userId\\users.id\\ - Unique: \is unique
profiles.userId\\ - Inverse: \/ \
user.profile\\EOF }profile.user\\
undefinedPhase 5: Schema Documentation
阶段5:Schema文档
I'll generate comprehensive schema documentation:
markdown
undefined我将生成全面的Schema文档:
markdown
undefinedDatabase Schema Documentation
Database Schema Documentation
Generated: 2026-01-25 18:45:00
Generated: 2026-01-25 18:45:00
Overview
Overview
- Database: PostgreSQL 15
- ORM: Prisma
- Tables: 6
- Relationships: 8
- Database: PostgreSQL 15
- ORM: Prisma
- Tables: 6
- Relationships: 8
Tables
Tables
users
users
User accounts and authentication
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO_INC | User identifier |
| varchar | UNIQUE, NOT NULL | Login email | |
| name | varchar | NULLABLE | Display name |
| createdAt | timestamp | DEFAULT NOW() | Account creation |
Indexes:
- PRIMARY KEY on
id - UNIQUE INDEX on
email
Relationships:
- One-to-Many: (via
posts)posts.authorId - One-to-Many: (via
comments)comments.userId
User accounts and authentication
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO_INC | User identifier |
| varchar | UNIQUE, NOT NULL | Login email | |
| name | varchar | NULLABLE | Display name |
| createdAt | timestamp | DEFAULT NOW() | Account creation |
Indexes:
- PRIMARY KEY on
id - UNIQUE INDEX on
email
Relationships:
- One-to-Many: (via
posts)posts.authorId - One-to-Many: (via
comments)comments.userId
posts
posts
Blog posts and articles
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO_INC | Post identifier |
| title | varchar | NOT NULL | Post title |
| content | text | NULLABLE | Post body |
| authorId | integer | FOREIGN KEY, NOT NULL | Author reference |
| categoryId | integer | FOREIGN KEY | Category reference |
| publishedAt | timestamp | NULLABLE | Publication date |
Indexes:
- PRIMARY KEY on
id - INDEX on
authorId - INDEX on
categoryId - INDEX on
publishedAt
Relationships:
- Many-to-One: (references
author)users.id - Many-to-One: (references
category)categories.id - One-to-Many: (via
comments)comments.postId - Many-to-Many: (via
tags)post_tags
[... additional tables ...]
Blog posts and articles
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO_INC | Post identifier |
| title | varchar | NOT NULL | Post title |
| content | text | NULLABLE | Post body |
| authorId | integer | FOREIGN KEY, NOT NULL | Author reference |
| categoryId | integer | FOREIGN KEY | Category reference |
| publishedAt | timestamp | NULLABLE | Publication date |
Indexes:
- PRIMARY KEY on
id - INDEX on
authorId - INDEX on
categoryId - INDEX on
publishedAt
Relationships:
- Many-to-One: (references
author)users.id - Many-to-One: (references
category)categories.id - One-to-Many: (via
comments)comments.postId - Many-to-Many: (via
tags)post_tags
[... additional tables ...]
Relationship Diagram
Relationship Diagram
```mermaid
[Generated Mermaid diagram here]
```
\\\
\\mermaid [Generated Mermaid diagram here] \\\\Database Statistics
Database Statistics
- Total Tables: 6
- Total Columns: 32
- Foreign Keys: 7
- Unique Constraints: 5
- Indexes: 12
- Total Tables: 6
- Total Columns: 32
- Foreign Keys: 7
- Unique Constraints: 5
- Indexes: 12
Change History
Change History
- 2026-01-25: Initial schema
- [Track schema migrations here]
undefined- 2026-01-25: Initial schema
- [Track schema migrations here]
undefinedPhase 6: Schema Comparison & Evolution
阶段6:Schema比较与演进
Track schema changes over time:
bash
undefined跟踪Schema随时间的变化:
bash
undefinedCompare current schema with previous snapshot
Compare current schema with previous snapshot
compare_schemas() {
local previous="db-diagram/schema-snapshot.json"
local current="db-diagram/schema-current.json"
if [ ! -f "$previous" ]; then
echo "No previous schema snapshot found"
return 1
fi
echo "=== Schema Changes Detected ==="
# Compare tables
echo "New tables:"
diff <(jq -r '.models[].name' "$previous" | sort) \
<(jq -r '.models[].name' "$current" | sort) | \
grep "^>" | sed 's/^> / + /'
echo "Removed tables:"
diff <(jq -r '.models[].name' "$previous" | sort) \
<(jq -r '.models[].name' "$current" | sort) | \
grep "^<" | sed 's/^< / - /'
# Compare fields within tables
echo "Modified tables:"
# [Field comparison logic]
# Generate migration summary
cat > db-diagram/migration-summary.md <<EOFcompare_schemas() {
local previous="db-diagram/schema-snapshot.json"
local current="db-diagram/schema-current.json"
if [ ! -f "$previous" ]; then
echo "No previous schema snapshot found"
return 1
fi
echo "=== Schema Changes Detected ==="
# Compare tables
echo "New tables:"
diff <(jq -r '.models[].name' "$previous" | sort) \\
<(jq -r '.models[].name' "$current" | sort) | \\
grep "^>" | sed 's/^> / + /'
echo "Removed tables:"
diff <(jq -r '.models[].name' "$previous" | sort) \\
<(jq -r '.models[].name' "$current" | sort) | \\
grep "^<" | sed 's/^< / - /'
# Compare fields within tables
echo "Modified tables:"
# [Field comparison logic]
# Generate migration summary
cat > db-diagram/migration-summary.md <<EOFSchema Migration Summary
Schema Migration Summary
Date: $(date +"%Y-%m-%d %H:%M:%S")
Date: $(date +"%Y-%m-%d %H:%M:%S")
Changes
Changes
Added Tables
Added Tables
- [List new tables]
- [List new tables]
Modified Tables
Modified Tables
- [List modified tables with field changes]
- [List modified tables with field changes]
Removed Tables
Removed Tables
- [List removed tables]
- [List removed tables]
Impact Analysis
Impact Analysis
- Breaking Changes: [Yes/No]
- Migration Required: [Yes/No]
- Data Migration: [Yes/No]
- Breaking Changes: [Yes/No]
- Migration Required: [Yes/No]
- Data Migration: [Yes/No]
Recommended Actions
Recommended Actions
- Review changes
- Create migration script
- Update API contracts
- Update documentation EOF }
undefined- Review changes
- Create migration script
- Update API contracts
- Update documentation EOF }
undefinedPhase 7: Integration with Schema Validation
阶段7:与Schema验证集成
Integration with /schema-validate:
When schema changes detected:
→ Automatically suggest /schema-validate
→ Validate foreign key integrity
→ Check for orphaned records
→ Verify constraint compliance与/schema-validate集成:
当检测到Schema变化时:
→ 自动建议使用/schema-validate
→ 验证外键完整性
→ 检查孤立记录
→ 验证约束合规性Context Continuity
上下文连续性
Session Resume:
When you return and run or :
/db-diagram/db-diagram update- Check for schema changes since last generation
- Show diff if schema evolved
- Regenerate diagrams with updates
- Update documentation
Progress Example:
DATABASE DIAGRAM GENERATION
═══════════════════════════════════════════════════
Schema: Prisma (prisma/schema.prisma)
Last generated: 3 hours ago
Schema Status:
├── Tables: 6 (unchanged)
├── Relationships: 8 (unchanged)
├── Migrations: 2 new since last diagram
Changes Detected:
├── ✓ Added index on posts.publishedAt
└── ✓ Modified users.email (added validation)
Generating updated diagrams...
├── Mermaid: db-diagram/diagrams/schema.mmd
├── PlantUML: db-diagram/diagrams/schema.puml
└── DBML: db-diagram/diagrams/schema.dbml
Documentation updated: db-diagram/README.md会话恢复:
当您返回并运行或时:
/db-diagram/db-diagram update- 检查自上次生成以来的Schema变化
- 如果Schema演进则显示差异
- 重新生成包含更新的图
- 更新文档
进度示例:
DATABASE DIAGRAM GENERATION
═══════════════════════════════════════════════════
Schema: Prisma (prisma/schema.prisma)
Last generated: 3 hours ago
Schema Status:
├── Tables: 6 (unchanged)
├── Relationships: 8 (unchanged)
├── Migrations: 2 new since last diagram
Changes Detected:
├── ✓ Added index on posts.publishedAt
└── ✓ Modified users.email (added validation)
Generating updated diagrams...
├── Mermaid: db-diagram/diagrams/schema.mmd
├── PlantUML: db-diagram/diagrams/schema.puml
└── DBML: db-diagram/diagrams/schema.dbml
Documentation updated: db-diagram/README.mdPractical Examples
实用示例
Generate Diagrams:
/db-diagram # Auto-detect and generate
/db-diagram mermaid # Generate Mermaid format
/db-diagram prisma/schema.prisma # Specific schema file
/db-diagram all # All formatsUpdate & Compare:
/db-diagram update # Regenerate with changes
/db-diagram compare # Compare with previous version
/db-diagram export svg # Export as image生成图:
/db-diagram # 自动检测并生成
/db-diagram mermaid # 生成Mermaid格式
/db-diagram prisma/schema.prisma # 指定Schema文件
/db-diagram all # 生成所有格式更新与比较:
/db-diagram update # 重新生成包含变更的图
/db-diagram compare # 与之前版本比较
/db-diagram export svg # 导出为图片格式Safety Guarantees
安全保障
Protection Measures:
- Read-only schema analysis
- No database modifications
- Version controlled diagrams
- Schema snapshot preservation
Important: I will NEVER:
- Modify database schema
- Execute migrations
- Connect to production databases
- Delete schema files
保护措施:
- 只读Schema分析
- 不修改数据库
- 图支持版本控制
- 保留Schema快照
重要提示: 我绝不会:
- 修改数据库Schema
- 执行迁移
- 连接到生产数据库
- 删除Schema文件
Skill Integration
技能集成
Perfect complement to database workflows:
- - Validate after diagram generation
/schema-validate - - Create migrations from schema
/migration-generate - - Include diagrams in documentation
/docs - - Link schema to API docs
/api-docs-generate
完美适配数据库工作流:
- - 图生成后验证Schema
/schema-validate - - 从Schema创建迁移脚本
/migration-generate - - 在文档中包含图
/docs - - 关联Schema与API文档
/api-docs-generate
Token Budget Optimization
Token预算优化
To stay within 2,500-4,000 token budget:
- Focus on diagram generation logic
- Provide one detailed example per format
- Use file outputs for documentation
- Defer ORM-specific parsing to external tools when available
- Compact relationship notation
为了控制在2500-4000个Token的预算内:
- 专注于图生成逻辑
- 每种格式提供一个详细示例
- 使用文件输出存储文档
- 当可用时,将ORM特定解析委托给外部工具
- 使用紧凑的关系表示法
What I'll Actually Do
我实际会执行的操作
- Detect ORM - Auto-identify schema format (Prisma/TypeORM/SQLAlchemy/Django)
- Parse schema - Extract tables, fields, relationships, constraints
- Generate diagrams - Mermaid (default), PlantUML, DBML as requested
- Document relationships - Clear documentation of all relationships
- Track evolution - Compare with previous versions
- Export formats - Multiple output formats for different use cases
- Integrate validation - Suggest schema validation when appropriate
I'll help you visualize and document your database schema for better understanding and team collaboration.
Credits:
- Prisma schema documentation
- TypeORM entity relationship patterns
- SQLAlchemy ORM relationship types
- Django model relationship documentation
- Mermaid ER diagram syntax
- PlantUML database diagrams
- DBML specification from dbdiagram.io
- Database design best practices
- 检测ORM - 自动识别Schema格式(Prisma/TypeORM/SQLAlchemy/Django)
- 解析Schema - 提取表、字段、关系、约束
- 生成图 - 默认生成Mermaid格式,按需生成PlantUML、DBML格式
- 记录关系 - 清晰记录所有关系
- 跟踪演进 - 与之前版本比较
- 导出格式 - 多种输出格式以适配不同使用场景
- 集成验证 - 适当时建议进行Schema验证
我将帮助您可视化并记录数据库Schema,以提升理解与团队协作效率。
致谢:
- Prisma Schema文档
- TypeORM实体关系模式
- SQLAlchemy ORM关系类型
- Django模型关系文档
- Mermaid ER图语法
- PlantUML数据库图
- dbdiagram.io提供的DBML规范
- 数据库设计最佳实践 ",