Geert: “Geert’s an Enterprise Entity Relation Tracker” ;)

Find missing foreign keys in ActiveRecord and create a migration to add them.

If you want to do it to keep your DBA happy, or want to generate a nice ERD (see below), or you have a legitimate reason to add foreign keys later, this gem might be for you.

Usage

Go to your Rails application and type the command:

geert

And you’ll get the migration you need right in your console. To generate a migration, run:

geert --migration add_foreign_keys

Run “geert -h” for all possible options.

A note of caution

Foreign key constraints have a real impact on your application. Geert can’t always see the difference between the desired and unwanted foreign keys. It does try to get the proper type of constraint (restrict, nullify or delete), but that might not be what you want. A properly tested application will help you.

A quick summary of how geert decides which type of foreign key to use:

  • Did you specify “has_many :foobars” with “:dependent => :delete_all” or with “:dependent => :nullify”, that geert will use that too.

  • Can your foreign key be null in the database, than geert will nullify too.

  • If your foreign key cannot be null, it will constrain usage.

Generating an ERD

See a sample of the generated ERD here, based on Webistrano:

http://github.com/finalist/geert/blob/master/sample-erd.png

Click on raw for full size. Can’t link directly, because github will show it directly, which is rather awkward.

If you run on a Mac, this is really easy. You’ll might have to sacrifice a database for it, and you’ll need at least graphviz and Sequel Pro.

  • Run geert

  • Migrate your database, apply all foreign keys for the best effect.

  • Open the database in Sequel Pro

  • Select: File -> Export -> Graphviz dotfile

  • Save the dotfile

  • In the console:

    dot -Tsvg your_database.dot > your_database.svg
    
  • If you have librsvg installed, you can also generate a png file:

    dot -Tsvg your_database.dot | rsvg-convert -o your_database.png
    

You can find these applications here:

  • Sequel Pro: sequelpro.com

  • Graphviz: graphviz.org

  • librsvg: sudo port install librsvg (warning, has a lot of X11 dependencies)

Installation

To install geert:

gem install geert --source http://gemcutter.org

It requires the foreigner gem as well, so please install that into your project, before running the “geert” command. See github.com/matthuhiggins/foreigner for more info about foreigner.

Copyright © 2009 Iain Hecker. Released under the MIT License.