How important are constraints like NOT NULL and FOREIGN KEY if I'll always control my database input with PHP?

后端 未结 15 2114
我在风中等你
我在风中等你 2021-02-04 01:14

I am trying to create a column in a table that\'s a foreign key, but in MySQL that\'s more difficult than it should be. It would require me to go back and make certain changes

15条回答
  •  -上瘾入骨i
    2021-02-04 01:42

    I'm usually in favor of declaring constraints in the database. Arguments for constraints:

    • Declarative code is easier to make bug-free than Imperative code. Constraints are enforced even if app code contains bugs.
    • Supports the "Don't Repeat Yourself" principle, if you have multiple applications or code modules accessing the same database and you need business rules to be enforced uniformly. If you need to change the constraint, you can do it in one place, even if you have many apps.
    • Enforces data integrity even when people try to bypass the application, using ad hoc query tools to tinker with the database.
    • Enforces consistency which means that you can always be certain the data is in a valid state before and after any data update. If you don't use constraints, you may need to run periodic queries to check for broken references and clean them up.
    • You can model cascading update/delete easily with constraints. Doing the same thing in application code is complex and inefficient, cannot apply changes atomically (though using transaction isolation is recommended), and is susceptible to bugs.
    • Constraints help databases be more self-documenting, just as column names and SQL data types help.

    Arguments against constraints:

    • More complex business rules cannot be modeled by declarative constraints, so you have to implement some in application space anyway. Given that, why not implement all business rules in one place (your app) and in the same language? This makes it easier to debug, test, and track code revisions.
    • Constraints often involve indexes, which incur some amount of overhead during inserts/updates. On the other hand, even if you don't declare a constraint, you probably need an index anyway, because the column may be used in search criteria or join conditions frequently.
    • Constraints can complicate your attempts to "clean up" mistakes in the data.
    • In your current project, the incompatibility of MyISAM vs. InnoDB with respect to referential constraints is causing some grief.

提交回复
热议问题