本文整理汇总了Python中sqlalchemy.orm.query.Query类的典型用法代码示例。如果您正苦于以下问题:Python Query类的具体用法?Python Query怎么用?Python Query使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Query类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, entities, session, **kw):
SaQuery.__init__(self, entities, session, **kw)
ent_cls = entities[0]
if isinstance(ent_cls, type) and issubclass(ent_cls, Entity):
self._entity_class = ent_cls
else:
self._entity_class = None
示例2: __init__
def __init__ (self, entities, session):
"""Create an SCMQuery.
Parameters
----------
entities:
session:
Attributes
----------
self.start: datetime.datetime
Start of the period to consider for commits. Default: None
(start from the first commit)
self.end: datetime.datetime
End of the period to consider for commits. Default: None
(end in the last commit)
"""
self.start = None
self.end = None
# Keep an accounting of which tables have been joined, to avoid
# undesired repeated joins
self.joined = []
Query.__init__(self, entities, session)
示例3: test_query_column_name
def test_query_column_name(self):
# test for bug: http://groups.google.com/group/geoalchemy/browse_thread/thread/6b731dd1673784f9
from sqlalchemy.orm.query import Query
query = Query(Road.road_geom).filter(Road.road_geom == '..').__str__()
ok_('AsBinary(roads.road_geom)' in query, 'table name is part of the column expression (select clause)')
ok_('WHERE Equals(roads.road_geom' in query, 'table name is part of the column expression (where clause)')
query_wkb = Select([Road.road_geom]).where(Road.road_geom == 'POINT(0 0)').__str__()
ok_('SELECT AsBinary(roads.road_geom)' in query_wkb, 'AsBinary is added')
ok_('WHERE Equals(roads.road_geom' in query_wkb, 'AsBinary is not added in where clause')
# test for RAW attribute
query_wkb = Select([Road.road_geom.RAW]).__str__()
ok_('SELECT roads.road_geom' in query_wkb, 'AsBinary is not added')
ok_(session.query(Road.road_geom.RAW).first())
query_srid = Query(func.SRID(Road.road_geom.RAW))
ok_('SRID(roads.road_geom)' in query_srid.__str__(), 'AsBinary is not added')
ok_(session.scalar(query_srid))
eq_(session.scalar(Select([func.SRID(Spot.spot_location)]).where(Spot.spot_id == 1)),
None,
'AsBinary is added and the SRID is not returned')
eq_(str(session.scalar(Select([func.SRID(Spot.spot_location.RAW)]).where(Spot.spot_id == 1))),
'4326',
'AsBinary is not added and the SRID is returned')
spot_alias = aliased(Spot)
query_wkt = Select([func.wkt(spot_alias.spot_location.RAW)]).__str__()
ok_('SELECT wkt(spots_1.spot_location' in query_wkt, 'Table alias is used in select clause')
ok_('FROM spots AS spots_1' in query_wkt, 'Table alias is used in from clause')
示例4: __init__
def __init__(self, entities, session, **kw):
SaQuery.__init__(self, entities, session, **kw)
ent_cls = entities[0]
if isinstance(ent_cls, type) and issubclass(ent_cls, Entity):
self._entity_class = ent_cls
else: # just for compatibility pragma: no cover
self._entity_class = None
示例5: __init__
def __init__ (self, entities, session):
"""Create a GrimoreQuery.
Parameters
----------
entities: list of SQLAlchemy entities
Entities (tables) to include in the query
session: SQLAlchemy session
SQLAlchemy session to use to connect to the database
Attributes
----------
self.start: datetime.datetime
Start of the period to consider for commits. Default: None
(start from the first commit)
self.end: datetime.datetime
End of the period to consider for commits. Default: None
(end in the last commit)
"""
self.start = None
self.end = None
# Keep an accounting of which tables have been joined, to avoid
# undesired repeated joins
self.joined = []
Query.__init__(self, entities, session)
示例6: get
def get(self, ident):
prop = self.property_name
if self._criterion:
mapper = self._only_full_mapper_zero("get")
# Don't use getattr/hasattr to check public existence, since this
# might misinterpret a bug (AttributeError raised by some code in
# property implementation) as missing attribute and cause all
# private data going to public.
if prop in dir(mapper.class_):
crit = getattr(mapper.class_, prop)
if crit is not None:
if not isinstance(crit, ClauseElement):
# This simplest safe way to make bare boolean column
# accepted as expression.
crit = cast(crit, Boolean)
if crit!=self._criterion:
# We can't verify that criterion is from our private()
# call. Check from DB instead of looking in identity
# map.
assert False # XXX temporal to verify it's used
return Query.get(self.populate_existing(), ident)
assert False # XXX temporal to verify it's used
obj = Query.get(self, ident)
if obj is not None and (prop not in dir(obj) or getattr(obj, prop)):
return obj
示例7: element_atomic_weight
def element_atomic_weight(self, zeq, reference=None):
z = self._get_z(zeq)
q = Query(ElementAtomicWeightProperty.value)
q = q.join(Element)
q = q.filter(Element.z == z)
exception = ValueError('Unknown atomic weight for z="{0}" and '
'reference="{1}"'.format(z, reference))
return self._query_with_references(q, exception, reference)
示例8: element_mass_density_kg_per_m3
def element_mass_density_kg_per_m3(self, zeq, reference=None):
z = self._get_z(zeq)
q = Query(ElementMassDensityProperty.value_kg_per_m3)
q = q.join(Element)
q = q.filter(Element.z == z)
exception = ValueError('Unknown mass density for z="{0}" and '
'reference="{1}"'.format(z, reference))
return self._query_with_references(q, exception, reference)
示例9: __init__
def __init__ (self, entities, session):
"""Initialize the object
self.start and self.end will be used in case there are temporal
limits for the query (useful to produce TimeSeries objects,
which needs those.
"""
self.start = None
self.end = None
Query.__init__(self, entities, session)
示例10: element_name
def element_name(self, zeq, language='en', reference=None):
z = self._get_z(zeq)
q = Query(ElementNameProperty.name)
q = q.filter(ElementNameProperty.language_code == language)
q = q.join(Element)
q = q.filter(Element.z == z)
exception = ValueError('Unknown name for z="{0}", '
'language="{1}" and '
'reference="{2}"'
.format(z, language, reference))
return self._query_with_references(q, exception, reference)
示例11: test_underscore_update_many_query
def test_underscore_update_many_query(self, mock_clean):
from sqlalchemy.orm.query import Query
items = Query('asd')
clean_items = Query("ASD")
clean_items.all = Mock(return_value=[1, 2, 3])
clean_items.update = Mock()
mock_clean.return_value = clean_items
count = docs.BaseMixin._update_many(items, {'foo': 'bar'})
mock_clean.assert_called_once_with(items)
clean_items.update.assert_called_once_with(
{'foo': 'bar'}, synchronize_session='fetch')
assert count == clean_items.update()
示例12: __iter__
def __iter__(self):
"""override __iter__ to pull results from Beaker
if particular attributes have been configured.
"""
if hasattr(self, '_cache_parameters'):
cache, cache_key = _get_cache_parameters(self)
ret = cache.get_value(cache_key, createfunc=lambda: list(Query.__iter__(self)))
# merge the result in.
return self.merge_result(ret, load=False)
else:
return Query.__iter__(self)
示例13: build_entity_query
def build_entity_query(self):
"""
Builds a :class:`sqla:sqlalchemy.orm.query.Query` object for this
entity (an instance of :class:`sir.schema.searchentities.SearchEntity`)
that eagerly loads the values of all search fields.
:rtype: :class:`sqla:sqlalchemy.orm.query.Query`
"""
root_model = self.model
query = Query(root_model)
paths = [field.paths for field in self.fields]
if (config.CFG.getboolean("sir", "wscompat")
and self.extrapaths is not None):
paths.extend([self.extrapaths])
merged_paths = merge_paths(paths)
for field_paths in paths:
for path in field_paths:
current_merged_path = merged_paths
model = root_model
load = Load(model)
split_path = path.split(".")
for pathelem in split_path:
current_merged_path = current_merged_path[pathelem]
column = getattr(model, pathelem)
prop = column.property
if isinstance(prop, RelationshipProperty):
pk = column.mapper.primary_key[0].name
if prop.direction == ONETOMANY:
load = load.subqueryload(pathelem)
elif prop.direction == MANYTOONE:
load = load.joinedload(pathelem)
else:
load = load.defaultload(pathelem)
required_columns = current_merged_path.keys()
required_columns.append(pk)
# Get the mapper class of the current element of the path so
# the next iteration can access it.
model = prop.mapper.class_
logger.debug("Loading only %s on %s",
required_columns,
model)
load = defer_everything_but(class_mapper(model),
load,
*required_columns)
query = query.options(load)
return query
示例14: __iter__
def __iter__(self):
if hasattr(self, 'cachekey'):
try:
ret = _cache[self.cachekey]
except KeyError:
ret = list(Query.__iter__(self))
for x in ret:
self.session.expunge(x)
_cache[self.cachekey] = ret
return iter(self.session.merge(x, dont_load=True) for x in ret)
else:
return Query.__iter__(self)
示例15: __init__
def __init__(self, attr, state):
Query.__init__(self, attr.target_mapper, None)
self.instance = instance = state.obj()
self.attr = attr
mapper = object_mapper(instance)
prop = mapper.get_property(self.attr.key, resolve_synonyms=True)
self._criterion = prop.compare(
operators.eq,
instance,
value_is_parent=True,
alias_secondary=False)
if self.attr.order_by:
self._order_by = self.attr.order_by