我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sqlalchemy.column()。
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
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.
def set_nullable_columns_default_values(): role = sa.table(u'jobs', sa.column(u'address_is_valid')) op.execute(role.update().values(address_is_valid=True)) role = sa.table(u'jobs', sa.column(u'geolocation_is_valid')) op.execute(role.update().values(geolocation_is_valid=True)) role = sa.table(u'jobs', sa.column(u'last_sync')) op.execute(role.update().values(last_sync=datetime(1970, 1, 1))) role = sa.table(u'jobs', sa.column(u'latitude')) op.execute(role.update().values(latitude=0.0)) role = sa.table(u'jobs', sa.column(u'longitude')) op.execute(role.update().values(longitude=0.0)) role = sa.table(u'jobs', sa.column(u'pushed_on_twitter')) op.execute(role.update().values(pushed_on_twitter=True)) role = sa.table(u'jobs', sa.column(u'publication_datetime_is_fake')) op.execute(role.update() .where(role.c.publication_datetime_is_fake == None) .values(publication_datetime_is_fake=False))
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)
def expression(self): """Return a column expression. Part of the inspection interface; returns self. """ return self
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
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)
def literal_column(text, type_=None): """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)
def _create_nullsfirst(cls, column): """Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression. :func:`.nullsfirst` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled when they are encountered during ordering:: from sqlalchemy import desc, nullsfirst stmt = select([users_table]).\\ order_by(nullsfirst(desc(users_table.c.name))) The SQL expression from the above would resemble:: SELECT id, name FROM user ORDER BY name DESC NULLS FIRST Like :func:`.asc` and :func:`.desc`, :func:`.nullsfirst` is typically invoked from the column expression itself using :meth:`.ColumnElement.nullsfirst`, rather than as its standalone function version, as in:: stmt = (select([users_table]). order_by(users_table.c.name.desc().nullsfirst()) ) .. seealso:: :func:`.asc` :func:`.desc` :func:`.nullslast` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.nullsfirst_op, wraps_column_expression=False)
def _create_desc(cls, column): """Produce a descending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import desc stmt = select([users_table]).order_by(desc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name DESC The :func:`.desc` function is a standalone version of the :meth:`.ColumnElement.desc` method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.desc()) :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.desc` operation. .. seealso:: :func:`.asc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.desc_op, wraps_column_expression=False)
def _create_asc(cls, column): """Produce an ascending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import asc stmt = select([users_table]).order_by(asc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name ASC The :func:`.asc` function is a standalone version of the :meth:`.ColumnElement.asc` method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.asc()) :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.asc` operation. .. seealso:: :func:`.desc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.asc_op, wraps_column_expression=False)
def _create_distinct(cls, expr): """Produce an column-expression-level unary ``DISTINCT`` clause. This applies the ``DISTINCT`` keyword to an individual column expression, and is typically contained within an aggregate function, as in:: from sqlalchemy import distinct, func stmt = select([func.count(distinct(users_table.c.name))]) The above would produce an expression resembling:: SELECT COUNT(DISTINCT name) FROM user The :func:`.distinct` function is also available as a column-level method, e.g. :meth:`.ColumnElement.distinct`, as in:: stmt = select([func.count(users_table.c.name.distinct())]) The :func:`.distinct` operator is different from the :meth:`.Select.distinct` method of :class:`.Select`, which produces a ``SELECT`` statement with ``DISTINCT`` applied to the result set as a whole, e.g. a ``SELECT DISTINCT`` expression. See that method for further information. .. seealso:: :meth:`.ColumnElement.distinct` :meth:`.Select.distinct` :data:`.func` """ expr = _literal_as_binds(expr) return UnaryExpression( expr, operator=operators.distinct_op, type_=expr.type, wraps_column_expression=False)
def __init__(self, func, partition_by=None, order_by=None): """Produce an :class:`.Over` object against a function. Used against aggregate or so-called "window" functions, for database backends that support window functions. E.g.:: from sqlalchemy import over over(func.row_number(), order_by='x') Would produce "ROW_NUMBER() OVER(ORDER BY x)". :param func: a :class:`.FunctionElement` construct, typically generated by :data:`~.expression.func`. :param partition_by: a column element or string, or a list of such, that will be used as the PARTITION BY clause of the OVER construct. :param order_by: a column element or string, or a list of such, that will be used as the ORDER BY clause of the OVER construct. This function is also available from the :data:`~.expression.func` construct itself via the :meth:`.FunctionElement.over` method. .. versionadded:: 0.7 """ self.func = func if order_by is not None: self.order_by = ClauseList( *util.to_list(order_by), _literal_as_text=_literal_as_label_reference) if partition_by is not None: self.partition_by = ClauseList( *util.to_list(partition_by), _literal_as_text=_literal_as_label_reference)
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
def _interpret_as_column_or_from(element): if isinstance(element, Visitable): return element elif hasattr(element, '__clause_element__'): return element.__clause_element__() insp = inspection.inspect(element, raiseerr=False) if insp is None: if isinstance(element, (util.NoneType, bool)): return _const_expr(element) elif hasattr(insp, "selectable"): return insp.selectable # be forgiving as this is an extremely common # and known expression if element == "*": guess_is_literal = True elif isinstance(element, (numbers.Number)): return ColumnClause(str(element), is_literal=True) else: element = str(element) # give into temptation, as this fact we are guessing about # is not one we've previously ever needed our users tell us; # but let them know we are not happy about it guess_is_literal = not _guess_straight_column.match(element) util.warn_limited( "Textual column expression %(column)r should be " "explicitly declared with text(%(column)r), " "or use %(literal_column)s(%(column)r) " "for more specificity", { "column": util.ellipses_string(element), "literal_column": "literal_column" if guess_is_literal else "column" }) return ColumnClause( element, is_literal=guess_is_literal)
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
def __init__(self, x): if isinstance(x, unicode): x = column(x) if not isinstance(x, UnaryExpression): x = asc(x) self.uo = x 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
def do_core_tests(dburl): spec = ['b', 'd', 'id', 'c'] cols = [column(each) for each in spec] ob = [OC(x).uo for x in spec] with S(dburl, echo=ECHO) as s: selectable = select( cols, from_obj=[table('t_Book')], whereclause=column('d') == 99, order_by=ob) check_paging(selectable=selectable, s=s)