Python django.db.transaction.TransactionManagementError() Examples

The following are 30 code examples of django.db.transaction.TransactionManagementError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.transaction , or try the search function .
Example #1
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def managed(self, flag=True):
        """
        Puts the transaction manager into a manual state: managed transactions have
        to be committed explicitly by the user. If you switch off transaction
        management and there is a pending commit/rollback, the data will be
        commited.
        """
        top = self.transaction_state
        if top:
            top[-1] = flag
            if not flag and self.is_dirty():
                self._commit()
                self.set_clean()
        else:
            raise TransactionManagementError("This code isn't under transaction "
                "management") 
Example #2
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def leave_transaction_management(self):
        """
        Leaves transaction management for a running thread. A dirty flag is carried
        over to the surrounding block, as a commit will commit all changes, even
        those from outside. (Commits are on connection level.)
        """
        if self.transaction_state:
            del self.transaction_state[-1]
        else:
            raise TransactionManagementError(
                "This code isn't under transaction management")
        # We will pass the next status (after leaving the previous state
        # behind) to subclass hook.
        self._leave_transaction_management(self.is_managed())
        if self._dirty:
            self.rollback()
            raise TransactionManagementError(
                "Transaction managed block ended with pending COMMIT/ROLLBACK")
        self._dirty = False 
Example #3
Source File: locks.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def acquire(self):
        connection = connections[self.db]
        qn = connection.ops.quote_name
        with connection.cursor() as cursor:
            if not connection.get_autocommit():
                raise TransactionManagementError(
                    "InnoDB requires that we not be in a transaction when "
                    "gaining a table lock."
                )

            # Begin transaction - does 'SET autocommit = 0'
            self._atomic = atomic(using=self.db)
            self._atomic.__enter__()

            locks = []
            for name in self.read:
                locks.append("{} READ".format(qn(name)))
            for name in self.write:
                locks.append("{} WRITE".format(qn(name)))
            cursor.execute("LOCK TABLES {}".format(", ".join(locks))) 
Example #4
Source File: orm.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def validate_in_transaction(connection):
    """Ensure that `connection` is within a transaction.

    This only enquires as to Django's perspective on the situation. It does
    not actually check that the database agrees with Django.

    :raise TransactionManagementError: If no transaction is in progress.
    """
    if not in_transaction(connection):
        raise TransactionManagementError(
            # XXX: GavinPanella 2015-08-07 bug=1482563: This error message is
            # specific to lobjects, but this lives in a general utils module.
            "PostgreSQL's large object support demands that all interactions "
            "are done in a transaction. Further, lobject() has been known to "
            "segfault when used outside of a transaction. This assertion has "
            "prevented the use of lobject() outside of a transaction. Please "
            "investigate."
        ) 
Example #5
Source File: orm.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def savepoint():
    """Context manager to wrap the code within a savepoint.

    This also enters a savepoint context for post-commit hooks, and so should
    always be used in preference to `transaction.atomic()` when only a
    savepoint is needed.

    If either a transaction or a savepoint within a transaction is what you
    want, use the `transactional` decorator.

    If you want a _decorator_ specifically, use the `transactional` decorator.

    If you want a _savepoint decorator_ specifically, write one, or adapt
    this to do it.

    """
    if connection.in_atomic_block:
        with post_commit_hooks.savepoint():
            with transaction.atomic():
                yield
    else:
        raise TransactionManagementError(
            "Savepoints cannot be created outside of a transaction."
        ) 
Example #6
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_raises_exception_non_autocommit_mode(self):
        def should_never_be_called():
            raise AssertionError('this function should never be called')

        try:
            connection.set_autocommit(False)
            with self.assertRaises(transaction.TransactionManagementError):
                transaction.on_commit(should_never_be_called)
        finally:
            connection.set_autocommit(True) 
Example #7
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def validate_no_atomic_block(self):
        """
        Raise an error if an atomic block is active.
        """
        if self.in_atomic_block:
            raise TransactionManagementError(
                "This is forbidden when an 'atomic' block is active.") 
Example #8
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def validate_no_broken_transaction(self):
        if self.needs_rollback:
            raise TransactionManagementError(
                "An error occurred in the current transaction. You can't "
                "execute queries until the end of the 'atomic' block.")

    # ##### Foreign key constraints checks handling ##### 
Example #9
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def on_commit(self, func):
        if self.in_atomic_block:
            # Transaction in progress; save for execution on commit.
            self.run_on_commit.append((set(self.savepoint_ids), func))
        elif not self.get_autocommit():
            raise TransactionManagementError('on_commit() cannot be used in manual transaction management')
        else:
            # No transaction in progress and in autocommit mode; execute
            # immediately.
            func() 
Example #10
Source File: test_locks.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fails_in_atomic(self):
        with atomic(), pytest.raises(TransactionManagementError) as excinfo:
            with TableLock(read=[Alphabet]):
                pass

        assert str(excinfo.value).startswith("InnoDB requires that we not be") 
Example #11
Source File: test_locks.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fail_nested(self):
        with pytest.raises(TransactionManagementError) as excinfo:
            with TableLock(write=[Alphabet]), TableLock(write=[Customer]):
                pass

        assert str(excinfo.value).startswith("InnoDB requires that we not be") 
Example #12
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def get_rollback(self):
        """
        Get the "needs rollback" flag -- for *advanced use* only.
        """
        if not self.in_atomic_block:
            raise TransactionManagementError(
                "The rollback flag doesn't work outside of an 'atomic' block.")
        return self.needs_rollback 
Example #13
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def set_rollback(self, rollback):
        """
        Set or unset the "needs rollback" flag -- for *advanced use* only.
        """
        if not self.in_atomic_block:
            raise TransactionManagementError(
                "The rollback flag doesn't work outside of an 'atomic' block.")
        self.needs_rollback = rollback 
Example #14
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def validate_no_atomic_block(self):
        """
        Raise an error if an atomic block is active.
        """
        if self.in_atomic_block:
            raise TransactionManagementError(
                "This is forbidden when an 'atomic' block is active.") 
Example #15
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def validate_no_broken_transaction(self):
        if self.needs_rollback:
            raise TransactionManagementError(
                "An error occurred in the current transaction. You can't "
                "execute queries until the end of the 'atomic' block.")

    # ##### Foreign key constraints checks handling ##### 
Example #16
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def on_commit(self, func):
        if self.in_atomic_block:
            # Transaction in progress; save for execution on commit.
            self.run_on_commit.append((set(self.savepoint_ids), func))
        elif not self.get_autocommit():
            raise TransactionManagementError('on_commit() cannot be used in manual transaction management')
        else:
            # No transaction in progress and in autocommit mode; execute
            # immediately.
            func() 
Example #17
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_rollback(self):
        """
        Get the "needs rollback" flag -- for *advanced use* only.
        """
        if not self.in_atomic_block:
            raise TransactionManagementError(
                "The rollback flag doesn't work outside of an 'atomic' block.")
        return self.needs_rollback 
Example #18
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_unsupported_transactional_ddl_disallowed(self):
        message = (
            "Executing DDL statements while in a transaction on databases "
            "that can't perform a rollback is prohibited."
        )
        with atomic(), connection.schema_editor() as editor:
            with self.assertRaisesMessage(TransactionManagementError, message):
                editor.execute(editor.sql_create_table % {'table': 'foo', 'definition': ''}) 
Example #19
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_unsupported_transactional_ddl_disallowed(self):
        message = (
            "Executing DDL statements while in a transaction on databases "
            "that can't perform a rollback is prohibited."
        )
        with atomic(), connection.schema_editor() as editor:
            with self.assertRaisesMessage(TransactionManagementError, message):
                editor.execute(editor.sql_create_table % {'table': 'foo', 'definition': ''}) 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_raises_exception_non_autocommit_mode(self):
        def should_never_be_called():
            raise AssertionError('this function should never be called')

        try:
            connection.set_autocommit(False)
            msg = 'on_commit() cannot be used in manual transaction management'
            with self.assertRaisesMessage(transaction.TransactionManagementError, msg):
                transaction.on_commit(should_never_be_called)
        finally:
            connection.set_autocommit(True) 
Example #21
Source File: orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def __enter__(self):
        if len(self.hooks) > 0:
            # Capture a textual description of the hooks to help us understand
            # why this is about to blow oodles of egg custard in our faces.
            description = "\n".join(gen_description_of_hooks(self.hooks))
            # Crash when there are orphaned post-commit hooks. These might
            # only turn up in testing, where transactions are managed by the
            # test framework instead of this decorator. We need to fail hard
            # -- not just warn about it -- to ensure it gets fixed.
            self.reset()
            raise TransactionManagementError(
                "Orphaned post-commit hooks found:\n" + description
            ) 
Example #22
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_crashes_on_enter_if_hooks_exist(self):
        hook = Deferred()
        post_commit_hooks.add(hook)
        with ExpectedException(TransactionManagementError):
            with post_commit_hooks:
                pass
        # The hook has been cancelled, but CancelledError is suppressed in
        # hooks, so we don't see it here.
        self.assertThat(hook, IsFiredDeferred())
        # The hook list is cleared so that the exception is raised only once.
        self.assertThat(post_commit_hooks.hooks, HasLength(0)) 
Example #23
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_crashes_if_hooks_exist_before_entering_transaction(self):
        post_commit(lambda failure: None)
        decorated_function = orm.transactional(lambda: None)
        self.assertRaises(TransactionManagementError, decorated_function)
        # The hook list is cleared so that the exception is raised only once.
        self.assertThat(post_commit_hooks.hooks, HasLength(0)) 
Example #24
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_explodes_when_no_transaction_is_active(self):
        self.assertRaises(
            TransactionManagementError, validate_in_transaction, connection
        ) 
Example #25
Source File: test_populate_tags.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_populate_tags_fails_called_in_transaction(self):
        with transaction.atomic():
            tag = factory.make_Tag(populate=False)
            self.assertRaises(
                transaction.TransactionManagementError, populate_tags, tag
            ) 
Example #26
Source File: managers.py    From django-postgres-copy with MIT License 5 votes vote down vote up
def from_csv(self, csv_path, mapping=None, drop_constraints=True, drop_indexes=True, silent=True, **kwargs):
        """
        Copy CSV file from the provided path to the current model using the provided mapping.
        """
        # Dropping constraints or indices will fail with an opaque error for all but
        # very trivial databases which wouldn't benefit from this optimization anyway.
        # So, we prevent the user from even trying to avoid confusion.
        if drop_constraints or drop_indexes:
            try:
                connection.validate_no_atomic_block()
            except TransactionManagementError:
                raise TransactionManagementError("You are attempting to drop constraints or "
                                                 "indexes inside a transaction block, which is "
                                                 "very likely to fail.  If it doesn't fail, you "
                                                 "wouldn't gain any significant benefit from it "
                                                 "anyway.  Either remove the transaction block, or set "
                                                 "drop_constraints=False and drop_indexes=False.")

        mapping = CopyMapping(self.model, csv_path, mapping, **kwargs)

        if drop_constraints:
            self.drop_constraints()
        if drop_indexes:
            self.drop_indexes()

        insert_count = mapping.save(silent=silent)

        if drop_constraints:
            self.restore_constraints()
        if drop_indexes:
            self.restore_indexes()

        return insert_count 
Example #27
Source File: tests.py    From django-postgres-copy with MIT License 5 votes vote down vote up
def test_atomic_block(self):
        with transaction.atomic():
            try:
                f = open(self.name_path, 'r')
                MockObject.objects.from_csv(
                    f,
                    dict(name='NAME', number='NUMBER', dt='DATE')
                )
                self.fail("Expected TransactionManagementError.")
            except TransactionManagementError:
                # Expected
                pass 
Example #28
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def set_rollback(self, rollback):
        """
        Set or unset the "needs rollback" flag -- for *advanced use* only.
        """
        if not self.in_atomic_block:
            raise TransactionManagementError(
                "The rollback flag doesn't work outside of an 'atomic' block.")
        self.needs_rollback = rollback 
Example #29
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def set_rollback(self, rollback):
        """
        Set or unset the "needs rollback" flag -- for *advanced use* only.
        """
        if not self.in_atomic_block:
            raise TransactionManagementError(
                "The rollback flag doesn't work outside of an 'atomic' block.")
        self.needs_rollback = rollback 
Example #30
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def validate_no_atomic_block(self):
        """
        Raise an error if an atomic block is active.
        """
        if self.in_atomic_block:
            raise TransactionManagementError(
                "This is forbidden when an 'atomic' block is active.")