Dienstag, 17. Februar 2015

How to generate a database schema report with Maven and Schemaspy

Lately I wanted to setup a continuously generated schema diagram on the database layout for a project. I finally managed to achieve this with SchemaSpy and Maven.
Below you find the relevant parts from my pom. I bound the report generation to the "site" phase. The tricky thing is that SchemaSpy requires the database driver library as a parameter. I extracted it from the build classpath into a property, see below.

    
<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>eckstein</groupId>
  <artifactId>test</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <reporting>
    <plugins>
      <plugin>
        <groupId>com.wakaleo.schemaspy</groupId>
        <artifactId>maven-schemaspy-plugin</artifactId>
        <configuration>
          <databaseType>mysql</databaseType>
          <database>${db.name}</database>
          <host>${db.host}</host>
          <user>${db.username}</user>
          <password>${db.password}</password>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.4</version>
        <configuration>
          <!-- disable all the default Maven reports -->
          <generateReports>false</generateReports>
        </configuration>
      </plugin>
    </plugins>
  </reporting>

  <pluginRepositories>
    <pluginRepository>
      <id>Wakaleo Repository</id>
      <url>http://www.wakaleo.com/maven/repos/</url>
    </pluginRepository>
  </pluginRepositories>
  
</project>

With the configuration above the reports get generated if you run this Maven command in the project:

mvn site -Ddb.name=<database-name> -Ddb.host=<mydatabase-host> \
         -Ddb.username=<user> -Ddb.password=<password>

The reports end up under target/site/schemaspy. Running it on your continuous build server enables you to have always an up-to-date report available. You can then link to it from your corporate Wiki or Blog.
 
To have the graphical diagrams generated Schemaspy requires Graphviz installed on the systems it runs on. If that's the case for a Linux installation you can check by testing for the dot command:
dot -?
If it's not there you should install it, e.g. for Ubuntu this way:
sudo apt-get install graphviz
The generated report looks like below. Images are generated as DOT files, but also exported to PNG which can then nicely get embedded into your online documentation!