Mermaid Entity-Relationship diagram in top-down layout

350 Views Asked by At

Consider the following mermaid diagram:

erDiagram
  CLIENT {}
  ACCOUNT {}
  PRODUCT {}
  ADDRESS {}
  INVESTMENT {}
  REPORT {}

  
  CLIENT ||--o{ ACCOUNT : account_fkey
  CLIENT ||--o{ PRODUCT : product_fkey
  CLIENT ||--o{ ADDRESS : address_fkey
  CLIENT ||--o{ INVESTMENT : investment_fkey
  CLIENT ||--o{ REPORT : report_fkey

Mermaid compiles this syntax into a "left-right" layout (apparently the default):

enter image description here

It is easy to see how this layout may rapidly become unusable, both in web pages as well as in documents. With other types of diagrams it is possible to set the layout to "top-down" by appending the characters TD to the diagram type identifier. For the diagram above this would be:

erDiagram TD 
  CLIENT {}
  ACCOUNT {}
  PRODUCT {}
  ADDRESS {}
  INVESTMENT {}
  REPORT {}

  
  CLIENT ||--o{ ACCOUNT : account_fkey
  CLIENT ||--o{ PRODUCT : product_fkey
  CLIENT ||--o{ ADDRESS : address_fkey
  CLIENT ||--o{ INVESTMENT : investment_fkey
  CLIENT ||--o{ REPORT : report_fkey

However, mermaid instead interprets the layout instruction as an additional entity in the diagram:

enter image description here

Then, how can the layout be set in a mermaid ER diagram?

1

There are 1 best solutions below

0
On

Mermaid has little positioning feature in its ERD diagram, unlike plantUML, which allows you not only to set a general direction but also explicitly for each relationship give an individual direction.

The Mermaid syntax is defined for each diagram, and the TD RL are only foreseen as (mandatory) parameter for flowchart. By the way, most flowcharts tend to be rather linear, so the hint of the direction helps Mermaid to position new nodes downstream of the flow in a rather consistent way.

For ERD, it is less obvious as many ERD are rather networks/meshes where a simple direction is not sufficient for an intelligent positioning. Therefore Mermaid relies on its own -rather rigid- algorithm: it seems to identify the depth of the relationships (e.g. the largest number of elements connected as a chain) positioning the entities of this chain according to vertical levels, and expanding horizontally along these levels. The vertical level is governed by the direct or indirect relationships to the elements of the largest chain, their order of occurrence, and starting a top level if some new element is unconnected to other elements already positioned.

I do not pretend to reverse engineer the positioning algorithm from Mermaid; such algorithm can be rather complex (e.g. look at force-field graph visualisation or the spanning tree algorithm). But the point is, that it's rather rigid and the syntax does not allows to interfere.