erd

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2026 License: MIT Imports: 4 Imported by: 0

README

erd

CI Status codecov Go Report Card CodeQL Go Reference License Go Version Release

Go package for generating Entity Relationship Diagrams from domain models.

Domain as Diagram

Your Go structs already define your domain. ERD extracts that structure and renders it as visual documentation that stays in sync with your code.

type User struct {
    ID      string   `erd:"pk"`
    Profile *Profile              // one-to-one
    Orders  []Order               // one-to-many
}

The relationships live in your types. ERD makes them visible.

Installation

go get github.com/zoobz-io/erd

Example

Define your domain models with erd struct tags:

package main

import (
    "fmt"

    "github.com/zoobz-io/erd"
    "github.com/zoobz-io/sentinel"
)

type User struct {
    ID      string   `erd:"pk"`
    Email   string   `erd:"uk"`
    Name    string
    Profile *Profile
    Orders  []Order
}

type Profile struct {
    ID     string  `erd:"pk"`
    Bio    *string
    Avatar *string `erd:"note:Profile picture URL"`
}

type Order struct {
    ID     string  `erd:"pk"`
    UserID string  `erd:"fk"`
    Total  float64
    Status string
}

func main() {
    // Scan types to extract metadata
    sentinel.Scan[User]()

    // Generate ERD from schema
    diagram := erd.FromSchema("User Domain", sentinel.Schema())

    // Output as Mermaid
    fmt.Println(diagram.ToMermaid())
}

This produces the following diagram:

erDiagram
    Order {
        string ID PK
        string UserID FK
        float64 Total
        string Status
    }
    Profile {
        string ID PK
        string Bio "nullable"
        string Avatar "nullable, Profile picture URL"
    }
    User {
        string ID PK
        string Email UK
        string Name
    }
    User ||--|| Profile : Profile
    User ||--o{ Order : Orders

Struct Tags

The erd tag supports:

Tag Description
pk Primary key
fk Foreign key
uk Unique key
note:... Attribute note

Tags can be combined: erd:"pk,note:Auto-generated UUID"

Relationships

Relationships are inferred from struct fields:

Field Type Cardinality
*T (pointer) One-to-one
[]T (slice) One-to-many
T (embedded) One-to-one
map[K]V Many-to-many

Output Formats

Mermaid
mermaid := diagram.ToMermaid()
GraphViz DOT
dot := diagram.ToDOT()

Manual Construction

For cases where you need more control:

diagram := erd.NewDiagram("E-commerce").
    WithDescription("Shopping cart domain model")

product := erd.NewEntity("Product").
    AddAttribute(erd.NewAttribute("ID", "string").WithPrimaryKey()).
    AddAttribute(erd.NewAttribute("Name", "string")).
    AddAttribute(erd.NewAttribute("Price", "float64"))

cart := erd.NewEntity("Cart").
    AddAttribute(erd.NewAttribute("ID", "string").WithPrimaryKey()).
    AddAttribute(erd.NewAttribute("UserID", "string").WithForeignKey())

diagram.
    AddEntity(product).
    AddEntity(cart).
    AddRelationship(erd.NewRelationship("Cart", "Product", "Items", erd.ManyToMany))

Validation

errors := diagram.Validate()
for _, err := range errors {
    fmt.Println(err.Error())
}

Why erd?

  • Type-driven: Relationships inferred from Go types, not annotations
  • Two modes: Automatic via sentinel, or manual builder API
  • Multiple formats: Mermaid for browsers, DOT for print-quality output
  • Zero config: Works out of the box with standard Go structs
  • Validation: Catches structural errors before rendering

Documentation

  • API Reference - Complete API documentation
  • Sentinel - Type scanning library used for automatic extraction

Contributing

Contributions welcome. See CONTRIBUTING.md for development setup and guidelines.

License

MIT

Documentation

Overview

Package erd generates Entity Relationship Diagrams from Go domain models.

The package provides two approaches for generating ERD diagrams:

Automatic Generation (via Sentinel)

Use FromSchema to automatically generate diagrams from Go types scanned by the sentinel package:

sentinel.Scan[User]()
diagram := erd.FromSchema("My Domain", sentinel.Schema())
fmt.Println(diagram.ToMermaid())

Manual Construction (via Builder)

Use NewDiagram, NewEntity, NewAttribute, and NewRelationship to construct diagrams programmatically:

diagram := erd.NewDiagram("E-commerce").
    AddEntity(erd.NewEntity("Product").
        AddAttribute(erd.NewAttribute("ID", "string").WithPrimaryKey())).
    AddRelationship(erd.NewRelationship("Cart", "Product", "Items", erd.ManyToMany))

Output Formats

Diagrams can be rendered to multiple formats:

Struct Tags

When using automatic generation, the erd struct tag controls attribute metadata:

  • pk: Primary key
  • fk: Foreign key
  • uk: Unique key
  • note:...: Attribute annotation

Tags can be combined: `erd:"pk,note:Auto-generated UUID"`

Validation

Use Diagram.Validate to check diagram structural validity before rendering.

Package erd provides types and functions for generating Entity Relationship Diagrams.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attribute

type Attribute struct {
	Key      *KeyType
	Note     *string
	Name     string
	Type     string
	Nullable bool
}

Attribute represents a field/property of an entity.

func NewAttribute

func NewAttribute(name, attrType string) *Attribute

NewAttribute creates a new attribute.

func (*Attribute) Validate

func (a *Attribute) Validate() []ValidationError

Validate checks the attribute for structural validity.

func (*Attribute) WithForeignKey

func (a *Attribute) WithForeignKey() *Attribute

WithForeignKey marks the attribute as a foreign key.

func (*Attribute) WithKey

func (a *Attribute) WithKey(keyType KeyType) *Attribute

WithKey marks the attribute with a key type.

func (*Attribute) WithNote

func (a *Attribute) WithNote(note string) *Attribute

WithNote adds a note to the attribute.

func (*Attribute) WithNullable

func (a *Attribute) WithNullable() *Attribute

WithNullable marks the attribute as nullable.

func (*Attribute) WithPrimaryKey

func (a *Attribute) WithPrimaryKey() *Attribute

WithPrimaryKey marks the attribute as a primary key.

func (*Attribute) WithUnique

func (a *Attribute) WithUnique() *Attribute

WithUnique marks the attribute as unique.

type Cardinality

type Cardinality string

Cardinality represents the type of relationship between entities.

const (
	OneToOne   Cardinality = "one-to-one"
	OneToMany  Cardinality = "one-to-many"
	ManyToOne  Cardinality = "many-to-one"
	ManyToMany Cardinality = "many-to-many"
)

Cardinality constants.

type Diagram

type Diagram struct {
	Title         string
	Description   *string
	Entities      map[string]*Entity
	Relationships []*Relationship
}

Diagram represents an Entity Relationship Diagram.

func FromSchema

func FromSchema(title string, schema map[string]sentinel.Metadata) *Diagram

FromSchema converts a sentinel schema to an ERD diagram. The schema is typically obtained via sentinel.Schema() after scanning types.

func NewDiagram

func NewDiagram(title string) *Diagram

NewDiagram creates a new ERD diagram.

func (*Diagram) AddEntity

func (d *Diagram) AddEntity(entity *Entity) *Diagram

AddEntity adds an entity to the diagram.

func (*Diagram) AddRelationship

func (d *Diagram) AddRelationship(rel *Relationship) *Diagram

AddRelationship adds a relationship to the diagram.

func (*Diagram) ToDOT

func (d *Diagram) ToDOT() string

ToDOT generates a GraphViz DOT diagram from the diagram structure.

func (*Diagram) ToMermaid

func (d *Diagram) ToMermaid() string

ToMermaid generates a Mermaid ERD diagram from the diagram structure.

func (*Diagram) Validate

func (d *Diagram) Validate() []ValidationError

Validate checks the diagram for structural validity.

func (*Diagram) WithDescription

func (d *Diagram) WithDescription(description string) *Diagram

WithDescription sets the description for the diagram.

type Entity

type Entity struct {
	Package    *string
	Note       *string
	Name       string
	Attributes []*Attribute
}

Entity represents a domain model entity (typically a Go struct).

func FromMetadata

func FromMetadata(meta sentinel.Metadata) *Entity

FromMetadata converts a single sentinel Metadata to an ERD Entity.

func NewEntity

func NewEntity(name string) *Entity

NewEntity creates a new entity.

func (*Entity) AddAttribute

func (e *Entity) AddAttribute(attr *Attribute) *Entity

AddAttribute adds an attribute to the entity.

func (*Entity) Validate

func (e *Entity) Validate() []ValidationError

Validate checks the entity for structural validity.

func (*Entity) WithNote

func (e *Entity) WithNote(note string) *Entity

WithNote adds a note to the entity.

func (*Entity) WithPackage

func (e *Entity) WithPackage(pkg string) *Entity

WithPackage sets the package name for the entity.

type KeyType

type KeyType string

KeyType represents the key constraint on an attribute.

const (
	PrimaryKey KeyType = "PK"
	ForeignKey KeyType = "FK"
	UniqueKey  KeyType = "UK"
)

Key type constants.

type Relationship

type Relationship struct {
	Label       *string
	Note        *string
	From        string
	To          string
	Field       string
	Cardinality Cardinality
}

Relationship represents a relationship between entities.

func NewRelationship

func NewRelationship(from, to, field string, cardinality Cardinality) *Relationship

NewRelationship creates a new relationship.

func (*Relationship) ValidateAgainst

func (r *Relationship) ValidateAgainst(entities map[string]*Entity) []ValidationError

ValidateAgainst checks the relationship references valid entities.

func (*Relationship) WithLabel

func (r *Relationship) WithLabel(label string) *Relationship

WithLabel sets a label for the relationship.

func (*Relationship) WithNote

func (r *Relationship) WithNote(note string) *Relationship

WithNote adds a note to the relationship.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error.

func (ValidationError) Error

func (e ValidationError) Error() string

Error implements the error interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL