sql - Should validation be carried out at the application or database level? -
i relatively new database programming , find coding aspect of sql counter intuitive. coding mean, example, finding single string value in column , capitalizing it, concatenating value, modifying based on table references it, etc.
my question whether better enforce rules governing data @ database level or @ application level, , why. this article (see enforcing integrity via applications), example, argues should enforced @ database level.
here 2 examples, 1 obvious, 1 more complex.
if have simple person table so
create table person( id serial, age int check (age>=0) );
it makes sense enforce non negative age @ database level. however, if have more complicated example so
create table person( id serial, age int check (age>=0), spouse int references person (id) );
ensuring
- both spouses on 18
- both spouses single @ time of marriage
- spouses not in polygamous relationship
requires more complex triggers. alternatively, these checked when adding database far more human readable languages php or python. if database built 1 program, acceptable enforce these rules @ database level?
this crucial design question when designing database , application. things think about:
- are planning give users field level validation feedback? if so, field level validation might better done in application code. otherwise, when attempt insert have decode exception figure out problem is.
- how familiar database , capabilities? more logic put database, more dependent on syntax , behavior.
- will application ever ported database? example, sql-server mysql? or postgres oracle? if so, consider amount of effort needed translate logic have embedded in schema new database's lexicon.
i tend put validation application , integrity constraints (a.k.a foreign key constraints) database. put validation application can tell user what's wrong input. think integrity constraints vital @ db level because, inevitably, need make sort of manual database update correct problem, add new capability, or whatever. constraints protect against errors in manual updates , against bugs in application logic.
Comments
Post a Comment