Last active
January 15, 2021 12:29
-
-
Save gaikaz/f3dc6ccca6ef4615c8e52321b18e7cdc to your computer and use it in GitHub Desktop.
Odoo request transaction logic example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# PSQL DB cursor mock | |
class Cursor: | |
def __init__(self): | |
print('cursor: BEGIN') | |
def commit(self): | |
print('cursor: COMMIT') | |
def rollback(self): | |
print('cursor: ROLLBACK') | |
def close(self): | |
print('cursor: CLOSE') | |
cr = Cursor() | |
def failingCode(): | |
# Let's open a black hole (•̀ᴗ•́ )و ̑̑ | |
return 2 / 0 | |
def yourCode(): | |
try: | |
# ... some code that changes data ... | |
failingCode() | |
# ... some more code ... | |
except Exception: | |
# Because the error is not re-raised, | |
# This stops Odoo from rollback'ing any bad changes | |
print('I caught it!') | |
# This is roughly what happens in Odoo core | |
try: | |
# Your code should not catch errors without re-raising ... | |
yourCode() | |
cr.commit() | |
except Exception: | |
# ... because "rollback" would not get executed. | |
cr.rollback() | |
finally: | |
cr.close() | |
# When executed, this code prints: | |
""" | |
cursor: BEGIN | |
I caught it! | |
cursor: COMMIT | |
cursor: CLOSE | |
""" | |
# Notice how there is no "cursor: ROLLBACK" message. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment