I recently discovered the wonders of foreign keys and deletion cascading with InnoDB and I love it. It helps me easily delete intricate data structures without worrying about leaving junk behind.
I'm currently storing images for a products database (like you would have on a web-shop) in the following manner:
My products table is what you would expect, it has an id primary column.
My product_images table has a product_id column with a foreign key to the products.id column, and an image column of type varchar storing the image file name.
The file names are created by computing the SHA1 hash of the image, then storing in a folder named after the first 2 characters of the hash:
61/6153A6FA0E4880D9B8D0BE4720F78E895265D0A9.jpg. In the database, only 6153A6FA0E4880D9B8D0BE4720F78E895265D0A9.jpg is stored.
Now, if I were to delete a product from the database, the cascading DELETE rule would delete the record in the product_images table, but would leave the file on my server.
Is there a way to automate the deletion of the image file whenever a record in the product_images table is deleted, be it specifically or by cascading? Maybe link some kind of trigger or routine to the deletion operation?