Python sqlalchemy.sql.expression.ColumnElement() Examples

The following are 15 code examples of sqlalchemy.sql.expression.ColumnElement(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.sql.expression , or try the search function .
Example #1
Source File: columns.py    From sqlakeyset with The Unlicense 6 votes vote down vote up
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 
Example #2
Source File: columns.py    From sqlakeyset with The Unlicense 6 votes vote down vote up
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 
Example #3
Source File: helpers.py    From planespotter with MIT License 6 votes vote down vote up
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 
Example #4
Source File: test_query.py    From sqlalchemy with MIT License 6 votes vote down vote up
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,)]) 
Example #5
Source File: test_query.py    From sqlalchemy with MIT License 6 votes vote down vote up
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)",
        ) 
Example #6
Source File: columns.py    From sqlakeyset with The Unlicense 5 votes vote down vote up
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 
Example #7
Source File: columns.py    From sqlakeyset with The Unlicense 5 votes vote down vote up
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 
Example #8
Source File: result.py    From aiopg with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #9
Source File: test_resultset.py    From sqlalchemy with MIT License 5 votes vote down vote up
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) 
Example #10
Source File: test_resultset.py    From sqlalchemy with MIT License 5 votes vote down vote up
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) 
Example #11
Source File: test_resultset.py    From sqlalchemy with MIT License 5 votes vote down vote up
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]
            ) 
Example #12
Source File: pinot.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def make_select_compatible(
        cls, groupby_exprs: Dict[str, ColumnElement], select_exprs: List[ColumnElement]
    ) -> List[ColumnElement]:
        return select_exprs 
Example #13
Source File: base.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
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 
Example #14
Source File: result.py    From aiomysql with MIT License 5 votes vote down vote up
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 
Example #15
Source File: columns.py    From sqlakeyset with The Unlicense 4 votes vote down vote up
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