本文整理匯總了Python中sqlalchemy.sql.expression.case方法的典型用法代碼示例。如果您正苦於以下問題:Python expression.case方法的具體用法?Python expression.case怎麽用?Python expression.case使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sqlalchemy.sql.expression
的用法示例。
在下文中一共展示了expression.case方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: touch_dids
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [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
示例2: get_count_of_expired_temporary_dids
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def get_count_of_expired_temporary_dids(rse_id, session=None):
"""
List expired temporary DIDs.
:param rse_id: the rse id.
:param session: The database session in use.
:returns: a count number.
"""
is_none = None
count = session.query(func.count(models.TemporaryDataIdentifier.scope)).\
with_hint(models.TemporaryDataIdentifier, "INDEX(tmp_dids TMP_DIDS_EXPIRED_AT_IDX)", 'oracle').\
filter(case([(models.TemporaryDataIdentifier.expired_at != is_none, models.TemporaryDataIdentifier.rse_id), ]) == rse_id).\
one()
return count[0] or 0
示例3: upgrade
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def upgrade():
# re-size existing data if necessary
identifier_map = table('cisco_csr_identifier_map',
column('ipsec_site_conn_id', sa.String(36)))
ipsec_site_conn_id = identifier_map.columns['ipsec_site_conn_id']
op.execute(identifier_map.update(values={
ipsec_site_conn_id: expr.case([(func.length(ipsec_site_conn_id) > 36,
func.substr(ipsec_site_conn_id, 1, 36))],
else_=ipsec_site_conn_id)}))
# Need to drop foreign key constraint before mysql will allow changes
with migration.remove_fks_from_table('cisco_csr_identifier_map'):
op.alter_column(table_name='cisco_csr_identifier_map',
column_name='ipsec_site_conn_id',
type_=sa.String(36),
existing_nullable=False)
示例4: full_name
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def full_name(cls):
"""
The person's commonly known full name, following naming order conventions.
If a person has a nickname, that name becomes the person's full name.
:return: Person's full name.
"""
return case(
[(cls.nick_name != None, cls.nick_name)],
else_=case(
[(cls.order == enums.NameOrderType.middle,
cls.first_name + ' ' + cls.middle_name + ' ' + cls.last_name),
(cls.order == enums.NameOrderType.eastern,
cls.last_name + ' ' + cls.first_name)],
else_=cls.first_name + ' ' + cls.last_name
))
示例5: update_replica_lock_counter
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def update_replica_lock_counter(rse_id, scope, name, value, session=None):
"""
Update File replica lock counters.
:param rse_id: The id of the RSE.
:param scope: the tag name.
:param name: The data identifier name.
:param value: The number of created/deleted locks.
:param session: The database session in use.
:returns: True or False.
"""
# WTF BUG in the mysql-driver: lock_cnt uses the already updated value! ACID? Never heard of it!
if session.bind.dialect.name == 'mysql':
rowcount = session.query(models.RSEFileAssociation).\
filter_by(rse_id=rse_id, scope=scope, name=name).\
update({'lock_cnt': models.RSEFileAssociation.lock_cnt + value,
'tombstone': case([(models.RSEFileAssociation.lock_cnt + value < 0,
datetime.utcnow()), ],
else_=None)},
synchronize_session=False)
else:
rowcount = session.query(models.RSEFileAssociation).\
filter_by(rse_id=rse_id, scope=scope, name=name).\
update({'lock_cnt': models.RSEFileAssociation.lock_cnt + value,
'tombstone': case([(models.RSEFileAssociation.lock_cnt + value == 0,
datetime.utcnow()), ],
else_=None)},
synchronize_session=False)
return bool(rowcount)
示例6: list_expired_temporary_dids
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def list_expired_temporary_dids(rse_id, limit, worker_number=None, total_workers=None,
session=None):
"""
List expired temporary DIDs.
:param rse_id: the rse id.
:param limit: The maximum number of replicas returned.
:param worker_number: id of the executing worker.
:param total_workers: Number of total workers.
:param session: The database session in use.
:returns: a list of dictionary replica.
"""
is_none = None
query = session.query(models.TemporaryDataIdentifier.scope,
models.TemporaryDataIdentifier.name,
models.TemporaryDataIdentifier.path,
models.TemporaryDataIdentifier.bytes).\
with_hint(models.TemporaryDataIdentifier, "INDEX(tmp_dids TMP_DIDS_EXPIRED_AT_IDX)", 'oracle').\
filter(case([(models.TemporaryDataIdentifier.expired_at != is_none, models.TemporaryDataIdentifier.rse_id), ]) == rse_id)
query = filter_thread_work(session=session, query=query, total_threads=total_workers, thread_id=worker_number, hash_variable='name')
return [{'path': path,
'rse_id': rse_id,
'scope': scope,
'name': name,
'bytes': bytes}
for scope, name, path, bytes in query.limit(limit)]
示例7: deprecated
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def deprecated(cls):
return case([(cls.name in BAD_CIPHERS, True)], else_=False)
示例8: expired
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def expired(cls):
return case([(cls.not_after <= arrow.utcnow(), True)], else_=False)
示例9: revoked
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def revoked(cls):
return case([(cls.status == "revoked", True)], else_=False)
示例10: has_private_key
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def has_private_key(cls):
return case([(cls.private_key.is_(None), True)], else_=False)
示例11: in_rotation_window
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def in_rotation_window(cls):
"""
Determines if a certificate is available for rotation based
on the rotation policy associated.
:return:
"""
return case(
[(extract("day", cls.not_after - func.now()) <= RotationPolicy.days, True)],
else_=False,
)
示例12: name
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def name(cls):
return case(
[(
and_(cls.last_name != None, cls.last_name != ""),
cls.last_name + " " + cls.first_name
)],
else_=cls.first_name
)
示例13: log_param
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def log_param(self, run_id, param):
with self.ManagedSessionMaker() as session:
run = self._get_run(run_uuid=run_id, session=session)
self._check_run_is_active(run)
# if we try to update the value of an existing param this will fail
# because it will try to create it with same run_uuid, param key
try:
# This will check for various integrity checks for params table.
# ToDo: Consider prior checks for null, type, param name validations, ... etc.
self._get_or_create(model=SqlParam, session=session, run_uuid=run_id,
key=param.key, value=param.value)
# Explicitly commit the session in order to catch potential integrity errors
# while maintaining the current managed session scope ("commit" checks that
# a transaction satisfies uniqueness constraints and throws integrity errors
# when they are violated; "get_or_create()" does not perform these checks). It is
# important that we maintain the same session scope because, in the case of
# an integrity error, we want to examine the uniqueness of parameter values using
# the same database state that the session uses during "commit". Creating a new
# session synchronizes the state with the database. As a result, if the conflicting
# parameter value were to be removed prior to the creation of a new session,
# we would be unable to determine the cause of failure for the first session's
# "commit" operation.
session.commit()
except sqlalchemy.exc.IntegrityError:
# Roll back the current session to make it usable for further transactions. In the
# event of an error during "commit", a rollback is required in order to continue
# using the session. In this case, we re-use the session because the SqlRun, `run`,
# is lazily evaluated during the invocation of `run.params`.
session.rollback()
existing_params = [p.value for p in run.params if p.key == param.key]
if len(existing_params) > 0:
old_value = existing_params[0]
raise MlflowException(
"Changing param values is not allowed. Param with key='{}' was already"
" logged with value='{}' for run ID='{}'. Attempted logging new value"
" '{}'.".format(
param.key, old_value, run_id, param.value), INVALID_PARAMETER_VALUE)
else:
raise
示例14: list_rebalance_rule_candidates
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def list_rebalance_rule_candidates(rse, mode=None, session=None):
"""
List the rebalance rule candidates based on the agreed on specification
:param rse: RSE of the source.
:param mode: Rebalancing mode.
:param session: DB Session.
"""
rse_id = get_rse_id(rse)
# dumps can be applied only for decommission since the dumps doesn't contain info from dids
if mode == 'decommission':
return _list_rebalance_rule_candidates_dump(rse, mode)
# the rest is done with sql query
from_date = datetime.utcnow() + timedelta(days=60)
to_date = datetime.now() - timedelta(days=60)
allowed_accounts = [InternalAccount(a) for a in ('panda', 'root', 'ddmadmin')]
allowed_grouping = [RuleGrouping.DATASET, RuleGrouping.ALL]
external_dsl = aliased(models.DatasetLock)
count_locks = select([func.count()]).where(and_(external_dsl.scope == models.DatasetLock.scope,
external_dsl.name == models.DatasetLock.name,
external_dsl.rse_id == models.DatasetLock.rse_id)).as_scalar()
query = session.query(models.DatasetLock.scope,
models.DatasetLock.name,
models.ReplicationRule.id,
models.ReplicationRule.rse_expression,
models.ReplicationRule.subscription_id,
models.DataIdentifier.bytes,
models.DataIdentifier.length,
case([(or_(models.DatasetLock.length < 1, models.DatasetLock.length.is_(None)), 0)],
else_=cast(models.DatasetLock.bytes / models.DatasetLock.length, Integer))).\
join(models.ReplicationRule, models.ReplicationRule.id == models.DatasetLock.rule_id).\
join(models.DataIdentifier, and_(models.DatasetLock.scope == models.DataIdentifier.scope, models.DatasetLock.name == models.DataIdentifier.name)).\
filter(models.DatasetLock.rse_id == rse_id).\
filter(or_(models.ReplicationRule.expires_at > from_date, models.ReplicationRule.expires_at.is_(None))).\
filter(models.ReplicationRule.created_at < to_date).\
filter(models.ReplicationRule.account.in_(allowed_accounts)).\
filter(models.ReplicationRule.state == RuleState.OK).\
filter(models.ReplicationRule.did_type == DIDType.DATASET).\
filter(models.ReplicationRule.copies == 1).\
filter(models.ReplicationRule.child_rule_id.is_(None)).\
filter(models.ReplicationRule.grouping.in_(allowed_grouping)).\
filter(models.DataIdentifier.bytes.isnot(None)).\
filter(models.DataIdentifier.is_open == 0).\
filter(models.DataIdentifier.did_type == DIDType.DATASET).\
filter(case([(or_(models.DatasetLock.length < 1, models.DatasetLock.length.is_(None)), 0)],
else_=cast(models.DatasetLock.bytes / models.DatasetLock.length, Integer)) > 1000000000).\
filter(count_locks == 1)
summary = query.order_by(case([(or_(models.DatasetLock.length < 1, models.DatasetLock.length.is_(None)), 0)],
else_=cast(models.DatasetLock.bytes / models.DatasetLock.length, Integer)),
models.DatasetLock.accessed_at).all()
return summary
示例15: list_unlocked_replicas
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import case [as 別名]
def list_unlocked_replicas(rse_id, limit, bytes=None, worker_number=None, total_workers=None, delay_seconds=0, session=None):
"""
List RSE File replicas with no locks.
:param rse_id: the rse id.
:param bytes: the amount of needed bytes.
:param session: The database session in use.
:returns: a list of dictionary replica.
"""
# filter(models.RSEFileAssociation.state != ReplicaState.BEING_DELETED).\
none_value = None # Hack to get pep8 happy...
query = session.query(models.RSEFileAssociation.scope, models.RSEFileAssociation.name, models.RSEFileAssociation.path, models.RSEFileAssociation.bytes, models.RSEFileAssociation.tombstone, models.RSEFileAssociation.state).\
with_hint(models.RSEFileAssociation, "INDEX_RS_ASC(replicas REPLICAS_TOMBSTONE_IDX) NO_INDEX_FFS(replicas REPLICAS_TOMBSTONE_IDX)", 'oracle').\
filter(models.RSEFileAssociation.tombstone < datetime.utcnow()).\
filter(models.RSEFileAssociation.lock_cnt == 0).\
filter(case([(models.RSEFileAssociation.tombstone != none_value, models.RSEFileAssociation.rse_id), ]) == rse_id).\
filter(or_(models.RSEFileAssociation.state.in_((ReplicaState.AVAILABLE, ReplicaState.UNAVAILABLE, ReplicaState.BAD)),
and_(models.RSEFileAssociation.state == ReplicaState.BEING_DELETED, models.RSEFileAssociation.updated_at < datetime.utcnow() - timedelta(seconds=delay_seconds)))).\
order_by(models.RSEFileAssociation.tombstone)
# do no delete files used as sources
stmt = exists(select([1]).prefix_with("/*+ INDEX(requests REQUESTS_SCOPE_NAME_RSE_IDX) */", dialect='oracle')).\
where(and_(models.RSEFileAssociation.scope == models.Request.scope,
models.RSEFileAssociation.name == models.Request.name))
query = query.filter(not_(stmt))
query = filter_thread_work(session=session, query=query, total_threads=total_workers, thread_id=worker_number, hash_variable='name')
needed_space = bytes
total_bytes, total_files = 0, 0
rows = []
for (scope, name, path, bytes, tombstone, state) in query.yield_per(1000):
if state != ReplicaState.UNAVAILABLE:
if tombstone != OBSOLETE and needed_space is not None and total_bytes > needed_space:
break
total_bytes += bytes
total_files += 1
if total_files > limit:
break
rows.append({'scope': scope, 'name': name, 'path': path,
'bytes': bytes, 'tombstone': tombstone,
'state': state})
return rows