Auto-generate a Database Schema Diagram

Originally published at dev.to

When building a web application, I always create a URL endpoint that generates a database schema diagram on the fly.  This is a quick reference item that never gets old.

This approach can be used with any Perl web framework.  The provided example is for the Catalyst Framework using a DBIx::Class ORM.  This example provides the url http://mywebsite.com/dbdiagram

=head2 dbdiagram

Render an image representing the current data model

=cut

use SQL::Translator;
sub dbdiagram :Local :Args(0) {
    my ($self, $c) = @_;

    my $translator = SQL::Translator->new(
        parser => 'SQL::Translator::Parser::DBIx::Class',
        data   => $c->model('Ezn')->schema,
        producer => 'Diagram',
        producer_args => {
            output_type => 'png',
            title       => "My clever database diagram",
            add_color   => 1,
            font_size   => 'large',
        },
    ) or die SQL::Translator->error;

    $c->res->content_type('image/png');
    $c->res->body($translator->translate);
}

Don't Forget to restrict to authorized users!

See also: