Visualise Persist Models Using Graphviz

No Comments Written by Etienne Laurin on 2011/09/14 in Code.

My current project uses the Yesod framework for web development. One of the advantages of Yesod is the Database.Persist library. It has type-checked queries, custom sql representations for types and automatic schema migration with postgresql, sqlite and mongodb support.

Here is a little script I wrote to visualise Persist data models.

persist-graph.hs

{-# LANGUAGE UnicodeSyntax, ViewPatterns #-}

-- usage:
--  persistent-graph < config/models > schema.dot
--  neato schema.dot -Tpdf > schema.pdf

import Database.Persist.Base (EntityDef(..), ColumnDef(..))
import Database.Persist.Quasi (parse)
import Data.List (intersperse)

main = do
  defs  getContents
  let schema = parse defs
  putStr $ convert schema

graphOpts = "node [shape=record]; overlap=false; splines=true;"

convert schema = unlines ["digraph {", graphOpts, unlines $ map entity schema, "}"] 

entity (EntityDef name _ cols _ _) = unlines $ [
  name ++ " [",
  "label=\"{" ++ name  ++ "|" ++
  (concat $ intersperse "|" (map column cols))
  ++ "}\"];"] ++
  map (links name) cols

column (ColumnDef name _ _) = "<" ++ name ++ "> " ++ name

links entity (ColumnDef name typ _) =
  if "dI" == take 2 (reverse typ)
  then entity ++ ":" ++ name ++ " -> " ++ reverse (drop 2 (reverse typ))
  else []

Leave a Comment

Would you like to Login to Your Account?


Comments on "Visualise Persist Models Using Graphviz"

Sorry, but it seems like there aren't any comments.