本文整理汇总了Python中sqlalchemy.sql.expression.ColumnElement方法的典型用法代码示例。如果您正苦于以下问题:Python expression.ColumnElement方法的具体用法?Python expression.ColumnElement怎么用?Python expression.ColumnElement使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.sql.expression
的用法示例。
在下文中一共展示了expression.ColumnElement方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_order_direction
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def _get_order_direction(x):
"""
Given a :class:`sqlalchemy.sql.expression.ColumnElement`, find and return
its ordering direction (ASC or DESC) if it has one.
:param x: a :class:`sqlalchemy.sql.expression.ColumnElement`
:return: `asc_op`, `desc_op` or `None`
"""
for _ in range(_WRAPPING_DEPTH):
mod = getattr(x, 'modifier', None)
if mod in (asc_op, desc_op):
return mod
el = getattr(x, 'element', None)
if el is None:
return None
x = el
raise Exception(_WRAPPING_OVERFLOW) # pragma: no cover
示例2: _reverse_order_direction
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def _reverse_order_direction(ce):
"""
Given a :class:`sqlalchemy.sql.expression.ColumnElement`, return a copy
with its ordering direction (ASC or DESC) reversed (if it has one).
:param ce: a :class:`sqlalchemy.sql.expression.ColumnElement`
"""
x = copied = ce._clone()
for _ in range(_WRAPPING_DEPTH):
mod = getattr(x, 'modifier', None)
if mod in (asc_op, desc_op):
if mod == asc_op:
x.modifier = desc_op
else:
x.modifier = asc_op
return copied
else:
if not hasattr(x, 'element'):
return copied
# Since we're going to change something inside x.element, we
# need to clone another level deeper.
x._copy_internals()
x = x.element
raise Exception(_WRAPPING_OVERFLOW) # pragma: no cover
示例3: get_field_type
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def get_field_type(model, fieldname):
"""Helper which returns the SQLAlchemy type of the field.
"""
field = getattr(model, fieldname)
if isinstance(field, ColumnElement):
fieldtype = field.type
else:
if isinstance(field, AssociationProxy):
field = field.remote_attr
if hasattr(field, 'property'):
prop = field.property
if isinstance(prop, RelProperty):
return None
fieldtype = prop.columns[0].type
else:
return None
return fieldtype
示例4: test_truly_unlabeled_sql_expressions
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def test_truly_unlabeled_sql_expressions(self):
users = self.tables.users
sess = Session()
class not_named_max(expression.ColumnElement):
name = "not_named_max"
@compiles(not_named_max)
def visit_max(element, compiler, **kw):
return "max(id)"
# assert that there is no "AS max_" or any label of any kind.
eq_(str(select([not_named_max()])), "SELECT max(id)")
# ColumnElement still handles it by applying label()
q = sess.query(not_named_max()).select_from(users)
eq_(q.all(), [(10,)])
示例5: test_scalar_subquery_compile_whereclause
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def test_scalar_subquery_compile_whereclause(self):
User = self.classes.User
Address = self.classes.Address
session = create_session()
q = session.query(User.id).filter(User.id == 7).scalar_subquery()
q = session.query(Address).filter(Address.user_id == q)
assert isinstance(q.whereclause.right, expression.ColumnElement)
self.assert_compile(
q,
"SELECT addresses.id AS addresses_id, addresses.user_id "
"AS addresses_user_id, addresses.email_address AS "
"addresses_email_address FROM addresses WHERE "
"addresses.user_id = (SELECT users.id "
"FROM users WHERE users.id = :id_1)",
)
示例6: strip_labels
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def strip_labels(el):
"""Remove labels from a
:class:`sqlalchemy.sql.expression.ColumnElement`."""
while isinstance(el, _LABELLED):
try:
el = el.element
except AttributeError:
raise ValueError # pragma: no cover
return el
示例7: _remove_order_direction
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def _remove_order_direction(ce):
"""
Given a :class:`sqlalchemy.sql.expression.ColumnElement`, return a copy
with its ordering modifiers (ASC/DESC, NULLS FIRST/LAST) removed (if it has
any).
:param ce: a :class:`sqlalchemy.sql.expression.ColumnElement`
"""
x = copied = ce._clone()
parent = None
for _ in range(_WRAPPING_DEPTH):
mod = getattr(x, 'modifier', None)
if mod in _UNSUPPORTED_ORDER_MODIFIERS:
warn("One of your order columns had a NULLS FIRST or NULLS LAST "
"modifier; but sqlakeyset does not support order columns "
"with nulls. YOUR RESULTS WILL BE WRONG. See the "
"Limitations section of the sqlakeyset README for more "
"information.")
if mod in _ORDER_MODIFIERS:
x._copy_internals()
if parent is None:
# The modifier was at the top level; so just take the child.
copied = x = x.element
else:
# Remove this link from the wrapping element chain and return
# the top-level expression.
parent.element = x = x.element
else:
if not hasattr(x, 'element'):
return copied
parent = x
# Since we might change something inside x.element, we
# need to clone another level deeper.
x._copy_internals()
x = x.element
raise Exception(_WRAPPING_OVERFLOW) # pragma: no cover
示例8: _key_fallback
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def _key_fallback(self, key, raiseerr=True):
map = self._keymap
result = None
if isinstance(key, str):
result = map.get(key)
# fallback for targeting a ColumnElement to a textual expression
# this is a rare use case which only occurs when matching text()
# or colummn('name') constructs to ColumnElements, or after a
# pickle/unpickle roundtrip
elif isinstance(key, expression.ColumnElement):
if (key._label and key._label in map):
result = map[key._label]
elif (hasattr(key, 'key') and key.key in map):
# match is only on name.
result = map[key.key]
# search extra hard to make sure this
# isn't a column/label name overlap.
# this check isn't currently available if the row
# was unpickled.
if result is not None and result[1] is not None:
for obj in result[1]:
if key._compare_name_for_result(obj):
break
else:
result = None
if result is None:
if raiseerr:
raise exc.NoSuchColumnError(
"Could not locate column in row for column '%s'" %
expression._string_or_unprintable(key))
else:
return None
else:
map[key] = result
return result
示例9: test_keyed_targeting_no_label_at_all_one
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def test_keyed_targeting_no_label_at_all_one(self, connection):
class not_named_max(expression.ColumnElement):
name = "not_named_max"
@compiles(not_named_max)
def visit_max(element, compiler, **kw):
# explicit add
kw["add_to_result_map"](None, None, (element,), NULLTYPE)
return "max(a)"
# assert that there is no "AS max_" or any label of any kind.
eq_(str(select([not_named_max()])), "SELECT max(a)")
nnm = not_named_max()
self._test_keyed_targeting_no_label_at_all(nnm, connection)
示例10: test_keyed_targeting_no_label_at_all_two
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def test_keyed_targeting_no_label_at_all_two(self, connection):
class not_named_max(expression.ColumnElement):
name = "not_named_max"
@compiles(not_named_max)
def visit_max(element, compiler, **kw):
# we don't add to keymap here; compiler should be doing it
return "max(a)"
# assert that there is no "AS max_" or any label of any kind.
eq_(str(select([not_named_max()])), "SELECT max(a)")
nnm = not_named_max()
self._test_keyed_targeting_no_label_at_all(nnm, connection)
示例11: test_adapt_result_columns
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def test_adapt_result_columns(self, connection, stmt_fn):
"""test adaptation of a CursorResultMetadata to another one.
This copies the _keymap from one to the other in terms of the
selected columns of a target selectable.
This is used by the statement caching process to re-use the
CursorResultMetadata from the cached statement against the same
statement sent separately.
"""
stmt1 = stmt_fn(self)
stmt2 = stmt_fn(self)
eq_(stmt1._generate_cache_key(), stmt2._generate_cache_key())
column_linkage = dict(
zip(stmt1.selected_columns, stmt2.selected_columns)
)
result = connection.execute(stmt1)
mock_context = Mock(
compiled=result.context.compiled, invoked_statement=stmt2
)
existing_metadata = result._metadata
adapted_metadata = existing_metadata._adapt_to_context(mock_context)
eq_(existing_metadata.keys, adapted_metadata.keys)
for k in existing_metadata._keymap:
if isinstance(k, ColumnElement) and k in column_linkage:
other_k = column_linkage[k]
else:
other_k = k
is_(
existing_metadata._keymap[k], adapted_metadata._keymap[other_k]
)
示例12: make_select_compatible
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def make_select_compatible(
cls, groupby_exprs: Dict[str, ColumnElement], select_exprs: List[ColumnElement]
) -> List[ColumnElement]:
return select_exprs
示例13: make_select_compatible
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def make_select_compatible(
cls, groupby_exprs: Dict[str, ColumnElement], select_exprs: List[ColumnElement]
) -> List[ColumnElement]:
"""
Some databases will just return the group-by field into the select, but don't
allow the group-by field to be put into the select list.
:param groupby_exprs: mapping between column name and column object
:param select_exprs: all columns in the select clause
:return: columns to be included in the final select clause
"""
return select_exprs
示例14: _key_fallback
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def _key_fallback(self, key, raiseerr=True):
map = self._keymap
result = None
if isinstance(key, str):
result = map.get(key)
# fallback for targeting a ColumnElement to a textual expression
# this is a rare use case which only occurs when matching text()
# or colummn('name') constructs to ColumnElements, or after a
# pickle/unpickle roundtrip
elif isinstance(key, expression.ColumnElement):
if (key._label and key._label in map):
result = map[key._label]
elif (hasattr(key, 'name') and key.name in map):
# match is only on name.
result = map[key.name]
# search extra hard to make sure this
# isn't a column/label name overlap.
# this check isn't currently available if the row
# was unpickled.
if (result is not None and
result[1] is not None):
for obj in result[1]:
if key._compare_name_for_result(obj):
break
else:
result = None
if result is None:
if raiseerr:
raise exc.NoSuchColumnError(
"Could not locate column in row for column '%s'" %
expression._string_or_unprintable(key))
else:
return None
else:
map[key] = result
return result
示例15: derive_order_key
# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import ColumnElement [as 别名]
def derive_order_key(ocol, desc, index):
"""Attempt to derive the value of `ocol` from a query column.
:param ocol: The :class:`OC` to look up.
:param desc: Either a column description as in
:attr:`sqlalchemy.orm.query.Query.column_descriptions`, or a
:class:`sqlalchemy.sql.expression.ColumnElement`.
:returns: Either a :class:`MappedOrderColumn` or `None`."""
if isinstance(desc, ColumnElement):
if desc.compare(ocol.comparable_value):
return DirectColumn(ocol, index)
else:
return None
entity = desc['entity']
expr = desc['expr']
if isinstance(expr, Bundle):
for key, col in expr.columns.items():
if strip_labels(col).compare(ocol.comparable_value):
return AttributeColumn(ocol, index, key)
try:
is_a_table = bool(entity == expr)
except (sqlalchemy.exc.ArgumentError, TypeError):
is_a_table = False
if isinstance(expr, Mapper) and expr.class_ == entity:
is_a_table = True
if is_a_table: # is a table
mapper = class_mapper(desc['type'])
try:
prop = mapper.get_property_by_column(ocol.element)
return AttributeColumn(ocol, index, prop.key)
except sqlalchemy.orm.exc.UnmappedColumnError:
pass
# is an attribute
if isinstance(expr, QueryableAttribute):
mapper = expr.parent
tname = mapper.local_table.description
if ocol.table_name == tname and ocol.name == expr.name:
return DirectColumn(ocol, index)
# is an attribute with label
try:
if ocol.quoted_full_name == OC(expr).full_name:
return DirectColumn(ocol, index)
except sqlalchemy.exc.ArgumentError:
pass