Should I check for DB constraints in code or should I catch exceptions thrown by DB

前端 未结 8 563
别跟我提以往
别跟我提以往 2021-02-04 03:43

I have an application that saves data into a table called Jobs. The Jobs table has a column called Name which has a UNIQUE constraint. The Name column is not PRIMARY KEY. I wond

8条回答
  •  轮回少年
    2021-02-04 04:09

    The answer is: both.

    If your database has constraints it can guarantee certain invariants about the data, such as uniqueness. This helps in several ways:

    • If you have a bug in your application, violating the constraint will flag something that might otherwise not be noticed.

    • Other users of the database can assume more about the behaviour of the data as the DBMS enforces invariants.

    • The database protects itself from incorrect updates that violate the constraints. If you find you have some other system or interface populating the database down the track, the constraints enforced by the database mean that anything caught by the constraints won't (or at least is less likely to) break your system.

    Applications and databases live in a M:M relationship in any but the most trivial cases. The application should still have the appropriate data and business rule validations but you should still not plan for your application being the only customer of the data. Work in data warehousing for a few years and you'll see the effects of applications designed by people with this mindset.

提交回复
热议问题