I am saving a file to a server and I'm saving the filename, user id of the individual who uploaded the file, and various other information about the file to a PostgreSQL database. I ideally want to structure this in a way that is similar to a database transaction. That is, one of the following should occur:
- Save file
- If successful, save information to database
- If saving information to database fails, delete file
OR
- Save information to database
- If successful, save file
- If saving file fails, delete information from database
The only problem with this methodology is step 3 may fail--that is, you may be left with a file saved without corresponding information in the database or you may have database information without a corresponding file saved.
What I want to know is if there is a way that you can use either of the two methods above while ensuring step 3 always occurs or occurs with sufficient reliability that I effectively do not have to worry about failure.
Note that I am using a PostgreSQL database and saving an image file using the imagegif
, imagejpeg
, and imagepng
functions from the GD library.
EDIT
In response to Jack's solid comments below, I forgot to mention that I am interacting with the DB through an API server, so instead of directly interacting with the DB, I am sending REST requests to the API which in turn interacting with the DB. What this effectively means is that I can't just put both database interactions into one transaction.