Python oslo_db.exception.DBError() Examples

The following are 30 code examples of oslo_db.exception.DBError(). 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 oslo_db.exception , or try the search function .
Example #1
Source File: member.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _validate_create_member(self, lock_session, member_dict):
        """Validate creating member on pool."""
        try:
            return self.repositories.member.create(lock_session, **member_dict)
        except odb_exceptions.DBDuplicateEntry as de:
            column_list = ['pool_id', 'ip_address', 'protocol_port']
            constraint_list = ['uq_member_pool_id_address_protocol_port']
            if ['id'] == de.columns:
                raise exceptions.IDAlreadyExists()
            if (set(column_list) == set(de.columns) or
                    set(constraint_list) == set(de.columns)):
                raise exceptions.DuplicateMemberEntry(
                    ip_address=member_dict.get('ip_address'),
                    port=member_dict.get('protocol_port'))
        except odb_exceptions.DBError:
            # TODO(blogan): will have to do separate validation protocol
            # before creation or update since the exception messages
            # do not give any information as to what constraint failed
            raise exceptions.InvalidOption(value='', option='') 
Example #2
Source File: l7policy.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _validate_create_l7policy(self, lock_session, l7policy_dict):
        try:
            # Set the default HTTP redirect code here so it's explicit
            if ((l7policy_dict.get('redirect_url') or
                l7policy_dict.get('redirect_prefix')) and
                    not l7policy_dict.get('redirect_http_code')):
                l7policy_dict['redirect_http_code'] = 302

            return self.repositories.l7policy.create(lock_session,
                                                     **l7policy_dict)
        except odb_exceptions.DBDuplicateEntry:
            raise exceptions.IDAlreadyExists()
        except odb_exceptions.DBError:
            # TODO(blogan): will have to do separate validation protocol
            # before creation or update since the exception messages
            # do not give any information as to what constraint failed
            raise exceptions.InvalidOption(value='', option='') 
Example #3
Source File: sqlalchemy.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def _retry_on_exceptions(exc):
    if not isinstance(exc, exception.DBError):
        return False
    inn_e = exc.inner_exception
    if not isinstance(inn_e, sqlalchemy.exc.InternalError):
        return False
    return ((
        pymysql and
        isinstance(inn_e.orig, pymysql.err.InternalError) and
        (inn_e.orig.args[0] == pymysql.constants.ER.TABLE_DEF_CHANGED)
    ) or (
        # HACK(jd) Sometimes, PostgreSQL raises an error such as "current
        # transaction is aborted, commands ignored until end of transaction
        # block" on its own catalog, so we need to retry, but this is not
        # caught by oslo.db as a deadlock. This is likely because when we use
        # Base.metadata.create_all(), sqlalchemy itself gets an error it does
        # not catch or something. So this is why this function exists. To
        # paperover I guess.
        psycopg2
        and isinstance(inn_e.orig, psycopg2.InternalError)
        # current transaction is aborted
        and inn_e.orig.pgcode == '25P02'
    )) 
Example #4
Source File: utils.py    From designate with Apache License 2.0 6 votes vote down vote up
def check_marker(table, marker, session):

    marker_query = select([table]).where(table.c.id == marker)

    try:
        marker_resultproxy = session.execute(marker_query)
        marker = marker_resultproxy.fetchone()
        if marker is None:
            raise exceptions.MarkerNotFound(
                'Marker %s could not be found' % marker)
    except oslo_db_exception.DBError as e:
        # Malformed UUIDs return StatementError wrapped in a
        # DBError
        if isinstance(e.inner_exception,
                      sqlalchemy_exc.StatementError):
            raise exceptions.InvalidMarker()
        else:
            raise

    return marker 
Example #5
Source File: migrations_data_checks.py    From manila with Apache License 2.0 6 votes vote down vote up
def check_upgrade(self, engine, data):
        sg_table = utils.load_table(self.table_name, engine)
        db_result = engine.execute(sg_table.select().where(
            sg_table.c.id == self.share_group_id))
        self.test_case.assertEqual(1, db_result.rowcount)
        for sg in db_result:
            self.test_case.assertTrue(hasattr(sg, self.new_attr_name))

            # Check that we can write proper enum data to the new field
            for value in (None, 'pool', 'host'):
                # pylint: disable=no-value-for-parameter
                engine.execute(sg_table.update().where(
                    sg_table.c.id == self.share_group_id,
                ).values({self.new_attr_name: value}))

            # Check that we cannot write values that are not allowed by enum.
            for value in ('', 'fake', 'pool1', 'host1', '1pool', '1host'):
                # pylint: disable=no-value-for-parameter
                self.test_case.assertRaises(
                    oslo_db_exc.DBError,
                    engine.execute,
                    sg_table.update().where(
                        sg_table.c.id == self.share_group_id
                    ).values({self.new_attr_name: value})
                ) 
Example #6
Source File: test_service.py    From karbor with Apache License 2.0 6 votes vote down vote up
def test_report_state_disconnected_DBError(self):
        service_ref = {'host': self.host,
                       'binary': self.binary,
                       'topic': self.topic,
                       'report_count': 0,
                       'id': 1}
        with mock.patch.object(service, 'db') as mock_db:
            mock_db.service_get_by_args.side_effect = exception.NotFound()
            mock_db.service_create.return_value = service_ref
            mock_db.service_get.side_effect = db_exc.DBError()

            serv = service.Service(
                self.host,
                self.binary,
                self.topic,
                'karbor.tests.unit.test_service.FakeManager'
            )
            serv.start()
            serv.report_state()
            self.assertTrue(serv.model_disconnected)
            self.assertFalse(mock_db.service_update.called) 
Example #7
Source File: share_types.py    From manila with Apache License 2.0 6 votes vote down vote up
def update(context, id, name, description, is_public=None):
    """Update share type by id."""
    values = {}
    if name:
        values.update({'name': name})
    if description == "":
        values.update({'description': None})
    elif description:
        values.update({'description': description})
    if is_public is not None:
        values.update({'is_public': is_public})
    try:
        db.share_type_update(context, id, values)
    except db_exception.DBError:
        LOG.exception('DB error.')
        raise exception.ShareTypeUpdateFailed(id=id) 
Example #8
Source File: test_sqlalchemy.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_string_too_long(self):
        value = 'a' * 512
        # String is too long.
        # With STRICT_ALL_TABLES or TRADITIONAL mode set, this is an error.
        self.assertRaises(exception.DBError,
                          self._test_string_too_long, value) 
Example #9
Source File: test_types.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_dict_type_check(self):
        self.assertRaises(db_exc.DBError,
                          JsonTable(id=1, jdict=[]).save, self.session) 
Example #10
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_generic_dbapi(self):
        matched = self._run_test(
            "mysql", "select you_made_a_programming_error",
            self.ProgrammingError("Error 123, you made a mistake"),
            exception.DBError
        )
        self.assertInnerException(
            matched,
            "ProgrammingError",
            "Error 123, you made a mistake",
            'select you_made_a_programming_error', ()) 
Example #11
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_garden_variety(self):
        matched = self._run_test(
            "mysql", "select some_thing_that_breaks",
            AttributeError("mysqldb has an attribute error"),
            exception.DBError
        )
        self.assertEqual("mysqldb has an attribute error", matched.args[0]) 
Example #12
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_cause_for_failed_flush_plus_no_savepoint(self):
        session = self.sessionmaker()

        with session.begin():
            session.add(self.A(id=1))
        try:
            with session.begin():
                try:
                    with session.begin_nested():
                        session.execute("rollback")
                        session.add(self.A(id=1))
                # outermost is the failed SAVEPOINT rollback
                # from the "with session.begin_nested()"
                except exception.DBError as dbe_inner:
                    # in SQLA 1.1+, the rollback() method of Session
                    # catches the error and repairs the state of the
                    # session even though the SAVEPOINT was lost;
                    # the net result here is that one exception is thrown
                    # instead of two.  This is SQLAlchemy ticket #3680
                    self.assertTrue(
                        isinstance(
                            dbe_inner.cause,
                            exception.DBDuplicateEntry
                        )
                    )
        except exception.DBError as dbe_outer:
            self.assertTrue(
                isinstance(
                    dbe_outer.cause,
                    exception.DBDuplicateEntry
                )
            )

        # resets itself afterwards
        try:
            with session.begin():
                session.add(self.A(id=1))
        except exception.DBError as dbe_outer:
            self.assertIsNone(dbe_outer.cause) 
Example #13
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_unsupported_backend(self):
        self._not_dupe_constraint_test(
            "nonexistent", "insert into table some_values",
            self.IntegrityError("constraint violation"),
            exception.DBError
        ) 
Example #14
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_ibm_db_sa_notadupe(self):
        self._not_dupe_constraint_test(
            'ibm_db_sa',
            'ALTER TABLE instance_types ADD CONSTRAINT '
            'uniq_name_x_deleted UNIQUE (name, deleted)',
            'SQL0542N  The column named "NAME" cannot be a column of a '
            'primary key or unique key constraint because it can contain null '
            'values.',
            exception.DBError
        ) 
Example #15
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_postgresql_not_deadlock(self):
        self._not_deadlock_test(
            "postgresql",
            'relation "fake" does not exist',
            # can be either depending on #3075
            (exception.DBError, sqla.exc.OperationalError),
            "TransactionRollbackError",
            orig_exception_cls=self.TransactionRollbackError
        ) 
Example #16
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_ibm_db_sa_not_deadlock(self):
        self._not_deadlock_test(
            "ibm_db_sa",
            "SQL01234B Some other error.",
            exception.DBError,
            "Error",
            orig_exception_cls=self.Error
        ) 
Example #17
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_flush_wrapper_plain_integrity_error(self):
        """test a plain integrity error wrapped as DBError."""

        _session = self.sessionmaker()

        with _session.begin():
            foo = self.Foo(counter=1)
            _session.add(foo)

        _session.begin()
        self.addCleanup(_session.rollback)
        foo = self.Foo(counter=None)
        _session.add(foo)
        self.assertRaises(exception.DBError, _session.flush) 
Example #18
Source File: test_exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_multiple_error_handlers(self):
        handler = mock.MagicMock(return_value=None)
        sqla.event.listen(self.engine, "handle_error", handler, retval=True)

        # cause an error in DB API
        self._run_test(
            "mysql", "select you_made_a_programming_error",
            self.ProgrammingError("Error 123, you made a mistake"),
            exception.DBError
        )

        # expect custom handler to be called together with oslo.db's one
        self.assertEqual(1, handler.call_count,
                         'Custom handler should be called') 
Example #19
Source File: exc_filters.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def _raise_savepoints_as_dberrors(error, match, engine_name, is_disconnect):
    # NOTE(rpodolyaka): this is a special case of an OperationalError that used
    # to be an InternalError. It's expected to be wrapped into oslo.db error.
    raise exception.DBError(error) 
Example #20
Source File: utils.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def is_retriable(exception):
    """Determine if the said exception is retriable.

    :param exception: The exception to check.
    :returns: True if 'exception' is retriable, otherwise False.
    """
    if _is_nested_instance(exception,
                           (db_exc.DBDeadlock, exc.StaleDataError,
                            db_exc.DBConnectionError,
                            db_exc.DBDuplicateEntry, db_exc.RetryRequest)):
        return True
    # Look for savepoints mangled by deadlocks. See bug/1590298 for details.
    return (_is_nested_instance(exception, db_exc.DBError) and
            '1305' in str(exception)) 
Example #21
Source File: api.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def _is_nested_instance(e, etypes):
    """Check if exception or its inner excepts are an instance of etypes."""
    if isinstance(e, etypes):
        return True
    if isinstance(e, exceptions.MultipleExceptions):
        return any(_is_nested_instance(i, etypes) for i in e.inner_exceptions)
    if isinstance(e, db_exc.DBError):
        return _is_nested_instance(e.inner_exception, etypes)
    return False 
Example #22
Source File: api.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def is_retriable(e):
    """Determine if the exception is retriable.

    :param e: The exception to check.
    :returns: True if e is retriable and False otherwise.
    """
    if getattr(e, '_RETRY_EXCEEDED', False):
        return False
    if _is_nested_instance(e, (db_exc.DBDeadlock, exc.StaleDataError,
                               db_exc.DBConnectionError,
                               db_exc.DBDuplicateEntry, db_exc.RetryRequest,
                               obj_exc.NeutronDbObjectDuplicateEntry)):
        return True
    # looking savepoints mangled by deadlocks. see bug/1590298 for details.
    return _is_nested_instance(e, db_exc.DBError) and '1305' in str(e) 
Example #23
Source File: test_api.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_translates_DBerror_inner_exception(self):
        with testtools.ExpectedException(db_exc.RetryRequest):
            with db_api.exc_to_retry(ValueError):
                raise db_exc.DBError(ValueError()) 
Example #24
Source File: test_api.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_mysql_savepoint_error(self):
        e = db_exc.DBError("(pymysql.err.InternalError) (1305, u'SAVEPOINT "
                           "sa_savepoint_1 does not exist')")
        self.assertIsNone(self._decorated_function(1, e)) 
Example #25
Source File: test_sqlalchemytypes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_wrong_cidr(self):
        wrong_cidrs = ["10.500.5.0/24", "10.0.0.1/40", "10.0.0.10.0/24",
                       "cidr", "", '2001:db8:5000::/64', '2001:db8::/130']
        for cidr in wrong_cidrs:
            self.assertRaises(exception.DBError, self._add_row,
                              id=uuidutils.generate_uuid(), cidr=cidr) 
Example #26
Source File: test_sqlalchemytypes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_wrong_mac(self):
        wrong_macs = ["fake", "", -1,
                      "FK:16:3E:00:00:02",
                      "FA:16:3E:00:00:020"]
        for mac in wrong_macs:
            self.assertRaises(exception.DBError, self._add_row,
                              id=uuidutils.generate_uuid(), mac=mac) 
Example #27
Source File: api.py    From manila with Apache License 2.0 5 votes vote down vote up
def share_type_create(context, values, projects=None):
    """Create a new share type.

    In order to pass in extra specs, the values dict should contain a
    'extra_specs' key/value pair:
    {'extra_specs' : {'k1': 'v1', 'k2': 'v2', ...}}
    """
    values = ensure_model_dict_has_id(values)

    projects = projects or []

    session = get_session()
    with session.begin():
        try:
            values['extra_specs'] = _metadata_refs(values.get('extra_specs'),
                                                   models.ShareTypeExtraSpecs)
            share_type_ref = models.ShareTypes()
            share_type_ref.update(values)
            share_type_ref.save(session=session)
        except db_exception.DBDuplicateEntry:
            raise exception.ShareTypeExists(id=values['name'])
        except Exception as e:
            raise db_exception.DBError(e)

        for project in set(projects):
            access_ref = models.ShareTypeProjects()
            access_ref.update({"share_type_id": share_type_ref.id,
                               "project_id": project})
            access_ref.save(session=session)

        return share_type_ref 
Example #28
Source File: l7rule.py    From octavia with Apache License 2.0 5 votes vote down vote up
def _validate_create_l7rule(self, lock_session, l7rule_dict):
        try:
            return self.repositories.l7rule.create(lock_session, **l7rule_dict)
        except odb_exceptions.DBDuplicateEntry:
            raise exceptions.IDAlreadyExists()
        except odb_exceptions.DBError:
            # TODO(blogan): will have to do separate validation protocol
            # before creation or update since the exception messages
            # do not give any information as to what constraint failed
            raise exceptions.InvalidOption(value='', option='') 
Example #29
Source File: test_service.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_update_pool_add_ns_record_without_priority(self):
        pool = self.create_pool(fixture=0)
        self.create_zone(pool_id=pool.id)
        new_ns_record = objects.PoolNsRecord(hostname='ns-new.example.org.')
        pool.ns_records.append(new_ns_record)
        # PoolNsRecord without "priority" triggers a DB exception
        with testtools.ExpectedException(db_exception.DBError):
            self.central_service.update_pool(self.admin_context, pool) 
Example #30
Source File: test_vpn_db.py    From neutron-vpnaas with Apache License 2.0 5 votes vote down vote up
def helper_create_endpoint_group(self, info):
        """Create endpoint group database entry and verify OK."""
        group = info['endpoint_group']
        try:
            actual = self.plugin.create_endpoint_group(self.context, info)
        except db_exc.DBError as e:
            self.fail("Endpoint create in prep for test failed: %s" % e)
        self._compare_groups(group, actual)
        self.assertIn('id', actual)
        return actual['id']