rod mclaughlin


Clever databases, Rails performance issues, and stored procedures (09 oct 10)

I know David Heinemeier Hansson, the creator of Rails, doesn't like 'clever databases'. Brilliant though he is, I am unconvinced - databases can have constraints, so they should. Something other than Rails might access the database. The problem is maintaining 'business logic' (eg. all customers must have a first and a last name and maybe a middle name) in more than one place.

This constraint can be in three places - the web pages can have JavaScript to check that the customer entered at least a first and a last name, the 'middleware' (the Ruby code) can do it also, and it can be in the database too (last_name NOT NULL). If the constraint changes, eg. they don't need a last name, three changes have to be made in three languages. It's easy to make a mistake if you have to do the same thing three times.

Hansson's solution is to put it in the middleware. Rails generates the checks for the web pages, so that's two out of three. As for the database, Hansson says "don't bother".

This isn't the real solution. What you need is one place where you maintain the constraints, then they propagate to the other two places. I wrote something like this using .NET and M$ SQL Server, where the database constraints are picked up when the application server starts, then added to the C# code. I would like to do something like this for Rails. It would involve stored procedures.


Stored procedures solve constraints, security and performance issues. I got a multi-table join from 2 hours with Active Record to 1 hour with find_by_sql to 3 minutes with a stored procedure (Rails 2.3.8, PostgreSQL).

It's all explained very well at http://nasir.wordpress.com/2007/12/03/stored-procedures-and-rails/



Back
Portland London