#๐Ÿ”’ Rolling back a series of operations

12 messages ยท Page 1 of 1 (latest)

inner topaz
#

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?

bright mauveBOT
#

@inner topaz

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

exotic cargo
#

from the top of my head, database migration tools do something similar.
They typically provide an "upgrade" and "downgrade" function for each migration step.

exotic cargo
#

tried it out. only rolls back on error

worthy saddle
#

Then use pop_all() if it's successful

exotic cargo
#

ah okay, that might look cleaner

inner topaz
bright mauveBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.