Python sqlalchemy.table() Examples

The following are 30 code examples of sqlalchemy.table(). 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 , or try the search function .
Example #1
Source File: elements.py    From jbox with MIT License 6 votes vote down vote up
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 
Example #2
Source File: alchemy.py    From ibis with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: elements.py    From sqlalchemy with MIT License 6 votes vote down vote up
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.

        """
        skip = self._memoized_keys
        c = self.__class__.__new__(self.__class__)
        c.__dict__ = {k: v for k, v in self.__dict__.items() if k not in skip}

        # 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 
Example #4
Source File: elements.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: elements.py    From planespotter with MIT License 6 votes vote down vote up
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 
Example #6
Source File: 16_a1ed2f75cb13_.py    From betterlifepsi with MIT License 6 votes vote down vote up
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    role_table = sa.table('role',
                          sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
                          sa.Column('name', sa.String(length=80), nullable=False),
                          sa.Column('description', sa.String(length=255), nullable=True),
                          sa.Column('parent_id', sa.Integer(), nullable=True),
                          )
    res = op.get_bind().execute('SELECT max(id)+1 FROM role')
    cm = 46
    for r in res.fetchall():
        cm = r[0]
    op.bulk_insert(role_table, [
        {'id': cm, 'name': 'import_store_data', 'description': u'导入店铺运营数据', 'parent_id': None},
    ], multiinsert=False)
    from sqlalchemy.sql import text
    op.get_bind().execute(text("ALTER SEQUENCE role_id_seq RESTART WITH " + str(cm + 1) + ";"))
    ### end Alembic commands ### 
Example #7
Source File: alchemy.py    From ibis with Apache License 2.0 6 votes vote down vote up
def _can_lower_sort_column(table_set, expr):
    # TODO(wesm): This code is pending removal through cleaner internal
    # semantics

    # we can currently sort by just-appeared aggregate metrics, but the way
    # these are references in the expression DSL is as a SortBy (blocking
    # table operation) on an aggregation. There's a hack in _collect_SortBy
    # in the generic SQL compiler that "fuses" the sort with the
    # aggregation so they appear in same query. It's generally for
    # cosmetics and doesn't really affect query semantics.
    bases = ops.find_all_base_tables(expr)
    if len(bases) > 1:
        return False

    base = list(bases.values())[0]
    base_op = base.op()

    if isinstance(base_op, ops.Aggregation):
        return base_op.table.equals(table_set)
    elif isinstance(base_op, ops.Selection):
        return base.equals(table_set)
    else:
        return False 
Example #8
Source File: dcf88e59aae4_add_lb_algorithm_source_ip_port.py    From octavia with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: alchemy.py    From ibis with Apache License 2.0 6 votes vote down vote up
def invalidates_reflection_cache(f):
    """Invalidate the SQLAlchemy reflection cache if `f` performs an operation
    that mutates database or table metadata such as ``CREATE TABLE``,
    ``DROP TABLE``, etc.

    Parameters
    ----------
    f : callable
        A method on :class:`ibis.sql.alchemy.AlchemyClient`
    """

    @functools.wraps(f)
    def wrapped(self, *args, **kwargs):
        result = f(self, *args, **kwargs)

        # only invalidate the cache after we've succesfully called the wrapped
        # function
        self._reflection_cache_is_dirty = True
        return result

    return wrapped 
Example #10
Source File: elements.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #11
Source File: database.py    From spice-hate_speech_detection with MIT License 5 votes vote down vote up
def get_users_n_tweets(self):
        table = sqlalchemy.table('tweets', Column('screen_name', Text), Column('text', Text))
        statement = table.select()
        results = self.engine.execute(statement)
        rows = results.fetchall()
        # TODO: There must be a more intelligent way to the get the first item
        # from each item in the list
        tweets = [] #* len(rows)
        screen_names = [] #* len(rows)
        print(len(rows))
        for i in range(0, len(rows)):
            #print(len(rows[i]))
            screen_names.append(rows[i][0])
            tweets.append(rows[i][1])
        return screen_names, tweets 
Example #12
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def _gen_label(self, name):
        t = self.table

        if self.is_literal:
            return None

        elif t is not None and t.named_with_column:
            if getattr(t, 'schema', None):
                label = t.schema.replace('.', '_') + "_" + \
                    t.name + "_" + name
            else:
                label = t.name + "_" + name

            # propagate name quoting rules for labels.
            if getattr(name, "quote", None) is not None:
                if isinstance(label, quoted_name):
                    label.quote = name.quote
                else:
                    label = quoted_name(label, name.quote)
            elif getattr(t.name, "quote", None) is not None:
                # can't get this situation to occur, so let's
                # assert false on it for now
                assert not isinstance(label, quoted_name)
                label = quoted_name(label, t.name.quote)

            # ensure the label name doesn't conflict with that
            # of an existing column
            if label in t.c:
                _label = label
                counter = 1
                while _label in t.c:
                    _label = label + "_" + str(counter)
                    counter += 1
                label = _label

            return _as_truncated(label)

        else:
            return name 
Example #13
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def __init__(self, element, values):
        Annotated.__init__(self, element, values)
        ColumnElement.comparator._reset(self)
        for attr in ('name', 'key', 'table'):
            if self.__dict__.get(attr, False) is None:
                self.__dict__.pop(attr) 
Example #14
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def _set_table(self, table):
        self._memoized_property.expire_instance(self)
        self.__dict__['table'] = table 
Example #15
Source File: elements.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def _gen_label(self, name):
        t = self.table

        if self.is_literal:
            return None

        elif t is not None and t.named_with_column:
            if getattr(t, 'schema', None):
                label = t.schema.replace('.', '_') + "_" + \
                    t.name + "_" + name
            else:
                label = t.name + "_" + name

            # propagate name quoting rules for labels.
            if getattr(name, "quote", None) is not None:
                if isinstance(label, quoted_name):
                    label.quote = name.quote
                else:
                    label = quoted_name(label, name.quote)
            elif getattr(t.name, "quote", None) is not None:
                # can't get this situation to occur, so let's
                # assert false on it for now
                assert not isinstance(label, quoted_name)
                label = quoted_name(label, t.name.quote)

            # ensure the label name doesn't conflict with that
            # of an existing column
            if label in t.c:
                _label = label
                counter = 1
                while _label in t.c:
                    _label = label + "_" + str(counter)
                    counter += 1
                label = _label

            return _as_truncated(label)

        else:
            return name 
Example #16
Source File: elements.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, element, values):
        Annotated.__init__(self, element, values)
        ColumnElement.comparator._reset(self)
        for attr in ('name', 'key', 'table'):
            if self.__dict__.get(attr, False) is None:
                self.__dict__.pop(attr) 
Example #17
Source File: elements.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def table(self):
        """pull 'table' from parent, if not present"""
        return self._Annotated__element.table 
Example #18
Source File: database.py    From spice-hate_speech_detection with MIT License 5 votes vote down vote up
def get_tweets(self):
        table = sqlalchemy.table('tweets', Column('text', Text))
        statement = table.select()
        results = self.engine.execute(statement)
        tweets = results.fetchall()
        # TODO: There must be a more intelligent way to the get the first item
        # from each item in the list
        for i in range(0, len(tweets)):
            tweets[i] = tweets[i][0]
        return tweets 
Example #19
Source File: elements.py    From sqlalchemy with MIT License 5 votes vote down vote up
def literal_column(text, type_=None):
    r"""Produce a :class:`.ColumnClause` object that has the
    :paramref:`_expression.column.is_literal` flag set to True.

    :func:`_expression.literal_column` is similar to
    :func:`_expression.column`, except that
    it is more often used as a "standalone" column expression that renders
    exactly as stated; while :func:`_expression.column`
    stores a string name that
    will be assumed to be part of a table and may be quoted as such,
    :func:`_expression.literal_column` can be that,
    or any other arbitrary column-oriented
    expression.

    :param text: the text of the expression; can be any SQL expression.
      Quoting rules will not be applied. To specify a column-name expression
      which should be subject to quoting rules, use the :func:`column`
      function.

    :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine`
      object which will
      provide result-set translation and additional expression semantics for
      this column. If left as ``None`` the type will be :class:`.NullType`.

    .. seealso::

        :func:`_expression.column`

        :func:`_expression.text`

        :ref:`sqlexpression_literal_column`

    """
    return ColumnClause(text, type_=type_, is_literal=True) 
Example #20
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def _render_label_in_columns_clause(self):
        return self.table is not None 
Example #21
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def _from_objects(self):
        t = self.table
        if t is not None:
            return [t]
        else:
            return [] 
Example #22
Source File: resource_models.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def status_display(cls):
        table = cls.__table__
        cases = [
            (table.c.status == status, label)
            for status, label in cls.STATUS_DISPLAY_NAMES.items()
        ]
        return case(cases, else_=db.cast(table.c.status, db.Text)) 
Example #23
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def _get_table(self):
        return self.__dict__['table'] 
Example #24
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def _create_all(cls, expr):
        """Produce an ALL expression.

        This may apply to an array type for some dialects (e.g. postgresql),
        or to a subquery for others (e.g. mysql).  e.g.::

            # postgresql '5 = ALL (somearray)'
            expr = 5 == all_(mytable.c.somearray)

            # mysql '5 = ALL (SELECT value FROM table)'
            expr = 5 == all_(select([table.c.value]))

        .. versionadded:: 1.1

        .. seealso::

            :func:`.expression.any_`

        """

        expr = _literal_as_binds(expr)
        if expr.is_selectable and hasattr(expr, 'as_scalar'):
            expr = expr.as_scalar()
        expr = expr.self_group()
        return CollectionAggregate(
            expr, operator=operators.all_op,
            type_=type_api.NULLTYPE, wraps_column_expression=False)

    # operate and reverse_operate are hardwired to
    # dispatch onto the type comparator directly, so that we can
    # ensure "reversed" behavior. 
Example #25
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def _create_any(cls, expr):
        """Produce an ANY expression.

        This may apply to an array type for some dialects (e.g. postgresql),
        or to a subquery for others (e.g. mysql).  e.g.::

            # postgresql '5 = ANY (somearray)'
            expr = 5 == any_(mytable.c.somearray)

            # mysql '5 = ANY (SELECT value FROM table)'
            expr = 5 == any_(select([table.c.value]))

        .. versionadded:: 1.1

        .. seealso::

            :func:`.expression.all_`

        """

        expr = _literal_as_binds(expr)

        if expr.is_selectable and hasattr(expr, 'as_scalar'):
            expr = expr.as_scalar()
        expr = expr.self_group()
        return CollectionAggregate(
            expr, operator=operators.any_op,
            type_=type_api.NULLTYPE, wraps_column_expression=False) 
Example #26
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def literal_column(text, type_=None):
    r"""Produce a :class:`.ColumnClause` object that has the
    :paramref:`.column.is_literal` flag set to True.

    :func:`.literal_column` is similar to :func:`.column`, except that
    it is more often used as a "standalone" column expression that renders
    exactly as stated; while :func:`.column` stores a string name that
    will be assumed to be part of a table and may be quoted as such,
    :func:`.literal_column` can be that, or any other arbitrary column-oriented
    expression.

    :param text: the text of the expression; can be any SQL expression.
      Quoting rules will not be applied. To specify a column-name expression
      which should be subject to quoting rules, use the :func:`column`
      function.

    :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine`
      object which will
      provide result-set translation and additional expression semantics for
      this column. If left as None the type will be NullType.

    .. seealso::

        :func:`.column`

        :func:`.text`

        :ref:`sqlexpression_literal_column`

    """
    return ColumnClause(text, type_=type_, is_literal=True) 
Example #27
Source File: elements.py    From planespotter with MIT License 5 votes vote down vote up
def __init__(self, *clauses, **kw):
        """Return a :class:`.Tuple`.

        Main usage is to produce a composite IN construct::

            from sqlalchemy import tuple_

            tuple_(table.c.col1, table.c.col2).in_(
                [(1, 2), (5, 12), (10, 19)]
            )

        .. warning::

            The composite IN construct is not supported by all backends,
            and is currently known to work on PostgreSQL and MySQL,
            but not SQLite.   Unsupported backends will raise
            a subclass of :class:`~sqlalchemy.exc.DBAPIError` when such
            an expression is invoked.

        """

        clauses = [_literal_as_binds(c) for c in clauses]
        self._type_tuple = [arg.type for arg in clauses]
        self.type = kw.pop('type_', self._type_tuple[0]
                           if self._type_tuple else type_api.NULLTYPE)

        super(Tuple, self).__init__(*clauses, **kw) 
Example #28
Source File: f5237c7e2374_create_scep_config_table.py    From commandment with MIT License 5 votes vote down vote up
def data_upgrades():
    tbl = sa.table(*TABLE[:-1])

    op.bulk_insert(tbl, [
        DEMO_SCEP_CONFIG
    ]) 
Example #29
Source File: resource_models.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def actual_number_of_instances(cls):
        ni_table = table('node_instances', column('id'), column('_node_fk'))
        return (select([func.count(ni_table.c.id)]).
                where(ni_table.c._node_fk == cls._storage_id).
                label("actual_number_of_instances")) 
Example #30
Source File: elements.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _corresponding_column_or_error(fromclause, column,
                                   require_embedded=False):
    c = fromclause.corresponding_column(column,
                                        require_embedded=require_embedded)
    if c is None:
        raise exc.InvalidRequestError(
            "Given column '%s', attached to table '%s', "
            "failed to locate a corresponding column from table '%s'"
            %
            (column,
             getattr(column, 'table', None),
             fromclause.description)
        )
    return c