Hi everyone,
When I say operations, I mean stuff like "make a folder" or "copy a file" or "query a database".
Here's an example:
def setup_folder(new_folder, file):
path = os.path.join("/mnt/destination/", new_folder)
os.mkdir(path)
db.add_folder(path)
shutil.copyfile(file, path)
db.add_file(os.path.join(path, file))
However, if any of those actions fail (namely the database query since it will be part of enforcing business rules), I need to roll back all operations as though they never happened.
If the mkdir fails, no action required.
If the folder log fails, ok, remove the folder.
If the file copy fails, ok, remove the folder log and the folder.
If the final copy log fails...
And so on.
A try/except may work, but it will get clunky with large operations:
try:
# mkdir
# db folder
# copy file
# db file
except:
# folder exists:
# remove
# select folder log from database
# if row exists
# delete row
# select file log from database
# if row exists
# delete row
Or if you try/except each step, you start copy/pasting except contents.
# mkdir
try:
# db folder
except:
# remove folder
try:
# copy file
except:
# remove folder (copy paste)
# remove db folder from database
Is there a design pattern to handle this gracefully? I'm really interested in learning best practise, not just how to 'get it done'.
I remember reading you can assign a function to a variable. Is constructing a list of rollback functions as operations succeed a good idea?