What to delete first? the db record or the referenced data (what was first the egg or the chicken?)
Well maybe you like me, were trying to store images or raw data like files directly in the database but that is not a good idea because store raw data or binary data inside a database is really expensive in terms of performance and could make the queries to the database's tables really slow.
So you decided like me, just to store a reference to the file in the database and keep the file in some specific folder. Let's see a example:
+--------------+
| stories |
+--------------+
| storyid |
| categoryid |
| title |
| content |
| picture |
| created |
| modified |
| published |
+--------------+
In the above table we have a basic schema that could be useful to store maybe blog entries with title, main story and a picture. Well the picture field could be a VARCHAR(255) and in that field we could store the file data reference like: 'story_images/some_picture.jpg'
In that way we could easily fetch the story and just put in the "src" attribute of the HTML img element the "picture" field of the story that contains the url or path of the file.
Ok, but now the main point of interest of this blog entry is what happens when I wish to delete the story record? well one thing for sure is that I have to delete the record in the database and also delete the file (the actual picture, raw data or binary data) in the server. But now what is first the egg or the chicken? let's see what could happen:
- The query to delete the record in the db fails and also the delete (unlink) of the file fails (maybe the script that is trying to delete the file doesn't have enough permissions). Well in this case we are like in the beginning it's like nothing have happened (not bad not good).
- The query to delete the record in the db fails, but now the delete of the file have been successful. This scenario is a bad one because this could lead to inconsistency in the data, because the db record now references a file that doesn't exist anymore.
- The query to delete the record have been successful, but the delete of the file have failed. This scenario is not that good, but now at least for the end user it's like everything is ok, because he can't see the db record anymore (maybe when listing the whole set of blog stories)
- Both, the query to delete the record and the delete of the file have been successful. Everybody is happy here :)
So in conclusion, try to delete the db record first, if the query execution was successful then delete the file (referenced data).