本文整理汇总了Python中sqlalchemy.sql.func.max方法的典型用法代码示例。如果您正苦于以下问题:Python func.max方法的具体用法?Python func.max怎么用?Python func.max使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.sql.func
的用法示例。
在下文中一共展示了func.max方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_max_tracking_record_id
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def get_max_tracking_record_id(self, upstream_application_name: str) -> int:
assert self.tracking_record_class is not None
application_name_field = (
self.tracking_record_class.application_name # type: ignore
)
upstream_app_name_field = (
self.tracking_record_class.upstream_application_name # type: ignore
)
pipeline_id_field = self.tracking_record_class.pipeline_id # type: ignore
notification_id_field = (
self.tracking_record_class.notification_id # type: ignore
)
query = self.session.query(func.max(notification_id_field))
query = query.filter(application_name_field == self.application_name)
query = query.filter(upstream_app_name_field == upstream_application_name)
query = query.filter(pipeline_id_field == self.pipeline_id)
value = query.scalar() or 0
return value
示例2: load
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def load(cls, db, **kwargs):
start_time = time.time()
session = db.session
q = session.query(
Shape.shape_id,
func.max(Shape.shape_dist_traveled).label('dist')
)
shapes = q.group_by(Shape.shape_id)
for shape in shapes:
pattern = cls()
pattern.shape_id = shape.shape_id
pattern.pattern_dist = shape.dist
if hasattr(cls, 'geom'):
q = session.query(Shape)
q = q.filter(Shape.shape_id == shape.shape_id)
q = q.order_by(Shape.shape_pt_sequence)
pattern.geom_from_shape(q)
session.add(pattern)
session.commit()
session.close()
processing_time = time.time() - start_time
log.debug('{0}.load ({1:.0f} seconds)'.format(cls.__name__, processing_time))
示例3: test_timezone_insert
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def test_timezone_insert(session):
"""Timezone 001: Insert timezone records into Timezones table and verify data."""
timezones = [
mco.Timezones(name=u"Europe/Paris", offset=1, confederation=enums.ConfederationType.europe),
mco.Timezones(name=u"America/New_York", offset=-5.0, confederation=enums.ConfederationType.north_america),
mco.Timezones(name=u"Asia/Kathmandu", offset=+5.75, confederation=enums.ConfederationType.asia)
]
session.add_all(timezones)
tz_uefa = session.query(mco.Timezones).filter_by(confederation=enums.ConfederationType.europe).one()
assert repr(tz_uefa) == "<Timezone(name=Europe/Paris, offset=+1.00, confederation=UEFA)>"
stmt = session.query(func.min(mco.Timezones.offset).label('far_west')).subquery()
tz_farwest = session.query(mco.Timezones).filter(mco.Timezones.offset == stmt.c.far_west).one()
assert repr(tz_farwest) == "<Timezone(name=America/New_York, offset=-5.00, confederation=CONCACAF)>"
stmt = session.query(func.max(mco.Timezones.offset).label('far_east')).subquery()
tz_fareast = session.query(mco.Timezones).filter(mco.Timezones.offset == stmt.c.far_east).one()
assert repr(tz_fareast) == "<Timezone(name=Asia/Kathmandu, offset=+5.75, confederation=AFC)>"
示例4: stats
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def stats(self, survey_id):
"""Get stats for a survey."""
result = (
self.session
.query(
func.max(Survey.created_on),
func.min(Submission.save_time),
func.max(Submission.save_time),
func.count(Submission.id),
)
.select_from(Submission)
.join(Survey)
# TODO: ask @jmwohl what this line is supposed to do
# .filter(User.id == self.current_user_model.id)
.filter(Submission.survey_id == survey_id)
.one()
)
response = {
"created_on": result[0],
"earliest_submission_time": result[1],
"latest_submission_time": result[2],
"num_submissions": result[3]
}
return response
示例5: _calculate_date_range
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def _calculate_date_range(self):
"""
The date range is the range of publication dates for the given
documents.
"""
if not self.start_date or not self.end_date:
if self.doc_ids is None:
raise ValueError("Need either doc_ids, or both start_date and end_date")
row = db.session.query(
func.min(Document.published_at),
func.max(Document.published_at))\
.filter(Document.id.in_(self.doc_ids))\
.first()
if row and row[0]:
self.start_date = row[0].date()
self.end_date = row[1].date()
else:
self.start_date = self.end_date = datetime.utcnow()
self.days = max((self.end_date - self.start_date).days, 1)
示例6: _set_transaction_pointers
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def _set_transaction_pointers(self):
for key in engine_manager.engines:
with session_scope_by_shard_id(key) as db_session:
pointer = db_session.query(
ContactSearchIndexCursor).first()
if pointer:
self.transaction_pointers[key] = pointer.transaction_id
else:
# Never start from 0; if the service hasn't run before
# start from the latest transaction, with the expectation
# that a backfill will be run separately.
max_id = db_session.query(
func.max(Transaction.id)).scalar() or 0
latest_transaction = \
db_session.query(Transaction).get(max_id)
if latest_transaction:
self.transaction_pointers[
key] = latest_transaction.id
else:
self.transaction_pointers[key] = 0
示例7: get_max_group_id
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def get_max_group_id(self, session):
"""Return the maximumn group_id of table `article`.
Parameters
----------
session : object
A SQLAlchemy Session instance.
Returns
-------
int
The maximum group_id of table `article`.
"""
group_id = session.query(func.max(Article.group_id)).scalar()
return group_id if group_id is not None else 0
示例8: __init__
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def __init__(self, protocolId):
self.protocolId = protocolId # maybe search through database to find max value and +1
# initializing all the lists with default sizes make things easier later
self.preambleSize = [0, 0]
self.arbPreambleList = []
self.pwmOneSymbol = [0, 0]
self.pwmZeroSymbol = [0, 0]
self.pwmOneSymbol_samp = [0, 0]
self.pwmZeroSymbol_samp = [0, 0]
self.crcFinalXor = []
self.crcPadCountOptions = []
self.crcPoly = []
self.idAddr = []
for i in xrange(wcv.NUM_ID_FIELDS):
self.idAddr.append([0, 0])
self.valAddr = []
for i in xrange(wcv.NUM_VAL_FIELDS):
self.valAddr.append([0, 0])
self.crcAddr = []
self.crcData = []
for i in xrange(wcv.NUM_CRC):
self.crcAddr.append([0, 0])
self.crcData.append([0, 0])
self.acsInitSum = []
self.acsAddr = []
self.acsData = []
for i in xrange(wcv.NUM_ACS):
self.acsInitSum.append(0)
self.acsAddr.append([0, 0])
self.acsData.append([0, 0])
# the rest of the features must be generated manually
示例9: convertTimingToSamples
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def convertTimingToSamples(self, basebandSampleRateIn):
if self.bb_samp_rate > 0:
basebandSampleRate = self.bb_samp_rate
else:
basebandSampleRate = wcv.basebandSampleRate
#microsecondsPerSample = 1000000.0/samp_rate
samplesPerMicrosecond = basebandSampleRate/1000000.0
self.unitWidth_samp = int(self.unitWidth * samplesPerMicrosecond)
self.interPacketWidth_samp = int(self.interPacketWidth * samplesPerMicrosecond)
self.preambleSymbolLow_samp = int(self.preambleSymbolLow * samplesPerMicrosecond)
self.preambleSymbolHigh_samp = int(self.preambleSymbolHigh * samplesPerMicrosecond)
self.headerWidth_samp = int(self.headerWidth * samplesPerMicrosecond)
self.pwmOneSymbol_samp[0] = int(self.pwmOneSymbol[0] * samplesPerMicrosecond)
self.pwmOneSymbol_samp[1] = int(self.pwmOneSymbol[1] * samplesPerMicrosecond)
self.pwmZeroSymbol_samp[0] = int(self.pwmZeroSymbol[0] * samplesPerMicrosecond)
self.pwmZeroSymbol_samp[1] = int(self.pwmZeroSymbol[1] * samplesPerMicrosecond)
self.pwmSymbolSize_samp = sum(self.pwmOneSymbol_samp)
newArbList = []
for timingVal in self.arbPreambleList:
newArbList.append(int(timingVal * samplesPerMicrosecond))
self.arbPreambleList_samp = newArbList
return(0)
# this produces the max legal duration (in samples) of a signal level equal to zero
# we'll use this to distinguish between a legal zero level within a transmission
# and the inter-packet dead air
示例10: maxZeroTimeInTx
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def maxZeroTimeInTx(self):
if self.encodingType == 3: # PWM
maxSize = (wcv.timingError + 0.05) * max([self.headerWidth_samp, self.preambleSymbolLow_samp, self.pwmSymbolSize_samp])
else:
maxSize = (wcv.timingError + 0.05) * max([self.headerWidth_samp, self.preambleSymbolLow_samp, self.unitWidth_samp * 2])
return(int(maxSize))
# sqlalchemy needs this after database class declaration
#if not wcv.argcHelp:
示例11: getNextProtocolId
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def getNextProtocolId():
global protocolSession
query = protocolSession.query(func.max(ProtocolDefinition.protocolId).label("maxId"))
try:
return query.one().maxId + 1 # if table is not empty
except:
return 1 # if table is empty
# - return size of library (number of protocol definitions)
示例12: _prepare_insert
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def _prepare_insert(
self,
tmpl: Any,
record_class: type,
field_names: List[str],
placeholder_for_id: bool = False,
) -> Any:
"""
With transaction isolation level of "read committed" this should
generate records with a contiguous sequence of integer IDs, assumes
an indexed ID column, the database-side SQL max function, the
insert-select-from form, and optimistic concurrency control.
"""
statement = super()._prepare_insert(
tmpl, record_class, field_names, placeholder_for_id
)
statement = text(statement)
# Define bind parameters with explicit types taken from record column types.
bindparams = []
for col_name in field_names:
column_type = getattr(record_class, col_name).type
bindparams.append(bindparam(col_name, type_=column_type))
# Redefine statement with explicitly typed bind parameters.
statement = statement.bindparams(*bindparams)
return statement
示例13: get_max_notification_id
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def get_max_notification_id(self) -> int:
try:
notification_id_col = getattr(self.record_class, self.notification_id_name)
query = self.session.query(func.max(notification_id_col))
query = self.filter_for_application_name(query)
query = self.filter_for_pipeline_id(query)
return query.scalar() or 0
finally:
self.session.close()
示例14: apply_ca_filters
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def apply_ca_filters(query, filters, user_join_condition):
# get all custom attributes and create pivot table
new_cs = [CustomAttributeUserStorage.user_id]
for value in db.session.query(CustomAttributeUserStorage.name).distinct():
value = value[0]
new_cs.append(
func.max(case(
[(CustomAttributeUserStorage.name == value, CustomAttributeUserStorage.value)],
else_=None
)).label(value)
)
# join pivot table of custom attributes
pivot = db.session.query(*new_cs).group_by(CustomAttributeUserStorage.user_id).subquery()
query = query.outerjoin(pivot, user_join_condition == pivot.c.user_id)
for batches in filters:
to_batch = []
for _filt in batches:
column = _filt[0]
comparator = _filt[1]
val = _filt[2]
if comparator == 'EQ':
val = val if isinstance(val, list) else [val]
val = [f'\"{element}\"' for element in val] # needs ot be in form '"{item}"' for json string match
to_batch.append(pivot.c[column].in_(val))
elif comparator == 'GT':
to_batch.append(pivot.c[column] > val)
elif comparator == "LT":
to_batch.append(pivot.c[column] < val)
query = query.filter(or_(*to_batch))
return query
示例15: test_greatest_right_is_always_double_number_of_nodes
# 需要导入模块: from sqlalchemy.sql import func [as 别名]
# 或者: from sqlalchemy.sql.func import max [as 别名]
def test_greatest_right_is_always_double_number_of_nodes(self):
""" The greatest right key is always double the number of nodes.
The following example should match COUNT(id) * 2 equal MAX(right).
.. code-block:: sql
SELECT COUNT(id), MAX(right) FROM tree
"""
table = self.model
result = self.session.query(
func.count(table.get_pk_name()),
func.max(table.right)).group_by(table.tree_id).all()
for tree in result:
self.assertEqual(tree[0] * 2, tree[1])