本文整理汇总了Python中sqlalchemy.cast方法的典型用法代码示例。如果您正苦于以下问题:Python sqlalchemy.cast方法的具体用法?Python sqlalchemy.cast怎么用?Python sqlalchemy.cast使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy
的用法示例。
在下文中一共展示了sqlalchemy.cast方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_model_search_filter
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def get_model_search_filter(Model):
mapper = inspect(Model)
class ModelSearchFilter(CharFilter):
def filter(self, qs, value):
value = self.clean_value(value)
if value in EMPTY_VALUES:
return qs
def map_column(column):
if isinstance(column.type, (sqlalchemy.Integer, sqlalchemy.Numeric)):
return cast(column, sqlalchemy.String).__eq__(value)
elif isinstance(column.type, sqlalchemy.String):
return column.ilike('%{}%'.format(value))
elif isinstance(column.type, sqlalchemy.JSON):
return cast(column, sqlalchemy.String).ilike('%{}%'.format(value))
operators = list(filter(lambda x: x is not None, map(map_column, mapper.columns)))
return qs.filter(or_(*operators))
return ModelSearchFilter
示例2: _cast
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def _cast(t, expr):
arg, typ = expr.op().args
sa_arg = t.translate(arg)
sa_type = t.get_sqla_type(typ)
# specialize going from an integer type to a timestamp
if isinstance(arg.type(), dt.Integer) and isinstance(sa_type, sa.DateTime):
return sa.func.timezone('UTC', sa.func.to_timestamp(sa_arg))
if arg.type().equals(dt.binary) and typ.equals(dt.string):
return sa.func.encode(sa_arg, 'escape')
if typ.equals(dt.binary):
# decode yields a column of memoryview which is annoying to deal with
# in pandas. CAST(expr AS BYTEA) is correct and returns byte strings.
return sa.cast(sa_arg, sa.LargeBinary())
return sa.cast(sa_arg, sa_type)
示例3: _cast
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def _cast(t, expr):
arg, typ = expr.op().args
sa_arg = t.translate(arg)
sa_type = t.get_sqla_type(typ)
# specialize going from an integer type to a timestamp
if isinstance(arg.type(), dt.Integer) and isinstance(sa_type, sa.DateTime):
return sa.func.timezone('UTC', sa.func.to_timestamp(sa_arg))
if arg.type().equals(dt.binary) and typ.equals(dt.string):
return sa.func.encode(sa_arg, 'escape')
if typ.equals(dt.binary):
# decode yields a column of memoryview which is annoying to deal with
# in pandas. CAST(expr AS BYTEA) is correct and returns byte strings.
return sa.cast(sa_arg, sa.Binary())
return sa.cast(sa_arg, sa_type)
示例4: _variance_reduction
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def _variance_reduction(func_name):
suffix = {'sample': 'samp', 'pop': 'pop'}
def variance_compiler(t, expr):
arg, how, where = expr.op().args
if arg.type().equals(dt.boolean):
arg = arg.cast('int32')
func = getattr(
sa.func, '{}_{}'.format(func_name, suffix.get(how, 'samp'))
)
if where is not None:
arg = where.ifelse(arg, None)
return func(t.translate(arg))
return variance_compiler
示例5: test_render_add_index_cast
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def test_render_add_index_cast(self):
m = MetaData()
t = Table(
"test",
m,
Column("id", Integer, primary_key=True),
Column("code", String(255)),
)
idx = Index("test_lower_code_idx", cast(t.c.code, String))
op_obj = ops.CreateIndexOp.from_index(idx)
eq_ignore_whitespace(
autogenerate.render_op_text(self.autogen_context, op_obj),
"op.create_index('test_lower_code_idx', 'test', "
"[sa.text(!U'CAST(code AS VARCHAR)')], unique=False)",
)
示例6: oql_for_chunk
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def oql_for_chunk(self, chunk, include_self=False, skip=None):
skip = set(skip or [])
q = self.items.filter(cast(Item.location, Geometry).contained(envelope(chunk)))
tags = set()
for item in q:
tags |= set(item.tags)
tags.difference_update(skip_tags)
tags.difference_update(skip)
tags = matcher.simplify_tags(tags)
if not(tags):
print('no tags, skipping')
return
ymin, ymax, xmin, xmax = chunk
bbox = '{:f},{:f},{:f},{:f}'.format(ymin, xmin, ymax, xmax)
oql = overpass.oql_for_area(self.overpass_type,
self.osm_id,
tags,
bbox, None,
include_self=include_self)
return oql
示例7: suggest_larger_areas
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def suggest_larger_areas(self):
ret = []
for e in reversed(self.is_in() or []):
osm_type, osm_id, bounds = e['type'], e['id'], e['bounds']
if osm_type == self.osm_type and osm_id == self.osm_id:
continue
box = func.ST_MakeEnvelope(bounds['minlon'], bounds['minlat'],
bounds['maxlon'], bounds['maxlat'], 4326)
q = func.ST_Area(box.cast(Geography))
bbox_area = session.query(q).scalar()
area_in_sq_km = bbox_area / (1000 * 1000)
if area_in_sq_km < 10 or area_in_sq_km > 40_000:
continue
place = Place.from_osm(osm_type, osm_id)
if not place:
continue
place.admin_level = e['tags'].get('admin_level') or None if 'tags' in e else None
ret.append(place)
ret.sort(key=lambda place: place.area_in_sq_km)
return ret
示例8: test_view_data_with_map_location
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def test_view_data_with_map_location(self):
survey_id = (
self.session
.query(models.SurveyNode.root_survey_id)
.filter(
sa.cast(
models.SurveyNode.type_constraint, pg.TEXT
) == 'location'
)
.scalar()
)
url = '/admin/data/' + survey_id
response = self.fetch(url, method='GET')
response_soup = BeautifulSoup(response.body, 'html.parser')
questions = response_soup.findAll('div', {'class': 'question-stats'})
self.assertEqual(len(questions), 1)
示例9: test_view_data_with_map_facility
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def test_view_data_with_map_facility(self):
survey_id = (
self.session
.query(models.SurveyNode.root_survey_id)
.filter(
sa.cast(
models.SurveyNode.type_constraint, pg.TEXT
) == 'facility'
)
.scalar()
)
url = '/admin/data/' + survey_id
response = self.fetch(url, method='GET')
response_soup = BeautifulSoup(response.body, 'html.parser')
questions = response_soup.findAll('div', {'class': 'question-stats'})
self.assertEqual(len(questions), 1)
示例10: test_only_updates_given_table
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def test_only_updates_given_table(
self,
session,
article,
user,
connection,
versioning_manager
):
alter_column(
connection,
'user',
'id',
lambda value, activity_table: sa.cast(value, sa.Text)
)
activity = session.query(versioning_manager.activity_cls).filter_by(
table_name='article'
).one()
assert isinstance(activity.changed_data['id'], int)
示例11: cast
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def cast(self, type_):
"""Produce a type cast, i.e. ``CAST(<expression> AS <type>)``.
This is a shortcut to the :func:`_expression.cast` function.
.. seealso::
:ref:`coretutorial_casts`
:func:`_expression.cast`
:func:`_expression.type_coerce`
.. versionadded:: 1.0.7
"""
return Cast(self, type_)
示例12: test_rowid
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def test_rowid(self):
metadata = self.metadata
t = Table("t1", metadata, Column("x", Integer))
with testing.db.begin() as conn:
t.create(conn)
conn.execute(t.insert(), {"x": 5})
s1 = select([t]).subquery()
s2 = select([column("rowid")]).select_from(s1)
rowid = conn.scalar(s2)
# the ROWID type is not really needed here,
# as cx_oracle just treats it as a string,
# but we want to make sure the ROWID works...
rowid_col = column("rowid", oracle.ROWID)
s3 = select([t.c.x, rowid_col]).where(
rowid_col == cast(rowid, oracle.ROWID)
)
eq_(conn.execute(s3).fetchall(), [(5, rowid)])
示例13: bind_expression
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def bind_expression(self, value):
return cast(value, sqltypes.JSON)
示例14: cast
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def cast(self, type_):
"""Produce a type cast, i.e. ``CAST(<expression> AS <type>)``.
This is a shortcut to the :func:`~.expression.cast` function.
.. versionadded:: 1.0.7
"""
return Cast(self, type_)
示例15: list_dids_by_meta
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import cast [as 别名]
def list_dids_by_meta(scope, select, session=None):
"""
Add or update the given metadata to the given did
:param scope: the scope of the did
:param name: the name of the did
:param meta: the metadata to be added or updated
"""
# Currently for sqlite only add, get and delete is implemented.
if session.bind.dialect.name == 'sqlite':
raise NotImplementedError
if session.bind.dialect.name == 'oracle':
oracle_version = int(session.connection().connection.version.split('.')[0])
if oracle_version < 12:
raise NotImplementedError
query = session.query(models.DidMeta)
if scope is not None:
query = query.filter(models.DidMeta.scope == scope)
for k, v in iteritems(select):
if session.bind.dialect.name == 'oracle':
query = query.filter(text("json_exists(meta,'$.%s?(@==''%s'')')" % (k, v)))
else:
query = query.filter(cast(models.DidMeta.meta[k], String) == type_coerce(v, JSON))
dids = list()
for row in query.yield_per(10):
dids.append({'scope': row.scope, 'name': row.name})
return dids