While doing some Ruby on Rails code refactoring, I realized I’d like to visualize the database schema of the application.
An easy possibility is to print out db/schema.rb. This seems a bit too linear and little visual to me. OK, I’d better keep thinking.
An enterprise approach would be to take a CASE machinery and feed it with the create DB scripts. That is solid and reliable, but a kind of overkill. What’s more, a Rails app with convention over configuration can do well without foreign keys and so it usually does. This means that relations between tables are mostly implied by column names rather than explicitly declared as DB constraints. Thus, hardly any CASE tool can derive such relations from a DB schema.
OK, let’s try to go the Rails way and put together existing ingredients, add a little cream and see what we can get:
- there are many UML modeling tools out there, although few of the free ones can reverse-engineer a DB schema
- there’s the SchemaDumper in ActiveRecord, which generates the schema.rb based on DB reflection
- there’s this standard XMI format for data interchange between modeling tools
OK, so let’s try and tweak the SchemaDumper to generate XMI, then import it into a UML modeling tool and get the schema diagram from there.
So, I morphed SchemaDumper into UmlDumper, which generates XMI in the widely adopted Rose flavor. E.g. a Typo blog database will result in schema.xml like this:
Then I import this XMI into a UML tool – StarUML in my case – to get the basic picture. Yellow boxes are DB tables, grey boxes are presumed “virtual” tables referenced by columns in other tables.
I play a little with the layout and incorporate the “virtual” tables into the hierarchy. For completeness, I also add a few model classes, which show up only in Rails code, not in the database (manual entries in blue color):
I export the diagram from the tool to print it, share it and enjoy.
Now, that’s it! The approach is quite universal (not yet true for UmlDumper), I can quickly reuse it in my further Rails projects, and so can you.
Note: for one-time use I created a rake task.
namespace :uml do desc "Generate an XMI db/schema.xml file describing the current DB as seen by AR. Produces XMI 1.1 for UML 1.3 Rose Extended, viewable e.g. by StarUML" task :schema => :environment do require 'lib/uml_dumper.rb' File.open("db/schema.xml", "w") do |file| ActiveRecord::UmlDumper.dump(ActiveRecord::Base.connection, file) end puts "Done. Schema XMI created as db/schema.xml." end end
For frequent use (fine-tuning the export), it is better to start the Rails console and call UmlDumper from there to avoid re-loading the whole Rails stack all over again.