diff --git a/django/db/transaction.py b/django/db/transaction.py index 5d80bf24f03f3..61238fa911ebd 100644 --- a/django/db/transaction.py +++ b/django/db/transaction.py @@ -245,7 +245,11 @@ def _commit_on_success(*args, **kw): raise else: if is_dirty(): - commit() + try: + commit() + except: + rollback() + raise return res finally: leave_transaction_management() diff --git a/tests/modeltests/transactions/models.py b/tests/modeltests/transactions/models.py index 6763144ca5d08..9f32776f26191 100644 --- a/tests/modeltests/transactions/models.py +++ b/tests/modeltests/transactions/models.py @@ -100,3 +100,23 @@ def __unicode__(self): ... TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK """ + +# Regression for #11900: If a function wrapped by commit_on_success writes a +# transaction that can't be committed, that transaction should be rolled back. +# The bug is only visible using the psycopg2 backend, though +# the fix is generally a good idea. +if building_docs or settings.DATABASE_ENGINE == 'postgresql_psycopg2': + __test__['API_TESTS'] += """ +>>> def execute_bad_sql(): +... cursor = connection.cursor() +... cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');") +... transaction.set_dirty() +... +>>> execute_bad_sql = transaction.commit_on_success(execute_bad_sql) +>>> execute_bad_sql() +Traceback (most recent call last): + ... +IntegrityError: null value in column "email" violates not-null constraint + + +"""