Alex Rivera | Logout

Should you enforce constraints at the database level as well as the application level?

Asked 2009-01-21T03:59:54.750
76

I've been reading the book "Enterprise Rails" by Dan Chak and it got me thinking: Do you feel that you should have data constraints at both the database level and the application level? Or do you feel similarly to opinionated frameworks like Ruby on Rails - the database is just a "dumb repository" for data, and all checks should be done in your application (I'm not trying to single out RoR here - I'm a huge fan of Rails myself, but I disagree with its approach to the database)?

Personally, I feel that you should have them both in order to make sure your database and application are well-secured. What I mean is that you should make use of not-null constraints, give your fields a length if known ( as opposed to leaving them all at nvarchar(255) ), have things such as Foreign Keys, Check Constraints and Triggers on your database, and then also enforce this through business logic rules in your application. IMO this makes your application robust through its user interface, and also secure against someone who might have direct access to the database.

The counter-argument I most often see is that it requires what amounts to duplicate logic; once at the database level, and once at the application level -- Let's say you have a check constraint to verify that a product's SKU is entered (i.e. it's length is greater than zero).

You would now need to also include validation methods in your business logic to make sure the value the user entered has a length greater than zero, and also possibly some client-side Javascript to catch the error as the user types data.

I for one do not see this as a bad thing - yes you have some duplicate logic, but the end result is the "database as fortress" mindset, since if you think about it your data is the single most important part of your application; after all, what good is your shiny new Web 2.0 application if the data can easily be corrupted a

Edit
Report

1 Answer

8

I think you should try and protect your data at all costs. Nothing is worse then trying to do reporting on an application which had bad data because the application had a bug. Now what does this mean?

You should enforce your relationships through FK's, there is no reason not to. You should try and avoid null values and only use them when null values are appropiate. I do think there is a fine line however.

Should you parse a phone number to ensure it's in the proper format? Probably not, but then again you should probably store the phone number in a schema that doesn't have a formating issue.

answered 2009-01-21T04:16:47.493

Your Answer