Search code examples
databasevalidationbusiness-logicunique-constraint

Should database constraints map to the business logic


The database has a unique constraint index on the users NAME field.

The business service checks via

service.GetUser(userName);

to see whether a user name already exists. Because of this logic in the service there can never be inserted duplicate names. I do not catch exceptions for a SqlException with Number = 2627 which is for unique constraint violations.

So why would I put a unique constraint on the NAME field?


Solution

  • Because of this logic in the service there can never be inserted duplicate names, so WHY should I put on the NAME field a unique constraint?

    Because there's no other good way to guarantee that, for the entire lifetime of the database, no application adds data except through that service.

    Every dbms that I'm familiar with includes a command-line interface, a graphical interface, and a bulk loader. That makes at least three applications that can be used to modify data without going through service.GetUser().