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

后端 未结 15 2113
我在风中等你
我在风中等你 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 01:30

    I highly appreciate your question, as I am deeply convinced that default-value rules should be implemented on the code-side, not on the database-side, and this for a very simple reason: when users are the one that initiate database changes (INSERTS, SELECTS and UPDATES), these changes shall integrate all business rules, and default values are basically business rules:

    • There is no invoice without invoice number
    • There is no invoice line without a quantity, and 0 or nulls are not acceptable
    • There is no incoming mail without date of reception
    • etc

    We have decided a few years ago to get rid of all these "database-side" artefacts like "not null", "(do not) allow empty strings", and other "default value" tricks, and it works perfectly. Arguments in favor of the default value mainly refer to a kind of "security" principle ("do it on the database side because you will forget to to it on the code side / your language is not made for that/it's easier to do it on the database side") that does not make any sense once you have chosen not to implement any default value on the database side: just check that your business rules are properly implemented while debugging.

    For the last 2 years, nobody in the team ever thought of declaring a default value in a table. I guess that our younger trainee does not even know about something that is called "default value".

    EDIT: rereading some of the answers here, my final comment would be: do it on any side, either DB or code, but make your choice and do it on one side only! There is nothing more dangerous than having such controls on both sides, because eventually (1) you'll never know if both sides are really implementing the same rule, meaning that (2) checking the rules will mean checking both sides, which can really become a mess! The worst situation is of course when one part of the job is done on the database side (ie the rules that were identified when the database was created) and the other part (ie the newly identitified rules) done on the client side ... nightmare ....

提交回复
热议问题