本文整理汇总了Python中oslo_db.exception.DBReferenceError方法的典型用法代码示例。如果您正苦于以下问题:Python exception.DBReferenceError方法的具体用法?Python exception.DBReferenceError怎么用?Python exception.DBReferenceError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oslo_db.exception
的用法示例。
在下文中一共展示了exception.DBReferenceError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_archive_policy_rule
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def create_archive_policy_rule(self, name, metric_pattern,
archive_policy_name):
apr = ArchivePolicyRule(
name=name,
archive_policy_name=archive_policy_name,
metric_pattern=metric_pattern
)
try:
with self.facade.writer() as session:
session.add(apr)
except exception.DBReferenceError as e:
if e.constraint == 'fk_apr_ap_name_ap_name':
raise indexer.NoSuchArchivePolicy(archive_policy_name)
raise
except exception.DBDuplicateEntry:
raise indexer.ArchivePolicyRuleAlreadyExists(name)
return apr
示例2: create_metric
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def create_metric(self, id, creator, archive_policy_name,
name=None, unit=None, resource_id=None):
m = Metric(id=id,
creator=creator,
archive_policy_name=archive_policy_name,
name=name,
unit=unit,
resource_id=resource_id)
try:
with self.facade.writer() as session:
session.add(m)
except exception.DBDuplicateEntry:
raise indexer.NamedMetricAlreadyExists(name)
except exception.DBReferenceError as e:
if (e.constraint ==
'fk_metric_ap_name_ap_name'):
raise indexer.NoSuchArchivePolicy(archive_policy_name)
if e.constraint == 'fk_metric_resource_id_resource_id':
raise indexer.NoSuchResource(resource_id)
raise
return m
示例3: test_db_cleanup_raise_integrity_error
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def test_db_cleanup_raise_integrity_error(self, project):
"""Test that an integrity error is thrown
This test tests the invalid scenario where
the secret meta was not marked for deletion during the secret deletion.
We want to make sure an integrity error is thrown during clean up.
"""
# create secret
secret = _setup_entry('secret', project=project)
secret_metadatum = _setup_entry('secret_metadatum', secret=secret)
# delete parent but not child and assert integrity error
secret.deleted = True
secret_metadatum.deleted = False
self.assertRaises(db_exc.DBReferenceError, clean.cleanup_all)
示例4: _foreign_key_error
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def _foreign_key_error(integrity_error, match, engine_name, is_disconnect):
"""Filter for foreign key errors."""
try:
table = match.group("table")
except IndexError:
table = None
try:
constraint = match.group("constraint")
except IndexError:
constraint = None
try:
key = match.group("key")
except IndexError:
key = None
try:
key_table = match.group("key_table")
except IndexError:
key_table = None
raise exception.DBReferenceError(table, constraint, key, key_table,
integrity_error)
示例5: test_raise
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def test_raise(self):
self.engine.execute("PRAGMA foreign_keys = ON;")
matched = self.assertRaises(
exception.DBReferenceError,
self.engine.execute,
self.table_2.insert({'id': 1, 'foo_id': 2})
)
self.assertInnerException(
matched,
"IntegrityError",
"FOREIGN KEY constraint failed",
'INSERT INTO resource_entity (id, foo_id) VALUES (?, ?)',
(1, 2)
)
self.assertIsNone(matched.table)
self.assertIsNone(matched.constraint)
self.assertIsNone(matched.key)
self.assertIsNone(matched.key_table)
示例6: test_raise_delete
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def test_raise_delete(self):
self.engine.execute("PRAGMA foreign_keys = ON;")
with self.engine.connect() as conn:
conn.execute(self.table_1.insert({"id": 1234, "foo": 42}))
conn.execute(self.table_2.insert({"id": 4321, "foo_id": 1234}))
matched = self.assertRaises(
exception.DBReferenceError,
self.engine.execute,
self.table_1.delete()
)
self.assertInnerException(
matched,
"IntegrityError",
"foreign key constraint failed",
"DELETE FROM resource_foo",
(),
)
self.assertIsNone(matched.table)
self.assertIsNone(matched.constraint)
self.assertIsNone(matched.key)
self.assertIsNone(matched.key_table)
示例7: test_raise_ansi_quotes
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def test_raise_ansi_quotes(self):
with self.engine.connect() as conn:
conn.detach() # will not be returned to the pool when closed
# this is incompatible with some internals of the engine
conn.execute("SET SESSION sql_mode = 'ANSI';")
matched = self.assertRaises(
exception.DBReferenceError,
conn.execute,
self.table_2.insert({'id': 1, 'foo_id': 2})
)
# NOTE(jd) Cannot check precisely with assertInnerException since MySQL
# error are not the same depending on its version…
self.assertIsInstance(matched.inner_exception,
sqlalchemy.exc.IntegrityError)
self.assertEqual(matched.inner_exception.orig.args[0], 1452)
self.assertEqual("resource_entity", matched.table)
self.assertEqual("foo_fkey", matched.constraint)
self.assertEqual("foo_id", matched.key)
self.assertEqual("resource_foo", matched.key_table)
示例8: _test_save_objectfield_fk_constraint_fails
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def _test_save_objectfield_fk_constraint_fails(self, foreign_key,
expected_exception):
error = db_exc.DBReferenceError('table', 'constraint', foreign_key,
'key_table')
# Prevent lazy-loading any fields, results in InstanceNotFound
deployable = fake_deployable.fake_deployable_obj(self.context)
fields_with_save_methods = [field for field in deployable.fields
if hasattr(deployable, '_save_%s' % field)]
for field in fields_with_save_methods:
@mock.patch.object(deployable, '_save_%s' % field)
@mock.patch.object(deployable, 'obj_attr_is_set')
def _test(mock_is_set, mock_save_field):
mock_is_set.return_value = True
mock_save_field.side_effect = error
deployable.obj_reset_changes(fields=[field])
deployable._changed_fields.add(field)
self.assertRaises(expected_exception, deployable.save)
deployable.obj_reset_changes(fields=[field])
_test()
示例9: delete
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def delete(self, id, version_id):
"""Delete a product version.
Endpoint: /v1/products/<product_id>/versions/<version_id>
"""
if (not api_utils.check_user_is_product_admin(id) and
not api_utils.check_user_is_foundation_admin()):
pecan.abort(403, 'Forbidden.')
try:
version = db.get_product_version(version_id,
allowed_keys=['version'])
if not version['version']:
pecan.abort(400, 'Can not delete the empty version as it is '
'used for basic product/test association. '
'This version was implicitly created with '
'the product, and so it cannot be deleted '
'explicitly.')
db.delete_product_version(version_id)
except DBReferenceError:
pecan.abort(400, 'Unable to delete. There are still tests '
'associated to this product version.')
pecan.response.status = 204
示例10: _mark_as_deleting_resource_type
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def _mark_as_deleting_resource_type(self, name):
try:
with self.facade.writer() as session:
rt = self._get_resource_type(session, name)
if rt.state not in ["active", "deletion_error",
"creation_error", "updating_error"]:
raise indexer.UnexpectedResourceTypeState(
name,
"active/deletion_error/creation_error/updating_error",
rt.state)
session.delete(rt)
# FIXME(sileht): Why do I need to flush here !!!
# I want remove/add in the same transaction !!!
session.flush()
# NOTE(sileht): delete and recreate to:
# * raise duplicate constraints
# * ensure we do not create a new resource type
# with the same name while we destroy the tables next
rt = ResourceType(name=rt.name,
tablename=rt.tablename,
state="deleting",
attributes=rt.attributes)
session.add(rt)
except exception.DBReferenceError as e:
if (e.constraint in [
'fk_resource_resource_type_name',
'fk_resource_history_resource_type_name',
'fk_rh_resource_type_name']):
raise indexer.ResourceTypeInUse(name)
raise
return rt
示例11: delete_archive_policy
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def delete_archive_policy(self, name):
constraints = [
"fk_metric_ap_name_ap_name",
"fk_apr_ap_name_ap_name"]
with self.facade.writer() as session:
try:
if session.query(ArchivePolicy).filter(
ArchivePolicy.name == name).delete() == 0:
raise indexer.NoSuchArchivePolicy(name)
except exception.DBReferenceError as e:
if e.constraint in constraints:
raise indexer.ArchivePolicyInUse(name)
raise
示例12: create_resource
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def create_resource(self, resource_type, id,
creator, user_id=None, project_id=None,
started_at=None, ended_at=None, metrics=None,
original_resource_id=None,
**kwargs):
if (started_at is not None
and ended_at is not None
and started_at > ended_at):
raise ValueError(
"Start timestamp cannot be after end timestamp")
if original_resource_id is None:
original_resource_id = str(id)
with self.facade.writer() as session:
resource_cls = self._resource_type_to_mappers(
session, resource_type)['resource']
r = resource_cls(
id=id,
original_resource_id=original_resource_id,
type=resource_type,
creator=creator,
user_id=user_id,
project_id=project_id,
started_at=started_at,
ended_at=ended_at,
**kwargs)
session.add(r)
try:
session.flush()
except exception.DBDuplicateEntry:
raise indexer.ResourceAlreadyExists(id)
except exception.DBReferenceError as ex:
raise indexer.ResourceValueError(r.type,
ex.key,
getattr(r, ex.key))
if metrics is not None:
self._set_metrics_for_resource(session, r, metrics)
# NOTE(jd) Force load of metrics :)
r.metrics
return r
示例13: destroy_registry
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def destroy_registry(self, context, registry_uuid):
session = get_session()
with session.begin():
query = model_query(models.Registry, session=session)
query = add_identity_filter(query, registry_uuid)
try:
count = query.delete()
if count != 1:
raise exception.RegistryNotFound(registry=registry_uuid)
except db_exc.DBReferenceError:
raise exception.Conflict('Failed to delete registry '
'%(registry)s since it is in use.',
registry=registry_uuid)
示例14: delete
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def delete(self, availability_zone_name):
"""Deletes an Availability Zone"""
context = pecan_request.context.get('octavia_context')
self._auth_validate_action(context, context.project_id,
constants.RBAC_DELETE)
if availability_zone_name == constants.NIL_UUID:
raise exceptions.NotFound(resource='Availability Zone',
id=constants.NIL_UUID)
serial_session = db_api.get_session(autocommit=False)
serial_session.connection(
execution_options={'isolation_level': 'SERIALIZABLE'})
try:
self.repositories.availability_zone.delete(
serial_session, name=availability_zone_name)
serial_session.commit()
# Handle when load balancers still reference this availability_zone
except odb_exceptions.DBReferenceError:
serial_session.rollback()
raise exceptions.ObjectInUse(object='Availability Zone',
id=availability_zone_name)
except sa_exception.NoResultFound:
serial_session.rollback()
raise exceptions.NotFound(resource='Availability Zone',
id=availability_zone_name)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(
'Unknown availability_zone delete exception: %s', str(e))
serial_session.rollback()
finally:
serial_session.close()
示例15: delete
# 需要导入模块: from oslo_db import exception [as 别名]
# 或者: from oslo_db.exception import DBReferenceError [as 别名]
def delete(self, flavor_id):
"""Deletes a Flavor"""
context = pecan_request.context.get('octavia_context')
self._auth_validate_action(context, context.project_id,
constants.RBAC_DELETE)
if flavor_id == constants.NIL_UUID:
raise exceptions.NotFound(resource='Flavor', id=constants.NIL_UUID)
serial_session = db_api.get_session(autocommit=False)
serial_session.connection(
execution_options={'isolation_level': 'SERIALIZABLE'})
try:
self.repositories.flavor.delete(serial_session, id=flavor_id)
serial_session.commit()
# Handle when load balancers still reference this flavor
except odb_exceptions.DBReferenceError:
serial_session.rollback()
raise exceptions.ObjectInUse(object='Flavor', id=flavor_id)
except sa_exception.NoResultFound:
serial_session.rollback()
raise exceptions.NotFound(resource='Flavor', id=flavor_id)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error('Unknown flavor delete exception: %s', str(e))
serial_session.rollback()
finally:
serial_session.close()