当前位置: 首页>>代码示例>>Python>>正文


Python expression.ColumnElement方法代码示例

本文整理汇总了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 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:20,代码来源:columns.py

示例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 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:26,代码来源:columns.py

示例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 
开发者ID:yfauser,项目名称:planespotter,代码行数:20,代码来源:helpers.py

示例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,)]) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:19,代码来源:test_query.py

示例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)",
        ) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:21,代码来源:test_query.py

示例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 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:11,代码来源:columns.py

示例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 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:38,代码来源:columns.py

示例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 
开发者ID:aio-libs,项目名称:aiopg,代码行数:37,代码来源:result.py

示例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) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:17,代码来源:test_resultset.py

示例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) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:16,代码来源:test_resultset.py

示例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]
            ) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:43,代码来源:test_resultset.py

示例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 
开发者ID:apache,项目名称:incubator-superset,代码行数:6,代码来源:pinot.py

示例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 
开发者ID:apache,项目名称:incubator-superset,代码行数:14,代码来源:base.py

示例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 
开发者ID:aio-libs,项目名称:aiomysql,代码行数:38,代码来源:result.py

示例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 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:54,代码来源:columns.py


注:本文中的sqlalchemy.sql.expression.ColumnElement方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。