本文整理汇总了Python中sqlalchemy.exc.DatabaseError方法的典型用法代码示例。如果您正苦于以下问题:Python exc.DatabaseError方法的具体用法?Python exc.DatabaseError怎么用?Python exc.DatabaseError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.exc
的用法示例。
在下文中一共展示了exc.DatabaseError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: touch_collection_replicas
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def touch_collection_replicas(collection_replicas, session=None):
"""
Update the accessed_at timestamp of the given collection replicas.
:param collection_replicas: the list of collection replicas.
:param session: The database session in use.
:returns: True, if successful, False otherwise.
"""
now = datetime.utcnow()
for collection_replica in collection_replicas:
try:
session.query(models.CollectionReplica).filter_by(scope=collection_replica['scope'], name=collection_replica['name'], rse_id=collection_replica['rse_id']).\
update({'accessed_at': collection_replica.get('accessed_at') or now}, synchronize_session=False)
except DatabaseError:
return False
return True
示例2: touch_dids
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def touch_dids(dids, session=None):
"""
Update the accessed_at timestamp and the access_cnt of the given dids.
:param replicas: the list of dids.
:param session: The database session in use.
:returns: True, if successful, False otherwise.
"""
now = datetime.utcnow()
none_value = None
try:
for did in dids:
session.query(models.DataIdentifier).\
filter_by(scope=did['scope'], name=did['name'], did_type=did['type']).\
update({'accessed_at': did.get('accessed_at') or now,
'access_cnt': case([(models.DataIdentifier.access_cnt == none_value, 1)],
else_=(models.DataIdentifier.access_cnt + 1))},
synchronize_session=False)
except DatabaseError:
return False
return True
示例3: checkInputDb
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def checkInputDb(inputfile):
try:
engine = create_engine('sqlite:///%s' % inputfile, echo=True)
except exc.DatabaseError:
logging.error(sys.exc_info()[0])
return -2
metadata = MetaData(bind=engine)
try:
table = Table('ledger', metadata, autoload=True)
table = Table('sub_ledger', metadata, autoload=True)
table = Table('moin', metadata, autoload=True)
except exc.DatabaseError:
logging.error(sys.exc_info()[0])
return -2
except exc.NoSuchTableError:
return -1
return 0
示例4: get_notification
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def get_notification(self, notification_id):
try:
with self._orm_engine.connect() as conn:
LOG.debug('Orm query {%s}', str(self._orm_get_notification))
result = conn.execute(self._orm_get_notification,
notification_id=notification_id)
notification = result.fetchone()
if notification is None:
return None
else:
return [
notification[0],
notification[1].lower(),
notification[2],
notification[3]]
except DatabaseError as e:
LOG.exception("Couldn't fetch the notification method %s", e)
raise exc.DatabaseException(e)
示例5: test_tostring_with_newlines
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def test_tostring_with_newlines(self):
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message\nthis is the next line\nthe last line",
None,
OperationalError(),
DatabaseError,
)
except sa_exceptions.DBAPIError as exc:
eq_(
str(exc),
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message\nthis is the next line\n"
"the last line]\n"
"(Background on this error at: http://sqlalche.me/e/%s/e3q8)"
% sa_exceptions._version_token,
)
示例6: test_statement_error_w_code
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def test_statement_error_w_code(self):
try:
raise sa_exceptions.DBAPIError.instance(
"select * from table",
[{"x": 1}],
sa_exceptions.InvalidRequestError("hello", code="abcd"),
DatabaseError,
)
except sa_exceptions.StatementError as err:
eq_(
str(err),
"(sqlalchemy.exc.InvalidRequestError) hello\n"
"[SQL: select * from table]\n"
"[parameters: [{'x': 1}]]\n"
"(Background on this error at: http://sqlalche.me/e/%s/abcd)"
% sa_exceptions._version_token,
)
eq_(err.args, ("(sqlalchemy.exc.InvalidRequestError) hello",))
示例7: test_outer_joinedload_w_limit
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def test_outer_joinedload_w_limit(self):
User = self.classes.User
sess = Session()
q = sess.query(User).options(
joinedload(User.addresses, innerjoin=False)
)
if testing.against("postgresql"):
q = q.with_for_update(of=User)
else:
q = q.with_for_update()
q = q.limit(1)
if testing.against("oracle"):
assert_raises_message(exc.DatabaseError, "ORA-02014", q.all)
else:
q.all()
sess.close()
示例8: validation_key_validate
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def validation_key_validate(key):
"""
Verify if a validation key is valid
"""
# validation key from database
try:
user = get_session().query(UserModel).filter(
UserModel.key == 'key_validation').order_by(UserModel.id.desc()).first()
except exc.DatabaseError: # In case of encrypted db, if the encryption key is invalid
# Drop db sessions to force a re-connection with the new key
drop_sessions()
return False
# Concatenate user given key and config's salt
key_salt = key + global_scope['conf'].salt.encode()
# Key is valid
try:
if global_scope['enc'].decrypt(user.value) == key_salt:
return True
except ValueError: # Decryption error
return False
return False
示例9: _ora_drop_ignore
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def _ora_drop_ignore(conn, dbname):
try:
conn.execute("drop user %s cascade" % dbname)
log.info("Reaped db: %s", dbname)
return True
except exc.DatabaseError as err:
log.warning("couldn't drop db: %s", err)
return False
示例10: _ora_drop_ignore
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def _ora_drop_ignore(conn, dbname):
try:
conn.execute("drop user %s cascade" % dbname)
log.info("Reaped db: %s" % dbname)
return True
except exc.DatabaseError as err:
log.warn("couldn't drop db: %s" % err)
return False
示例11: read_session
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def read_session(function):
'''
decorator that set the session variable to use inside a function.
With that decorator it's possible to use the session variable like if a global variable session is declared.
session is a sqlalchemy session, and you can get one calling get_session().
This is useful if only SELECTs and the like are being done; anything involving
INSERTs, UPDATEs etc should use transactional_session.
'''
@retry(retry_on_exception=retry_if_db_connection_error,
wait_fixed=500,
stop_max_attempt_number=2,
wrap_exception=False)
@wraps(function)
def new_funct(*args, **kwargs):
if isgeneratorfunction(function):
raise RucioException('read_session decorator should not be used with generator. Use stream_session instead.')
if not kwargs.get('session'):
session = get_session()
try:
kwargs['session'] = session
return function(*args, **kwargs)
except TimeoutError as error:
session.rollback() # pylint: disable=maybe-no-member
raise DatabaseException(str(error))
except DatabaseError as error:
session.rollback() # pylint: disable=maybe-no-member
raise DatabaseException(str(error))
except:
session.rollback() # pylint: disable=maybe-no-member
raise
finally:
session.remove()
try:
return function(*args, **kwargs)
except:
raise
new_funct.__doc__ = function.__doc__
return new_funct
示例12: transactional_session
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def transactional_session(function):
'''
decorator that set the session variable to use inside a function.
With that decorator it's possible to use the session variable like if a global variable session is declared.
session is a sqlalchemy session, and you can get one calling get_session().
'''
@wraps(function)
def new_funct(*args, **kwargs):
if not kwargs.get('session'):
session = get_session()
try:
kwargs['session'] = session
result = function(*args, **kwargs)
session.commit() # pylint: disable=maybe-no-member
except TimeoutError as error:
print(error)
session.rollback() # pylint: disable=maybe-no-member
raise DatabaseException(str(error))
except DatabaseError as error:
print(error)
session.rollback() # pylint: disable=maybe-no-member
raise DatabaseException(str(error))
except:
session.rollback() # pylint: disable=maybe-no-member
raise
finally:
session.remove() # pylint: disable=maybe-no-member
else:
result = function(*args, **kwargs)
return result
new_funct.__doc__ = function.__doc__
return new_funct
示例13: __handle_terminated_replicas
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def __handle_terminated_replicas(replicas, prepend_str=''):
"""
Used by finisher to handle available and unavailable replicas.
:param replicas: List of replicas.
:param prepend_str: String to prepend to logging.
"""
for req_type in replicas:
for rule_id in replicas[req_type]:
try:
__update_bulk_replicas(replicas[req_type][rule_id])
except (UnsupportedOperation, ReplicaNotFound):
# one replica in the bulk cannot be found. register it one by one
logging.warn('%s Problem to bulk update the replicas states. Will try one by one', prepend_str)
for replica in replicas[req_type][rule_id]:
try:
__update_replica(replica)
except (DatabaseException, DatabaseError) as error:
if re.match('.*ORA-00054.*', error.args[0]) or re.match('.*ORA-00060.*', error.args[0]) or 'ERROR 1205 (HY000)' in error.args[0]:
logging.warn("%s Locks detected when handling replica %s:%s at RSE %s", prepend_str, replica['scope'], replica['name'], replica['rse_id'])
else:
logging.error("%s Could not finish handling replicas %s:%s at RSE %s (%s)", prepend_str, replica['scope'], replica['name'], replica['rse_id'], traceback.format_exc())
except Exception as error:
logging.error("%s Something unexpected happened when updating replica state for transfer %s:%s at %s (%s)", prepend_str, replica['scope'], replica['name'], replica['rse_id'], str(error))
except (DatabaseException, DatabaseError) as error:
if re.match('.*ORA-00054.*', error.args[0]) or re.match('.*ORA-00060.*', error.args[0]) or 'ERROR 1205 (HY000)' in error.args[0]:
logging.warn("%s Locks detected when handling replicas on %s rule %s, update updated time.", prepend_str, req_type, rule_id)
try:
request_core.touch_requests_by_rule(rule_id)
except (DatabaseException, DatabaseError):
logging.error("%s Failed to touch requests by rule(%s): %s", prepend_str, rule_id, traceback.format_exc())
else:
logging.error("%s Could not finish handling replicas on %s rule %s: %s", prepend_str, req_type, rule_id, traceback.format_exc())
except Exception as error:
logging.error("%s Something unexpected happened when handling replicas on %s rule %s: %s", prepend_str, req_type, rule_id, str(error))
示例14: __bulk_add_new_file_dids
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def __bulk_add_new_file_dids(files, account, dataset_meta=None, session=None):
"""
Bulk add new dids.
:param dids: the list of new files.
:param account: The account owner.
:param session: The database session in use.
:returns: True is successful.
"""
for file in files:
new_did = models.DataIdentifier(scope=file['scope'], name=file['name'],
account=file.get('account') or account,
did_type=DIDType.FILE, bytes=file['bytes'],
md5=file.get('md5'), adler32=file.get('adler32'),
is_new=None)
for key in file.get('meta', []):
new_did.update({key: file['meta'][key]})
for key in dataset_meta or {}:
new_did.update({key: dataset_meta[key]})
new_did.save(session=session, flush=False)
try:
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)
except DatabaseError as error:
raise exception.RucioException(error.args)
except FlushError as error:
if match('New instance .* with identity key .* conflicts with persistent instance', error.args[0]):
raise exception.DataIdentifierAlreadyExists('Data Identifier already exists!')
raise exception.RucioException(error.args)
return True
示例15: add_bad_pfns
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DatabaseError [as 别名]
def add_bad_pfns(pfns, account, state, reason=None, expires_at=None, session=None):
"""
Add bad PFNs.
:param pfns: the list of new files.
:param account: The account who declared the bad replicas.
:param state: One of the possible states : BAD, SUSPICIOUS, TEMPORARY_UNAVAILABLE.
:param reason: A string describing the reason of the loss.
:param expires_at: Specify a timeout for the TEMPORARY_UNAVAILABLE replicas. None for BAD files.
:param session: The database session in use.
:returns: True is successful.
"""
if isinstance(state, string_types):
rep_state = BadPFNStatus.from_sym(state)
else:
rep_state = state
pfns = clean_surls(pfns)
for pfn in pfns:
new_pfn = models.BadPFNs(path=str(pfn), account=account, state=rep_state, reason=reason, expires_at=expires_at)
new_pfn = session.merge(new_pfn)
new_pfn.save(session=session, flush=False)
try:
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)
except DatabaseError as error:
raise exception.RucioException(error.args)
except FlushError as error:
if match('New instance .* with identity key .* conflicts with persistent instance', error.args[0]):
raise exception.Duplicate('One PFN already exists!')
raise exception.RucioException(error.args)
return True