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


Python sqlalchemy.column方法代码示例

本文整理汇总了Python中sqlalchemy.column方法的典型用法代码示例。如果您正苦于以下问题:Python sqlalchemy.column方法的具体用法?Python sqlalchemy.column怎么用?Python sqlalchemy.column使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sqlalchemy的用法示例。


在下文中一共展示了sqlalchemy.column方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _clone

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def _clone(self):
        """Create a shallow copy of this ClauseElement.

        This method may be used by a generative API.  Its also used as
        part of the "deep" copy afforded by a traversal that combines
        the _copy_internals() method.

        """
        c = self.__class__.__new__(self.__class__)
        c.__dict__ = self.__dict__.copy()
        ClauseElement._cloned_set._reset(c)
        ColumnElement.comparator._reset(c)

        # this is a marker that helps to "equate" clauses to each other
        # when a Select returns its list of FROM clauses.  the cloning
        # process leaves around a lot of remnants of the previous clause
        # typically in the form of column expressions still attached to the
        # old table.
        c._is_clone_of = self

        return c 
开发者ID:jpush,项目名称:jbox,代码行数:23,代码来源:elements.py

示例2: _find_columns

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def _find_columns(clause):
    """locate Column objects within the given expression."""

    cols = util.column_set()
    traverse(clause, {}, {'column': cols.add})
    return cols


# there is some inconsistency here between the usage of
# inspect() vs. checking for Visitable and __clause_element__.
# Ideally all functions here would derive from inspect(),
# however the inspect() versions add significant callcount
# overhead for critical functions like _interpret_as_column_or_from().
# Generally, the column-based functions are more performance critical
# and are fine just checking for __clause_element__().  It is only
# _interpret_as_from() where we'd like to be able to receive ORM entities
# that have no defined namespace, hence inspect() is needed there. 
开发者ID:jpush,项目名称:jbox,代码行数:19,代码来源:elements.py

示例3: migrate_pools

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def migrate_pools():
    conn = op.get_bind()
    lb_table = sa.sql.table(
        'load_balancer',
        sa.sql.column('id', sa.String),
        sa.sql.column('provider', sa.String),
        sa.sql.column('provisioning_status', sa.String))
    pool_table = sa.sql.table(
        'pool',
        sa.sql.column('id', sa.String),
        sa.sql.column('load_balancer_id', sa.String),
        sa.sql.column('lb_algorithm', sa.String))

    j = pool_table.join(lb_table,
                        pool_table.c.load_balancer_id == lb_table.c.id)
    stmt = sa.select([pool_table.c.id]).select_from(j).where(
        lb_table.c.provider == 'ovn')
    result = conn.execute(stmt)

    for row in result:
        stmt = pool_table.update().values(lb_algorithm='SOURCE_IP_PORT').where(
            pool_table.c.id == row[0])
        op.execute(stmt) 
开发者ID:openstack,项目名称:octavia,代码行数:25,代码来源:dcf88e59aae4_add_lb_algorithm_source_ip_port.py

示例4: _cast

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def _cast(t, expr):
    arg, typ = expr.op().args

    sa_arg = t.translate(arg)
    sa_type = t.get_sqla_type(typ)

    # specialize going from an integer type to a timestamp
    if isinstance(arg.type(), dt.Integer) and isinstance(sa_type, sa.DateTime):
        return sa.func.timezone('UTC', sa.func.to_timestamp(sa_arg))

    if arg.type().equals(dt.binary) and typ.equals(dt.string):
        return sa.func.encode(sa_arg, 'escape')

    if typ.equals(dt.binary):
        #  decode yields a column of memoryview which is annoying to deal with
        # in pandas. CAST(expr AS BYTEA) is correct and returns byte strings.
        return sa.cast(sa_arg, sa.LargeBinary())

    return sa.cast(sa_arg, sa_type) 
开发者ID:ibis-project,项目名称:ibis,代码行数:21,代码来源:compiler.py

示例5: postgresql_array_search

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def postgresql_array_search(element, compiler, **kw):
    needle, haystack = element.clauses
    i = sa.func.generate_subscripts(haystack, 1).alias('i')
    c0 = sa.column('i', type_=sa.INTEGER(), _selectable=i)
    result = (
        sa.func.coalesce(
            sa.select([c0])
            .where(haystack[c0].op('IS NOT DISTINCT FROM')(needle))
            .order_by(c0)
            .limit(1)
            .as_scalar(),
            0,
        )
        - 1
    )
    string_result = compiler.process(result, **kw)
    return string_result 
开发者ID:ibis-project,项目名称:ibis,代码行数:19,代码来源:compiler.py

示例6: _table_column

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def _table_column(t, expr):
    op = expr.op()
    ctx = t.context
    table = op.table

    sa_table = _get_sqla_table(ctx, table)
    out_expr = getattr(sa_table.c, op.name)

    expr_type = expr.type()

    if isinstance(expr_type, dt.Timestamp):
        timezone = expr_type.timezone
        if timezone is not None:
            out_expr = out_expr.op('AT TIME ZONE')(timezone).label(op.name)

    # If the column does not originate from the table set in the current SELECT
    # context, we should format as a subquery
    if t.permit_subquery and ctx.is_foreign_expr(table):
        return sa.select([out_expr])

    return out_expr 
开发者ID:ibis-project,项目名称:ibis,代码行数:23,代码来源:compiler.py

示例7: schema_from_table

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def schema_from_table(table, schema=None):
    """Retrieve an ibis schema from a SQLAlchemy ``Table``.

    Parameters
    ----------
    table : sa.Table

    Returns
    -------
    schema : ibis.expr.datatypes.Schema
        An ibis schema corresponding to the types of the columns in `table`.
    """
    schema = schema if schema is not None else {}
    pairs = []
    for name, column in table.columns.items():
        if name in schema:
            dtype = dt.dtype(schema[name])
        else:
            dtype = dt.dtype(
                getattr(table.bind, 'dialect', SQLAlchemyDialect()),
                column.type,
                nullable=column.nullable,
            )
        pairs.append((name, dtype))
    return sch.schema(pairs) 
开发者ID:ibis-project,项目名称:ibis,代码行数:27,代码来源:alchemy.py

示例8: _maybe_to_geodataframe

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def _maybe_to_geodataframe(df, schema):
    """
    If the required libraries for geospatial support are installed, and if a
    geospatial column is present in the dataframe, convert it to a
    GeoDataFrame.
    """

    def to_shapely(row, name):
        return shape.to_shape(row[name]) if row[name] is not None else None

    if len(df) and geospatial_supported:
        geom_col = None
        for name, dtype in schema.items():
            if isinstance(dtype, dt.GeoSpatial):
                geom_col = geom_col or name
                df[name] = df.apply(lambda x: to_shapely(x, name), axis=1)
        if geom_col:
            df = geopandas.GeoDataFrame(df, geometry=geom_col)
    return df 
开发者ID:ibis-project,项目名称:ibis,代码行数:21,代码来源:alchemy.py

示例9: __init__

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def __init__(self, x):
        if isinstance(x, str):
            x = column(x)
        if _get_order_direction(x) is None:
            x = asc(x)
        self.uo = x
        _warn_if_nullable(self.comparable_value)
        self.full_name = str(self.element)
        try:
            table_name, name = self.full_name.split('.', 1)
        except ValueError:
            table_name = None
            name = self.full_name

        self.table_name = table_name
        self.name = name 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:18,代码来源:columns.py

示例10: test_order_manipulation

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def test_order_manipulation():
    is_asc = lambda c: _get_order_direction(c) == asc_op
    flip = _reverse_order_direction
    scrub = _remove_order_direction
    base = column('a')
    l = base.label('test')
    a = asc(base)
    d = desc(base)
    assert is_asc(a)
    assert not is_asc(d)
    equal_pairs = [
        (scrub(a), base),
        (scrub(d), base),
        (scrub(asc(l)), scrub(a.label('test'))),
        (flip(a), d),
        (flip(d), a),
    ]
    for lhs, rhs in equal_pairs:
        assert str(lhs) == str(rhs) 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:21,代码来源:test_internals.py

示例11: get_sessions

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def get_sessions(
        self,
        session_names: Container[str],
        field=None,
        allow_stale=False,
        db_connection=None,
    ):
        '''
        Batched version of :meth:`get_session() <AgentRegistry.get_session>`.
        The order of the returend array is same to the order of ``sess_ids``.
        For non-existent or missing kernel IDs, it fills None in their
        positions without raising SessionNotFound exception.
        '''

        cols = [kernels.c.id, kernels.c.sess_id,
                kernels.c.agent_addr, kernels.c.kernel_host, kernels.c.access_key,
                kernels.c.service_ports]
        if isinstance(field, (tuple, list)):
            cols.extend(field)
        elif isinstance(field, (sa.Column, sa.sql.elements.ColumnClause)):
            cols.append(field)
        elif isinstance(field, str):
            cols.append(sa.column(field))
        async with reenter_txn(self.dbpool, db_connection) as conn:
            if allow_stale:
                query = (sa.select(cols)
                           .select_from(kernels)
                           .where((kernels.c.sess_id.in_(session_names)) &
                                  (kernels.c.role == 'master')))
            else:
                query = (sa.select(cols)
                           .select_from(kernels.join(agents))
                           .where((kernels.c.sess_id.in_(session_names)) &
                                  (kernels.c.role == 'master') &
                                  (agents.c.status == AgentStatus.ALIVE) &
                                  (agents.c.id == kernels.c.agent)))
            result = await conn.execute(query)
            rows = await result.fetchall()
            return rows 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:41,代码来源:registry.py

示例12: params

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def params(self, *optionaldict, **kwargs):
        """Return a copy with :func:`bindparam()` elements replaced.

        Returns a copy of this ClauseElement with :func:`bindparam()`
        elements replaced with values taken from the given dictionary::

          >>> clause = column('x') + bindparam('foo')
          >>> print clause.compile().params
          {'foo':None}
          >>> print clause.params({'foo':7}).compile().params
          {'foo':7}

        """
        return self._params(False, optionaldict, kwargs) 
开发者ID:jpush,项目名称:jbox,代码行数:16,代码来源:elements.py

示例13: expression

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def expression(self):
        """Return a column expression.

        Part of the inspection interface; returns self.

        """
        return self 
开发者ID:jpush,项目名称:jbox,代码行数:9,代码来源:elements.py

示例14: compare

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def compare(self, other, use_proxies=False, equivalents=None, **kw):
        """Compare this ColumnElement to another.

        Special arguments understood:

        :param use_proxies: when True, consider two columns that
          share a common base column as equivalent (i.e. shares_lineage())

        :param equivalents: a dictionary of columns as keys mapped to sets
          of columns. If the given "other" column is present in this
          dictionary, if any of the columns in the corresponding set() pass
          the comparison test, the result is True. This is used to expand the
          comparison to other columns that may be known to be equivalent to
          this one via foreign key or other criterion.

        """
        to_compare = (other, )
        if equivalents and other in equivalents:
            to_compare = equivalents[other].union(to_compare)

        for oth in to_compare:
            if use_proxies and self.shares_lineage(oth):
                return True
            elif hash(oth) == hash(self):
                return True
        else:
            return False 
开发者ID:jpush,项目名称:jbox,代码行数:29,代码来源:elements.py

示例15: label

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import column [as 别名]
def label(self, name):
        """Produce a column label, i.e. ``<columnname> AS <name>``.

        This is a shortcut to the :func:`~.expression.label` function.

        if 'name' is None, an anonymous label name will be generated.

        """
        return Label(name, self, self.type) 
开发者ID:jpush,项目名称:jbox,代码行数:11,代码来源:elements.py


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