neilotoole.io

Web presence of Neil O'Toole.

sq inspect: visual edition

As of v0.53.0, sq inspect can output entity relationship diagrams (ERDs), as Mermaid, HTML, or Markdown. Behold:

sq inspect HTML output for the Sakila Postgres database

See the live page for the full thing: the whole Sakila schema, with per-table details for columns, keys, constraints and indexes. Click the diagram to zoom and pan.

That page is the output of a single command:

$ sq inspect --html @sakila/local/pg > sakila_pg.html

There are three formats. --html produces a standalone web page. --markdown produces the same document as Markdown, with the ERD in a mermaid code block that GitHub and GitLab render inline. And -f mermaid-erd produces just the diagram source.

What to do with it

The docs are generated from the live database, so they’re always current, and nobody has to maintain them by hand. A few ideas:

Publish a daily schema page. Regenerate the HTML every morning via cron, and post it to an internal wiki or web server. Add --format.html.embed-assets to inline Mermaid.js, so the page is a single self-contained file that doesn’t depend on a CDN:

# crontab: refresh the schema page at 7am daily
0 7 * * * sq inspect --html --format.html.embed-assets @sakila/prod -o /var/www/schema/sakila.html

Track schema changes in git. The Mermaid ERD is plain text:

$ sq inspect @sakila/local/pg.film_actor -f mermaid-erd
erDiagram
    film_actor {
        int actor_id PK,FK
        int film_id PK,FK
        datetime last_update
    }
    actor ||--o{ film_actor : "film_actor_actor_id_fkey"
    film ||--o{ film_actor : "film_actor_film_id_fkey"

Commit the ERD for the whole database next to your migrations, and regenerate it when the schema changes. Each column and relationship is its own line, so a schema change shows up in code review as a readable diff.

$ sq inspect @sakila/local/pg -f mermaid-erd -o docs/schema.mmd

Explain a change. Paste a table’s ERD into a PR or issue, to show the relationships you’re touching.

See the inspect docs for the details.