Development 5 min read

By ToolByte Team · Published

Diagrams as Code: Using Mermaid and SQL-Generated ER Diagrams for Documentation That Stays Current

Diagrams as Code: Using Mermaid and SQL-Generated ER Diagrams for Documentation That Stays Current
mermaid er diagram documentation database design markdown

Every team has a folder of architecture diagrams that were accurate the week they were drawn. The drawing tool needed a licence, the file was on someone's laptop, and the one time somebody tried to update it they gave up and drew a new one on a whiteboard.

Diagrams as code fixes the maintenance problem by making the diagram a text file. It lives in the repository next to the code it describes, it diffs in pull requests, and anyone can edit it with the editor they already have. Mermaid is the most widely supported syntax, rendered natively by GitHub, GitLab, Notion, Obsidian and most documentation generators.

Key takeaways

  • Text diagrams are reviewable, versionable and cheap to update. That is what keeps them accurate.
  • Mermaid covers the diagrams software teams actually draw: flowcharts, sequence diagrams, class diagrams, ER diagrams, state machines, Gantt charts and pie charts.
  • For database documentation, do not draw the ER diagram by hand. Generate it from the schema so it cannot disagree with the database.
  • Keep diagrams small. A diagram with forty boxes communicates nothing; split it.

Mermaid in five minutes

A Mermaid diagram is a code block. In Markdown:

```mermaid
flowchart LR
  A[Upload file] --> B{Valid?}
  B -- yes --> C[Process]
  B -- no --> D[Show error]
  C --> E[Download]
```

That renders as a left-to-right flowchart with a decision diamond. The syntax is readable without the rendering, which is the point: a reviewer can understand a change to the diagram from the diff alone.

Paste any of the examples below into the Mermaid Diagram Viewer to see them rendered, edit live, and export.

Flowcharts: processes and decisions

flowchart TD
  Start([Request received]) --> Auth{Authenticated?}
  Auth -- no --> Deny[401 Unauthorized]
  Auth -- yes --> Rate{Under rate limit?}
  Rate -- no --> Throttle[429 Too Many Requests]
  Rate -- yes --> Handle[Run handler]
  Handle --> Done([Response])

TD is top-down, LR is left-right. Shapes: [ ] rectangle, { } diamond, ([ ]) rounded, (( )) circle. Use flowcharts for request pipelines, deployment steps and anything with branches.

Sequence diagrams: who calls whom

sequenceDiagram
  participant B as Browser
  participant A as API
  participant Q as Queue
  participant W as Worker
  B->>A: POST /pdf-tools/compress
  A->>Q: enqueue job
  A-->>B: 202 Accepted + job id
  B->>A: GET /status/{id} (poll)
  W->>Q: dequeue
  W->>W: compress
  W-->>A: result stored
  A-->>B: 200 {download_url}

Solid arrows are calls, dashed arrows are responses. Sequence diagrams are the best way to explain an asynchronous flow or an authentication handshake; a paragraph of prose cannot show that the browser polls while the worker runs.

Entity-relationship diagrams: data models

erDiagram
  USER ||--o{ ORDER : places
  ORDER ||--|{ ORDER_LINE : contains
  PRODUCT ||--o{ ORDER_LINE : "appears in"
  USER {
    int id PK
    string email
    datetime created_at
  }
  ORDER {
    int id PK
    int user_id FK
    decimal total
  }

The crow's-foot notation reads as: || exactly one, o{ zero or more, |{ one or more. A user places zero or more orders; an order contains one or more lines.

State diagrams and the rest

stateDiagram-v2 for lifecycle states (draft, published, archived), classDiagram for object models, gantt for timelines, pie for proportions. The same editor renders all of them.

Generating ER diagrams from the real schema

Hand-written erDiagram blocks have the same problem as drawn diagrams: they drift. The fix is to derive the diagram from the schema itself.

The Database Diagram Generator takes SQL CREATE TABLE statements and draws the ER diagram, with foreign keys turned into relationships. Workflow:

  1. Dump the schema. mysqldump --no-data mydb, pg_dump --schema-only mydb, or .schema in SQLite.
  2. Paste the CREATE TABLE statements into the generator.
  3. Export as PNG or SVG for documents and slides, or as Mermaid so it can live in your Markdown and be rendered by GitHub.

Because the input is the schema, the diagram is correct by construction. Re-run it after each migration and commit the result alongside the migration.

Two practical notes. Foreign keys must be declared (FOREIGN KEY (user_id) REFERENCES users(id)) for relationships to appear; a convention-only user_id column without a constraint is just a column. And for a schema with eighty tables, paste a subset. The orders subsystem on one diagram and the billing subsystem on another is far more useful than one unreadable poster.

Writing docs around the diagrams

A diagram without words is a puzzle. The pattern that works: one or two sentences saying what the reader should notice, then the diagram, then the exceptions.

Compression runs asynchronously because large PDFs can take over a minute. The browser polls for status; nothing blocks on the worker.

(sequence diagram here)

If the job fails, the status endpoint returns the error and the browser offers a retry.

Write it in Markdown, preview it in the Markdown Editor, and commit it. If the documentation is being moved from HTML (a wiki export, for example), the HTML to Markdown converter gets you most of the way.

Keeping diagrams small

Rules we apply:

  • One idea per diagram. The request pipeline, or the data model, or the deployment topology. Not all three.
  • Under fifteen nodes. Past that, split into an overview plus detail diagrams.
  • Name the diagram by the question it answers. "How does a file upload get processed?" is a better title than "Architecture".
  • Delete diagrams nobody updates. An outdated diagram is worse than none; it is confidently wrong.

Frequently asked questions

Where can Mermaid diagrams be rendered?

GitHub and GitLab render them in Markdown files, issues and pull requests. Notion, Obsidian, Confluence (with a plugin), Docusaurus, MkDocs and most static site generators support them. For anything else, export SVG or PNG from the viewer.

Can I export a diagram as an image?

Yes. The Mermaid viewer and the database diagram generator both export PNG and SVG. Use SVG in documents and slides so it stays sharp when scaled.

Does the ER diagram generator connect to my database?

No. It parses CREATE TABLE statements you paste in. Nothing connects to your database and no credentials are involved. Dump the schema locally and paste the text.

Which SQL dialects work?

Standard CREATE TABLE syntax from MySQL, PostgreSQL and SQLite parses. Vendor-specific extras (storage engines, tablespaces) are ignored. If a table does not appear, simplify its statement to columns and keys and try again.

Tools used in this guide

More from the blog