當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。