本文整理汇总了Python中sqlalchemy.orm.session.query方法的典型用法代码示例。如果您正苦于以下问题:Python session.query方法的具体用法?Python session.query怎么用?Python session.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.orm.session
的用法示例。
在下文中一共展示了session.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _entity_corresponds_to
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def _entity_corresponds_to(given, entity):
"""determine if 'given' corresponds to 'entity', in terms
of an entity passed to Query that would match the same entity
being referred to elsewhere in the query.
"""
if entity.is_aliased_class:
if given.is_aliased_class:
if entity._base_alias is given._base_alias:
return True
return False
elif given.is_aliased_class:
if given._use_mapper_path:
return entity in given.with_polymorphic_mappers
else:
return entity is given
return entity.common_parent(given)
示例2: create_row_processor
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def create_row_processor(self, query, procs, labels):
"""Produce the "row processing" function for this :class:`.Bundle`.
May be overridden by subclasses.
.. seealso::
:ref:`bundles` - includes an example of subclassing.
"""
keyed_tuple = result_tuple(labels, [() for l in labels])
def proc(row):
return keyed_tuple([proc(row) for proc in procs])
return proc
示例3: _entity_corresponds_to
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def _entity_corresponds_to(given, entity):
"""determine if 'given' corresponds to 'entity', in terms
of an entity passed to Query that would match the same entity
being referred to elsewhere in the query.
"""
if entity.is_aliased_class:
if given.is_aliased_class:
if entity._base_alias() is given._base_alias():
return True
return False
elif given.is_aliased_class:
if given._use_mapper_path:
return entity in given.with_polymorphic_mappers
else:
return entity is given
return entity.common_parent(given)
示例4: join
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def join(left, right, onclause=None, isouter=False, join_to_left=None):
"""Produce an inner join between left and right clauses.
:func:`.orm.join` is an extension to the core join interface
provided by :func:`.sql.expression.join()`, where the
left and right selectables may be not only core selectable
objects such as :class:`.Table`, but also mapped classes or
:class:`.AliasedClass` instances. The "on" clause can
be a SQL expression, or an attribute or string name
referencing a configured :func:`.relationship`.
:func:`.orm.join` is not commonly needed in modern usage,
as its functionality is encapsulated within that of the
:meth:`.Query.join` method, which features a
significant amount of automation beyond :func:`.orm.join`
by itself. Explicit usage of :func:`.orm.join`
with :class:`.Query` involves usage of the
:meth:`.Query.select_from` method, as in::
from sqlalchemy.orm import join
session.query(User).\\
select_from(join(User, Address, User.addresses)).\\
filter(Address.email_address=='foo@bar.com')
In modern SQLAlchemy the above join can be written more
succinctly as::
session.query(User).\\
join(User.addresses).\\
filter(Address.email_address=='foo@bar.com')
See :meth:`.Query.join` for information on modern usage
of ORM level joins.
.. versionchanged:: 0.8.1 - the ``join_to_left`` parameter
is no longer used, and is deprecated.
"""
return _ORMJoin(left, right, onclause, isouter)
示例5: with_parent
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def with_parent(instance, prop):
"""Create filtering criterion that relates this query's primary entity
to the given related instance, using established :func:`.relationship()`
configuration.
The SQL rendered is the same as that rendered when a lazy loader
would fire off from the given parent on that attribute, meaning
that the appropriate state is taken from the parent object in
Python without the need to render joins to the parent table
in the rendered statement.
.. versionchanged:: 0.6.4
This method accepts parent instances in all
persistence states, including transient, persistent, and detached.
Only the requisite primary key/foreign key attributes need to
be populated. Previous versions didn't work with transient
instances.
:param instance:
An instance which has some :func:`.relationship`.
:param property:
String property name, or class-bound attribute, which indicates
what relationship from the instance should be used to reconcile the
parent/child relationship.
"""
if isinstance(prop, util.string_types):
mapper = object_mapper(instance)
prop = getattr(mapper.class_, prop).property
elif isinstance(prop, attributes.QueryableAttribute):
prop = prop.property
return prop._with_parent(instance)
示例6: join
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def join(
left, right, onclause=None, isouter=False,
full=False, join_to_left=None):
r"""Produce an inner join between left and right clauses.
:func:`.orm.join` is an extension to the core join interface
provided by :func:`.sql.expression.join()`, where the
left and right selectables may be not only core selectable
objects such as :class:`.Table`, but also mapped classes or
:class:`.AliasedClass` instances. The "on" clause can
be a SQL expression, or an attribute or string name
referencing a configured :func:`.relationship`.
:func:`.orm.join` is not commonly needed in modern usage,
as its functionality is encapsulated within that of the
:meth:`.Query.join` method, which features a
significant amount of automation beyond :func:`.orm.join`
by itself. Explicit usage of :func:`.orm.join`
with :class:`.Query` involves usage of the
:meth:`.Query.select_from` method, as in::
from sqlalchemy.orm import join
session.query(User).\
select_from(join(User, Address, User.addresses)).\
filter(Address.email_address=='foo@bar.com')
In modern SQLAlchemy the above join can be written more
succinctly as::
session.query(User).\
join(User.addresses).\
filter(Address.email_address=='foo@bar.com')
See :meth:`.Query.join` for information on modern usage
of ORM level joins.
.. versionchanged:: 0.8.1 - the ``join_to_left`` parameter
is no longer used, and is deprecated.
"""
return _ORMJoin(left, right, onclause, isouter, full)
示例7: with_parent
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def with_parent(instance, prop, from_entity=None):
"""Create filtering criterion that relates this query's primary entity
to the given related instance, using established :func:`.relationship()`
configuration.
The SQL rendered is the same as that rendered when a lazy loader
would fire off from the given parent on that attribute, meaning
that the appropriate state is taken from the parent object in
Python without the need to render joins to the parent table
in the rendered statement.
:param instance:
An instance which has some :func:`.relationship`.
:param property:
String property name, or class-bound attribute, which indicates
what relationship from the instance should be used to reconcile the
parent/child relationship.
:param from_entity:
Entity in which to consider as the left side. This defaults to the
"zero" entity of the :class:`.Query` itself.
.. versionadded:: 1.2
"""
if isinstance(prop, util.string_types):
mapper = object_mapper(instance)
prop = getattr(mapper.class_, prop).property
elif isinstance(prop, attributes.QueryableAttribute):
prop = prop.property
return prop._with_parent(instance, from_entity=from_entity)
示例8: with_parent
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def with_parent(instance, prop):
"""Create filtering criterion that relates this query's primary entity
to the given related instance, using established :func:`.relationship()`
configuration.
The SQL rendered is the same as that rendered when a lazy loader
would fire off from the given parent on that attribute, meaning
that the appropriate state is taken from the parent object in
Python without the need to render joins to the parent table
in the rendered statement.
.. versionchanged:: 0.6.4
This method accepts parent instances in all
persistence states, including transient, persistent, and detached.
Only the requisite primary key/foreign key attributes need to
be populated. Previous versions didn't work with transient
instances.
:param instance:
An instance which has some :func:`.relationship`.
:param property:
String property name, or class-bound attribute, which indicates
what relationship from the instance should be used to reconcile the
parent/child relationship.
"""
if isinstance(prop, util.string_types):
mapper = object_mapper(instance)
prop = getattr(mapper.class_, prop).property
elif isinstance(prop, attributes.QueryableAttribute):
prop = prop.property
return prop.compare(operators.eq,
instance,
value_is_parent=True)
示例9: __init__
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def __init__(self, name, *exprs, **kw):
r"""Construct a new :class:`.Bundle`.
e.g.::
bn = Bundle("mybundle", MyClass.x, MyClass.y)
for row in session.query(bn).filter(
bn.c.x == 5).filter(bn.c.y == 4):
print(row.mybundle.x, row.mybundle.y)
:param name: name of the bundle.
:param \*exprs: columns or SQL expressions comprising the bundle.
:param single_entity=False: if True, rows for this :class:`.Bundle`
can be returned as a "single entity" outside of any enclosing tuple
in the same manner as a mapped entity.
"""
self.name = self._label = name
self.exprs = exprs = [
coercions.expect(
roles.ColumnsClauseRole, expr, apply_propagate_attrs=self
)
for expr in exprs
]
self.c = self.columns = ColumnCollection(
(getattr(col, "key", col._label), col)
for col in [e._annotations.get("bundle", e) for e in exprs]
)
self.single_entity = kw.pop("single_entity", self.single_entity)
示例10: with_parent
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def with_parent(instance, prop, from_entity=None):
"""Create filtering criterion that relates this query's primary entity
to the given related instance, using established
:func:`_orm.relationship()`
configuration.
The SQL rendered is the same as that rendered when a lazy loader
would fire off from the given parent on that attribute, meaning
that the appropriate state is taken from the parent object in
Python without the need to render joins to the parent table
in the rendered statement.
:param instance:
An instance which has some :func:`_orm.relationship`.
:param property:
String property name, or class-bound attribute, which indicates
what relationship from the instance should be used to reconcile the
parent/child relationship.
:param from_entity:
Entity in which to consider as the left side. This defaults to the
"zero" entity of the :class:`_query.Query` itself.
.. versionadded:: 1.2
"""
if isinstance(prop, util.string_types):
mapper = object_mapper(instance)
prop = getattr(mapper.class_, prop).property
elif isinstance(prop, attributes.QueryableAttribute):
prop = prop.property
return prop._with_parent(instance, from_entity=from_entity)
示例11: test_engine
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def test_engine(self):
engine = dbutils.connect(self.json)
self.assertIsInstance(engine, sqlalchemy.engine.base.Engine)
table_names = ['chrom', 'hit', "orf", "external",
"external_sources", 'hsp', 'junctions', 'query', 'target']
self.assertEqual(sorted(list(engine.table_names())), sorted(table_names))
示例12: test_content
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def test_content(self):
engine = dbutils.connect(self.json)
sessionmaker = sqlalchemy.orm.sessionmaker(bind=engine)
session = sessionmaker()
# Simple tests based on the static content of the dictionary
self.assertEqual(session.query(serializers.junction.Junction).count(), 372,
self.json["db_settings"])
self.assertEqual(session.query(serializers.orf.Orf).count(), 169)
self.assertEqual(session.query(serializers.blast_serializer.Target).count(), 38909)
self.assertEqual(session.query(serializers.blast_serializer.Query).count(), 93)
self.assertEqual(session.query(serializers.blast_serializer.Hit).count(), 5034)
self.assertEqual(session.query(serializers.blast_serializer.Hsp).count(), 13585)
first_query = session.query(serializers.blast_serializer.Query).limit(1).one()
astup = first_query.as_tuple()
self.assertTrue(astup._fields, ("query_id", "query_name", "query_length"))
self.assertIsInstance(astup.query_id, int)
self.assertIsInstance(astup.query_length, int)
self.assertIsInstance(astup.query_name, str)
first_target = session.query(
serializers.blast_serializer.Target).limit(1).one()
astup = first_target.as_tuple()
self.assertTrue(astup._fields, ("target_id", "target_name", "target_length"))
self.assertIsInstance(astup.target_id, int)
self.assertIsInstance(astup.target_length, int)
self.assertIsInstance(astup.target_name, str)
示例13: test_connect_to_shm
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def test_connect_to_shm(self):
self.json["pick"]["run_options"]['shm'] = True
shutil.copy(self.json["db_settings"]["db"], "/dev/shm/")
self.json["db_settings"]["db"] = os.path.join("/dev/shm/",
os.path.basename(self.json["db_settings"]["db"]))
connector = dbutils.connect(self.json)
self.assertEqual(str(connector.url), "sqlite://")
engine = dbutils.connect(self.json)
sessionmaker = sqlalchemy.orm.sessionmaker(bind=engine)
session = sessionmaker()
first_target = session.query(serializers.blast_serializer.Target).limit(1).one()
astup = first_target.as_tuple()
self.assertTrue(astup._fields, ("target_id", "target_name", "target_length"))
os.remove(os.path.join("/dev/shm/", os.path.basename(self.json["db_settings"]["db"])))
示例14: join
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def join(
left, right, onclause=None, isouter=False, full=False, join_to_left=None
):
r"""Produce an inner join between left and right clauses.
:func:`_orm.join` is an extension to the core join interface
provided by :func:`_expression.join()`, where the
left and right selectables may be not only core selectable
objects such as :class:`_schema.Table`, but also mapped classes or
:class:`.AliasedClass` instances. The "on" clause can
be a SQL expression, or an attribute or string name
referencing a configured :func:`_orm.relationship`.
:func:`_orm.join` is not commonly needed in modern usage,
as its functionality is encapsulated within that of the
:meth:`_query.Query.join` method, which features a
significant amount of automation beyond :func:`_orm.join`
by itself. Explicit usage of :func:`_orm.join`
with :class:`_query.Query` involves usage of the
:meth:`_query.Query.select_from` method, as in::
from sqlalchemy.orm import join
session.query(User).\
select_from(join(User, Address, User.addresses)).\
filter(Address.email_address=='foo@bar.com')
In modern SQLAlchemy the above join can be written more
succinctly as::
session.query(User).\
join(User.addresses).\
filter(Address.email_address=='foo@bar.com')
See :meth:`_query.Query.join` for information on modern usage
of ORM level joins.
.. deprecated:: 0.8
the ``join_to_left`` parameter is deprecated, and will be removed
in a future release. The parameter has no effect.
"""
return _ORMJoin(left, right, onclause, isouter, full)
示例15: polymorphic_union
# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import query [as 别名]
def polymorphic_union(table_map, typecolname,
aliasname='p_union', cast_nulls=True):
"""Create a ``UNION`` statement used by a polymorphic mapper.
See :ref:`concrete_inheritance` for an example of how
this is used.
:param table_map: mapping of polymorphic identities to
:class:`.Table` objects.
:param typecolname: string name of a "discriminator" column, which will be
derived from the query, producing the polymorphic identity for
each row. If ``None``, no polymorphic discriminator is generated.
:param aliasname: name of the :func:`~sqlalchemy.sql.expression.alias()`
construct generated.
:param cast_nulls: if True, non-existent columns, which are represented
as labeled NULLs, will be passed into CAST. This is a legacy behavior
that is problematic on some backends such as Oracle - in which case it
can be set to False.
"""
colnames = util.OrderedSet()
colnamemaps = {}
types = {}
for key in table_map:
table = table_map[key]
# mysql doesnt like selecting from a select;
# make it an alias of the select
if isinstance(table, sql.Select):
table = table.alias()
table_map[key] = table
m = {}
for c in table.c:
colnames.add(c.key)
m[c.key] = c
types[c.key] = c.type
colnamemaps[table] = m
def col(name, table):
try:
return colnamemaps[table][name]
except KeyError:
if cast_nulls:
return sql.cast(sql.null(), types[name]).label(name)
else:
return sql.type_coerce(sql.null(), types[name]).label(name)
result = []
for type, table in table_map.items():
if typecolname is not None:
result.append(
sql.select([col(name, table) for name in colnames] +
[sql.literal_column(sql_util._quote_ddl_expr(type)).
label(typecolname)],
from_obj=[table]))
else:
result.append(sql.select([col(name, table) for name in colnames],
from_obj=[table]))
return sql.union_all(*result).alias(aliasname)