ER Diagram Generation
Relevant source files
The following files were used as context for generating this wiki page:
ER Diagram Generation in SeaORM is a specialized functionality within the sea-orm-codegen crate designed to provide visual representations of database schemas. It leverages the Mermaid diagramming language to generate text-based Entity Relationship (ER) diagrams directly from entity definitions. This allows developers to visualize complex relationships, including 1-1, 1-N, M-N, and self-referential links, which are central to the SeaORM ecosystem.
The core logic resides in the EntityWriter implementation, which iterates through identified entities, their columns, and their relational metadata to construct a valid Mermaid erDiagram string. This feature is particularly useful in the "Entity-First Workflow," where schema definitions are maintained in Rust code and can be exported as visual documentation or used to verify database structures.
Sources: sea-orm-codegen/src/entity/writer/mermaid.rs:1-12, CLAUDE.md:120-125, README.md:15-20
Architecture and Logic
The generation process is encapsulated within the generate_er_diagram method of EntityWriter. The logic follows a structured multi-pass approach to ensure all components of a standard ER diagram—entities, attributes, and relationships—are correctly mapped from the internal Entity representations.
Generation Flow
- Header Initialization: The output string is initialized with the
erDiagramdirective. - Metadata Pre-processing: The system scans all entities to create sets of Primary Keys (PKs) and Foreign Keys (FKs) to be used as attribute markers.
- Entity Block Writing: Each entity is converted into a Mermaid block containing its table name and a list of columns with their types and constraints (PK, FK, UK).
- Relationship Mapping: The system iterates through relations and conjunct (many-to-many) relations to draw connections between entity blocks.
The diagram shows the logical progression of the ER diagram generation algorithm.
Sources: sea-orm-codegen/src/entity/writer/mermaid.rs:12-42
Component Mapping
SeaORM maps internal Rust data structures and SQL types to specific Mermaid ER diagram syntax.
Column Constraints
Constraints are determined by checking if a column exists in the pre-processed PK/FK sets or if the column definition includes a unique flag.
| Constraint | Logic | Mermaid Label |
|---|---|---|
| Primary Key | pks.contains(col.name) | PK |
| Foreign Key | fks.contains(col.name) | FK |
| Unique Key | col.unique or col.unique_key.is_some() | UK |
| Composite | Combination of above (e.g., PK and FK) | PK,FK |
Sources: sea-orm-codegen/src/entity/writer/mermaid.rs:52-66
Type Mapping
Internal ColumnType variants are converted to standard SQL-like strings for the diagram.
| SeaORM ColumnType | Mermaid Display Type |
|---|---|
Integer | int |
String(n) | varchar |
Text | text |
Boolean | bool |
Json / JsonBinary | json |
DateTime / Timestamp | datetime / timestamp |
Sources: sea-orm-codegen/src/entity/writer/mermaid.rs:104-142
Relationship Representation
The generate_er_diagram logic distinguishes between direct relations (defined in the relations vector) and junction-based relations (defined in conjunct_relations).
Relation Cardinality
- BelongsTo: Represented as
}o--||. This indicates a "many-to-one" relationship where the current entity holds a foreign key to a single record in the referenced table. - Many-to-Many (Conjunct): Represented as
}o--o{. These relations utilize a junction table (indicated by theviafield). The generator automatically deduplicates these to ensure a single line connects the two primary entities in the diagram.
Visual representation of how SeaORM conceptualizes Many-to-Many relations vs the underlying schema.
Sources: sea-orm-codegen/src/entity/writer/mermaid.rs:77-98, sea-orm-codegen/src/entity/writer.rs:434-456
CLI Usage
ER diagram generation is triggered via the sea-orm-cli tool. The --er-diagram flag instructs the codegen to produce the Mermaid output.
# Example command to generate entities with an ER diagram
sea-orm-cli generate entity \
-o tests/common/sakila \
--entity-format dense \
--er-diagram
Sources: tests/common/sakila/NOTES.md:1-5, sea-orm-sync/tests/common/sakila/NOTES.md:1-5
Technical Implementation Snippets
The following snippet demonstrates the core logic for identifying foreign keys for the ER diagram:
// sea-orm-codegen/src/entity/writer/mermaid.rs:21-31
let fk_sets: Vec<HashSet<&str>> = self
.entities
.iter()
.map(|e| {
e.relations
.iter()
.filter(|r| matches!(r.rel_type, RelationType::BelongsTo))
.flat_map(|r| r.columns.iter().map(String::as_str))
.collect()
})
.collect();
Sources: sea-orm-codegen/src/entity/writer/mermaid.rs:21-31
Conclusion
ER Diagram Generation in SeaORM serves as a bridge between the "Entity-First" development style and visual database documentation. By converting internal relational metadata into Mermaid syntax, it enables automated, up-to-date visualization of the data model, including complex many-to-many associations and composite keys. This feature is integrated directly into the codegen pipeline, making it accessible through standard CLI workflows.
Sources: sea-orm-codegen/src/entity/writer/mermaid.rs:163-278, README.md:100-110