本文整理匯總了Python中sqlalchemy.sql.expression.cast方法的典型用法代碼示例。如果您正苦於以下問題:Python expression.cast方法的具體用法?Python expression.cast怎麽用?Python expression.cast使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sqlalchemy.sql.expression
的用法示例。
在下文中一共展示了expression.cast方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: preprocess_column_and_value
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def preprocess_column_and_value(self):
""" Preprocess the column and the value
Certain operations will only work if the types are cast correctly.
This is where it happens.
"""
col, val = self.column, self.value
# Case 1. Both column and value are arrays
if self.is_column_array() and self.is_value_array():
# Cast the value to ARRAY[] with the same type that the column has
# Only in this case Postgres will be able to handles them both
val = cast(pg.array(val), pg.ARRAY(col.type.item_type))
# Case 2. JSON column
if self.is_column_json():
# This is the type to which JSON column is coerced: same as `value`
# Doc: "Suggest a type for a `coerced` Python value in an expression."
coerce_type = col.type.coerce_compared_value('=', val) # HACKY: use sqlalchemy type coercion
# Now, replace the `col` used in operations with this new coerced expression
col = cast(col, coerce_type)
# Done
self.column_expression = col
self.value_expression = val
示例2: compile
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def compile(self):
# Json column?
if self.is_column_json:
# PostgreSQL always returns text values from it, and for aggregation we usually need numbers :)
column = cast(self.column, Float)
else:
# Simply use
column = self.column
# Now, handle the operator, and apply it to the expression
if self.operator == '$max':
stmt = func.max(column)
elif self.operator == '$min':
stmt = func.min(column)
elif self.operator == '$avg':
stmt = func.avg(column)
elif self.operator == '$sum':
stmt = func.sum(column)
else:
raise InvalidQueryError('Aggregate: unsupported operator "{}"'.format(self.operator))
return self.labeled_expression(stmt)
示例3: _serialize_and_update_indexes
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def _serialize_and_update_indexes(self,obj,collection,d,for_update = False):
pk_type = self._index_fields[collection]['pk']['type']
for index_field,index_params in self._index_fields[collection].items():
try:
if for_update:
value = obj[index_field]
else:
value = get_value(obj,index_field)
if value is None:
if not index_params['field'].nullable:
raise ValueError("Value for %s is `None`, but this is a mandatory field!" % index_field)
d[index_params['column']] = null()
else:
d[index_params['column']] = expression.cast(value,index_params['type'])
except KeyError:
if for_update:
continue
if index_params['field'].default is not None:
d[index_params['column']] = index_params['field'].default
elif not index_params['field'].nullable:
raise ValueError("No value for %s given, but this is a mandatory field!" % index_field)
else:
d[index_params['column']] = null()
示例4: test_paginate_with_boolean_sort
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def test_paginate_with_boolean_sort(self):
s = Session()
q = s.query(FakeTable)
q = utils.paginate_query(q, FakeTable, 5, ['enabled'],
sort_dirs=['asc'],
marker=FakeTable(user_id='hello',
enabled=False))
expected_core_sql = (
select([FakeTable]).
order_by(sqlalchemy.asc(FakeTable.enabled)).
where(cast(FakeTable.enabled, Integer) > 0).
limit(5)
)
self.assertEqual(
str(expected_core_sql.compile()),
str(q.statement.compile())
)
示例5: chosen
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def chosen(self):
"""Retrieve chosen via property1."""
return cast(self.property1, Boolean)
示例6: generation
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def generation(self):
"""Make generation queryable."""
return cast(self.property2, Integer)
示例7: score
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def score(self):
"""Make score queryable."""
return cast(self.property3, Integer)
示例8: proportion
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def proportion(self):
"""Make proportion queryable."""
return cast(self.property4, Float)
示例9: generation
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def generation(self):
"""Make generation queryable."""
from sqlalchemy import Integer
from sqlalchemy.sql.expression import cast
return cast(self.property2, Integer)
示例10: age
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def age(cls, reference):
"""
Person's age relative to a reference date.
:param reference: Date object of reference date.
:return: Integer value of person's age.
"""
return cast((reference - cls.birth_date)/365.25 - 0.5, Integer)
示例11: get_queryset
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def get_queryset(self,*args,**kwargs):
if self._queryset is None:
relationship_table = self.params['relationship_table']
foreign_table = self.obj.backend.get_collection_table(self.params['collection'])
condition = relationship_table.c[self.params['pk_field_name']] \
== expression.cast(self.obj.pk,self.params['type'])
self._queryset = QuerySet(backend = self.obj.backend,
table = foreign_table,
cls = self.params['class'],
joins = [(relationship_table,)],
condition = condition,
objects = self._objects,
*args,
**kwargs)
return self._queryset
示例12: get_tiles_by_quadkey
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def get_tiles_by_quadkey(prediction_id: int, quadkeys: tuple, zoom: int):
return db.session.query(func.substr(PredictionTile.quadkey, 1, zoom).label('qaudkey'),
func.avg(cast(cast(PredictionTile.predictions['ml_prediction'], sqlalchemy.String),
sqlalchemy.Float)).label('ml_prediction'),
func.avg(cast(cast(PredictionTile.predictions['osm_building_area'], sqlalchemy.String),
sqlalchemy.Float)).label('osm_building_area')).filter(PredictionTile.prediction_id == prediction_id).filter(
func.substr(
PredictionTile.quadkey, 1, zoom).in_(quadkeys)).group_by(func.substr(PredictionTile.quadkey, 1, zoom)).all()
示例13: get_aggregate_for_polygon
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def get_aggregate_for_polygon(prediction_id: int, polygon: str):
return db.session.query(func.avg(cast(cast(PredictionTile.predictions['ml_prediction'], sqlalchemy.String), sqlalchemy.Float)).label('ml_prediction'),
func.avg(cast(cast(PredictionTile.predictions['osm_building_area'],
sqlalchemy.String), sqlalchemy.Float)).label('osm_building_area')).filter(
PredictionTile.prediction_id == prediction_id).filter(ST_Within(PredictionTile.centroid, ST_GeomFromText(polygon)) == 'True').one()
示例14: perm
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def perm(cls) -> str: # pylint: disable=no-self-argument
return (
"[" + cls.database_name + "].(id:" + expression.cast(cls.id, String) + ")"
)
示例15: perm
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import cast [as 別名]
def perm(cls) -> str: # pylint: disable=no-self-argument
return "[" + cls.cluster_name + "].(id:" + expression.cast(cls.id, String) + ")"