A DuckDB macro that generates Mermaid Entity-Relationship diagrams from your database schema.
- https://gist.github.com/Bilbottom/e1d3d677d2479e0602132327703ff15d
- https://gist.github.com/michael-simons/bd89eaae2bc8ecdcc911c1b08268894b
INSTALL webmacro FROM community; LOAD webmacro;
SELECT load_macro_from_url('https://gist.github.com/lmangani/dc9ea2ba0a0b2a54a1330e7db868e0bc/raw/297bbabdb588b4917cf7a357194cc0558bfcb5e9/mermaid.sql');
Install the macro in your DuckDB
-- Create sample tables
CREATE TABLE users (
user_id INTEGER NOT NULL PRIMARY KEY,
username VARCHAR NOT NULL UNIQUE,
review_datetime TIMESTAMP,
UNIQUE (user_id, review_datetime)
);
CREATE TABLE events (
event_id INTEGER NOT NULL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(user_id),
event_datetime TIMESTAMP NOT NULL,
event_type VARCHAR NOT NULL
);
-- Generate and write ER diagram
COPY (
SELECT line
FROM generate_er_diagram('er-diagram.mermaid')
ORDER BY line_num
)
TO 'er-diagram.mermaid' (header false, quote '', delimiter E'\n');
-- Generate diagram for user-related tables only
COPY (
SELECT line
FROM generate_er_diagram('user-er.mermaid', 'user%')
ORDER BY line_num
)
TO 'user-er.mermaid' (header false, quote '', delimiter E'\n');
-- Use different relationship notation
COPY (
SELECT line
FROM generate_er_diagram('er-custom.mermaid', '%', '}o--o{')
ORDER BY line_num
)
TO 'er-custom.mermaid' (header false, quote '', delimiter E'\n');
output_path
: Name for the output file (used in generated content)table_pattern
: SQL LIKE pattern for filtering tables (default: '%')rel_style
: Mermaid relationship notation (default: '||--o{{')
||--o{{
: One-to-many (default)}}o--o{{
: Many-to-many||--||
: One-to-one}o--o{
: Many-to-many (alternative)
- Generates Mermaid-compatible ER diagrams
- Supports composite foreign keys
- Shows data types
- Table filtering using LIKE patterns
- Customizable relationship notation
- Includes column comments in relationships when available
- The macro returns a result set that must be written to a file using COPY
- Order by line_num to maintain correct diagram structure
- Table patterns use SQL LIKE syntax (e.g., 'user%' for all tables starting with "user")
- Relationship styles use Mermaid notation
For the sample tables above, the generated Mermaid diagram will look like:
erDiagram
events {integer event_id integer user_id timestamp event_datetime varchar event_type}
users {integer user_id varchar username timestamp review_datetime}
users }o--o{ events : "user_id"
MIT License - feel free to use in your own projects!