desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'return a SQL UNION ALL of this select() construct against the given selectable.'
def union_all(self, other, **kwargs):
return CompoundSelect._create_union_all(self, other, **kwargs)
'return a SQL EXCEPT of this select() construct against the given selectable.'
def except_(self, other, **kwargs):
return CompoundSelect._create_except(self, other, **kwargs)
'return a SQL EXCEPT ALL of this select() construct against the given selectable.'
def except_all(self, other, **kwargs):
return CompoundSelect._create_except_all(self, other, **kwargs)
'return a SQL INTERSECT of this select() construct against the given selectable.'
def intersect(self, other, **kwargs):
return CompoundSelect._create_intersect(self, other, **kwargs)
'return a SQL INTERSECT ALL of this select() construct against the given selectable.'
def intersect_all(self, other, **kwargs):
return CompoundSelect._create_intersect_all(self, other, **kwargs)
'Apply a WHERE clause to the SELECT statement referred to by this :class:`.ScalarSelect`.'
@_generative def where(self, crit):
self.element = self.element.where(crit)
'Construct a new :class:`.Exists` against an existing :class:`.Select` object. Calling styles are of the following forms:: # use on an existing select() s = select([table.c.col1]).where(table.c.col2==5) s = exists(s) # construct a select() at once exists([\'*\'], **select_arguments).where(criterion) # columns argument ...
def __init__(self, *args, **kwargs):
if (args and isinstance(args[0], (SelectBase, ScalarSelect))): s = args[0] else: if (not args): args = ([literal_column('*')],) s = Select(*args, **kwargs).as_scalar().self_group() UnaryExpression.__init__(self, s, operator=operators.exists, type_=type_api.BOOLEANTYPE)
'return a new :class:`.Exists` construct, applying the given expression to the :meth:`.Select.select_from` method of the select statement contained.'
def select_from(self, clause):
e = self._clone() e.element = self.element.select_from(clause).self_group() return e
'return a new exists() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.'
def where(self, clause):
e = self._clone() e.element = self.element.where(clause).self_group() return e
'Add a new kind of dialect-specific keyword argument for this class. E.g.:: Index.argument_for("mydialect", "length", None) some_index = Index(\'a\', \'b\', mydialect_length=5) The :meth:`.DialectKWArgs.argument_for` method is a per-argument way adding extra arguments to the :attr:`.DefaultDialect.construct_arguments` ...
@classmethod def argument_for(cls, dialect_name, argument_name, default):
construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name] if (construct_arg_dictionary is None): raise exc.ArgumentError(("Dialect '%s' does have keyword-argument validation and defaults enabled configured" % dialect_name)) construct_arg_dictionary[cls][argument_...
'A collection of keyword arguments specified as dialect-specific options to this construct. The arguments are present here in their original ``<dialect>_<kwarg>`` format. Only arguments that were actually passed are included; unlike the :attr:`.DialectKWArgs.dialect_options` collection, which contains all options know...
@util.memoized_property def dialect_kwargs(self):
return _DialectArgView(self)
'A synonym for :attr:`.DialectKWArgs.dialect_kwargs`.'
@property def kwargs(self):
return self.dialect_kwargs
'A collection of keyword arguments specified as dialect-specific options to this construct. This is a two-level nested registry, keyed to ``<dialect_name>`` and ``<argument_name>``. For example, the ``postgresql_where`` argument would be locatable as:: arg = my_object.dialect_options[\'postgresql\'][\'where\'] .. vers...
@util.memoized_property def dialect_options(self):
return util.PopulateDict(util.portable_instancemethod(self._kw_reg_for_dialect_cls))
'Set non-SQL options for the statement which take effect during execution. Execution options can be set on a per-statement or per :class:`.Connection` basis. Additionally, the :class:`.Engine` and ORM :class:`~.orm.query.Query` objects provide access to execution options which they in turn configure upon connections....
@_generative def execution_options(self, **kw):
if ('isolation_level' in kw): raise exc.ArgumentError("'isolation_level' execution option may only be specified on Connection.execution_options(), or per-engine using the isolation_level argument to create_engine().") if ('compiled_cache' in kw): r...
'Compile and execute this :class:`.Executable`.'
def execute(self, *multiparams, **params):
e = self.bind if (e is None): label = getattr(self, 'description', self.__class__.__name__) msg = ('This %s is not directly bound to a Connection or Engine.Use the .execute() method of a Connection or Engine to execute this constr...
'Compile and execute this :class:`.Executable`, returning the result\'s scalar representation.'
def scalar(self, *multiparams, **params):
return self.execute(*multiparams, **params).scalar()
'Returns the :class:`.Engine` or :class:`.Connection` to which this :class:`.Executable` is bound, or None if none found. This is a traversal which checks locally, then checks among the "from" clauses of associated objects until a bound engine or connection is found.'
@property def bind(self):
if (self._bind is not None): return self._bind for f in _from_objects(self): if (f is self): continue engine = f.bind if (engine is not None): return engine else: return None
'Associate with this SchemaEvent\'s parent object.'
def _set_parent(self, parent):
raise NotImplementedError()
'add the given column to this collection, removing unaliased versions of this column as well as existing columns with the same key. e.g.:: t = Table(\'sometable\', metadata, Column(\'col1\', Integer)) t.columns.replace(Column(\'col1\', Integer, key=\'columnone\')) will remove the original \'col1\' from the collection,...
def replace(self, column):
remove_col = None if ((column.name in self) and (column.key != column.name)): other = self[column.name] if (other.name == other.key): remove_col = other self._all_col_set.remove(other) del self._data[other.key] if (column.key in self._data): remove...
'Add a column to this collection. The key attribute of the column will be used as the hash key for this dictionary.'
def add(self, column):
self[column.key] = column
'evaluate the return type of <self> <op> <othertype>, and apply any adaptations to the given operator. This method determines the type of a resulting binary expression given two source types and an operator. For example, two :class:`.Column` objects, both of the type :class:`.Integer`, will produce a :class:`.BinaryE...
def _adapt_expression(self, op, other_comparator):
return (op, other_comparator.type)
'See :meth:`.ColumnOperators.__neg__`.'
def _neg_impl(self, expr, op, **kw):
return UnaryExpression(expr, operator=operators.neg)
'See :meth:`.ColumnOperators.match`.'
def _match_impl(self, expr, op, other, **kw):
return self._boolean_compare(expr, operators.match_op, self._check_literal(expr, operators.match_op, other))
'See :meth:`.ColumnOperators.distinct`.'
def _distinct_impl(self, expr, op, **kw):
return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type)
'See :meth:`.ColumnOperators.between`.'
def _between_impl(self, expr, op, cleft, cright, **kw):
return BinaryExpression(expr, ClauseList(self._check_literal(expr, operators.and_, cleft), self._check_literal(expr, operators.and_, cright), operator=operators.and_, group=False, group_contents=False), operators.between_op)
'Return a conversion function for processing literal values that are to be rendered directly without using binds. This function is used when the compiler makes use of the "literal_binds" flag, typically used in DDL generation as well as in certain scenarios where backends don\'t accept bound parameters. .. versionadded...
def literal_processor(self, dialect):
return None
'Return a conversion function for processing bind values. Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API. If processing is not necessary, the method should return ``None``. :param dialect: Dialect instance in use.'
def bind_processor(self, dialect):
return None
'Return a conversion function for processing result row values. Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user. If processing is not necessary, the method should return ``None``. :param dialect: Dialect instance in use. :para...
def result_processor(self, dialect, coltype):
return None
'Given a SELECT column expression, return a wrapping SQL expression. This is typically a SQL function that wraps a column expression as rendered in the columns clause of a SELECT statement. It is used for special data types that require columns to be wrapped in some special database function in order to coerce the valu...
def column_expression(self, colexpr):
return None
'memoized boolean, check if column_expression is implemented. Allows the method to be skipped for the vast majority of expression types that don\'t use this feature.'
@util.memoized_property def _has_column_expression(self):
return (self.__class__.column_expression.__code__ is not TypeEngine.column_expression.__code__)
'"Given a bind value (i.e. a :class:`.BindParameter` instance), return a SQL expression in its place. This is typically a SQL function that wraps the existing bound parameter within the statement. It is used for special data types that require literals being wrapped in some special database function in order to coerce...
def bind_expression(self, bindvalue):
return None
'memoized boolean, check if bind_expression is implemented. Allows the method to be skipped for the vast majority of expression types that don\'t use this feature.'
@util.memoized_property def _has_bind_expression(self):
return (self.__class__.bind_expression.__code__ is not TypeEngine.bind_expression.__code__)
'Compare two values for equality.'
def compare_values(self, x, y):
return (x == y)
'Return the corresponding type object from the underlying DB-API, if any. This can be useful for calling ``setinputsizes()``, for example.'
def get_dbapi_type(self, dbapi):
return None
'Return the Python type object expected to be returned by instances of this type, if known. Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like ``int`` for example), will return that type. If a return type is not defined, raises ``NotImplementedEr...
@property def python_type(self):
raise NotImplementedError()
'Produce a new type object that will utilize the given type when applied to the dialect of the given name. e.g.:: from sqlalchemy.types import String from sqlalchemy.dialects import mysql s = String() s = s.with_variant(mysql.VARCHAR(collation=\'foo\'), \'mysql\') The construction of :meth:`.TypeEngine.with_variant` is...
def with_variant(self, type_, dialect_name):
return Variant(self, {dialect_name: type_})
'Return a rudimental \'affinity\' value expressing the general class of type.'
@util.memoized_property def _type_affinity(self):
typ = None for t in self.__class__.__mro__: if (t in (TypeEngine, UserDefinedType)): return typ elif issubclass(t, (TypeEngine, UserDefinedType)): typ = t else: return self.__class__
'Return a dialect-specific implementation for this :class:`.TypeEngine`.'
def dialect_impl(self, dialect):
try: return dialect._type_memos[self]['impl'] except KeyError: return self._dialect_info(dialect)['impl']
'Return a dialect-specific literal processor for this type.'
def _cached_literal_processor(self, dialect):
try: return dialect._type_memos[self]['literal'] except KeyError: d = self._dialect_info(dialect) d['literal'] = lp = d['impl'].literal_processor(dialect) return lp
'Return a dialect-specific bind processor for this type.'
def _cached_bind_processor(self, dialect):
try: return dialect._type_memos[self]['bind'] except KeyError: d = self._dialect_info(dialect) d['bind'] = bp = d['impl'].bind_processor(dialect) return bp
'Return a dialect-specific result processor for this type.'
def _cached_result_processor(self, dialect, coltype):
try: return dialect._type_memos[self][coltype] except KeyError: d = self._dialect_info(dialect) d[coltype] = rp = d['impl'].result_processor(dialect, coltype) return rp
'Return a dialect-specific registry which caches a dialect-specific implementation, bind processing function, and one or more result processing functions.'
def _dialect_info(self, dialect):
if (self in dialect._type_memos): return dialect._type_memos[self] else: impl = self._gen_dialect_impl(dialect) if (impl is self): impl = self.adapt(type(self)) assert (impl is not self) dialect._type_memos[self] = d = {'impl': impl} return d
'Produce an "adapted" form of this type, given an "impl" class to work with. This method is used internally to associate generic types with "implementation" types that are specific to a particular dialect.'
def adapt(self, cls, **kw):
return util.constructor_copy(self, cls, **kw)
'Suggest a type for a \'coerced\' Python value in an expression. Given an operator and value, gives the type a chance to return a type which the value should be coerced into. The default behavior here is conservative; if the right-hand side is already coerced into a SQL type based on its Python type, it is usually left...
def coerce_compared_value(self, op, value):
_coerced_type = _type_map.get(type(value), NULLTYPE) if ((_coerced_type is NULLTYPE) or (_coerced_type._type_affinity is self._type_affinity)): return self else: return _coerced_type
'Produce a string-compiled form of this :class:`.TypeEngine`. When called with no arguments, uses a "default" dialect to produce a string result. :param dialect: a :class:`.Dialect` instance.'
def compile(self, dialect=None):
if (not dialect): dialect = self._default_dialect() return dialect.type_compiler.process(self)
'Suggest a type for a \'coerced\' Python value in an expression. Default behavior for :class:`.UserDefinedType` is the same as that of :class:`.TypeDecorator`; by default it returns ``self``, assuming the compared value should be coerced into the same type as this one. See :meth:`.TypeDecorator.coerce_compared_value` ...
def coerce_compared_value(self, op, value):
return self
'Construct a :class:`.TypeDecorator`. Arguments sent here are passed to the constructor of the class assigned to the ``impl`` class level attribute, assuming the ``impl`` is a callable, and the resulting object is assigned to the ``self.impl`` instance attribute (thus overriding the class attribute of the same name). I...
def __init__(self, *args, **kwargs):
if (not hasattr(self.__class__, 'impl')): raise AssertionError("TypeDecorator implementations require a class-level variable 'impl' which refers to the class of type being decorated") self.impl = to_instance(self.__class__.impl, *args, **kwargs)
'#todo'
def _gen_dialect_impl(self, dialect):
adapted = dialect.type_descriptor(self) if (adapted is not self): return adapted typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect) tt = self.copy() if (not isinstance(tt, self.__class__)): raise AssertionError(('Type object %s does not properly implem...
'#todo'
@property def _type_affinity(self):
return self.impl._type_affinity
'Return a dialect-specific :class:`.TypeEngine` instance for this :class:`.TypeDecorator`. In most cases this returns a dialect-adapted form of the :class:`.TypeEngine` type represented by ``self.impl``. Makes usage of :meth:`dialect_impl` but also traverses into wrapped :class:`.TypeDecorator` instances. Behavior can ...
def type_engine(self, dialect):
adapted = dialect.type_descriptor(self) if (type(adapted) is not type(self)): return adapted elif isinstance(self.impl, TypeDecorator): return self.impl.type_engine(dialect) else: return self.load_dialect_impl(dialect)
'Return a :class:`.TypeEngine` object corresponding to a dialect. This is an end-user override hook that can be used to provide differing types depending on the given dialect. It is used by the :class:`.TypeDecorator` implementation of :meth:`type_engine` to help determine what type should ultimately be returned for a...
def load_dialect_impl(self, dialect):
return self.impl
'Proxy all other undefined accessors to the underlying implementation.'
def __getattr__(self, key):
return getattr(self.impl, key)
'Receive a literal parameter value to be rendered inline within a statement. This method is used when the compiler renders a literal value without using binds, typically within DDL such as in the "server default" of a column or an expression within a CHECK constraint. The returned string will be rendered into the outpu...
def process_literal_param(self, value, dialect):
raise NotImplementedError()
'Receive a bound parameter value to be converted. Subclasses override this method to return the value that should be passed along to the underlying :class:`.TypeEngine` object, and from there to the DBAPI ``execute()`` method. The operation could be anything desired to perform custom behavior, such as transforming or s...
def process_bind_param(self, value, dialect):
raise NotImplementedError()
'Receive a result-row column value to be converted. Subclasses should implement this method to operate on data fetched from the database. Subclasses override this method to return the value that should be passed back to the application, given a value that is already processed by the underlying :class:`.TypeEngine` obje...
def process_result_value(self, value, dialect):
raise NotImplementedError()
'memoized boolean, check if process_bind_param is implemented. Allows the base process_bind_param to raise NotImplementedError without needing to test an expensive exception throw.'
@util.memoized_property def _has_bind_processor(self):
return (self.__class__.process_bind_param.__code__ is not TypeDecorator.process_bind_param.__code__)
'memoized boolean, check if process_literal_param is implemented.'
@util.memoized_property def _has_literal_processor(self):
return (self.__class__.process_literal_param.__code__ is not TypeDecorator.process_literal_param.__code__)
'Provide a literal processing function for the given :class:`.Dialect`. Subclasses here will typically override :meth:`.TypeDecorator.process_literal_param` instead of this method directly. By default, this method makes use of :meth:`.TypeDecorator.process_bind_param` if that method is implemented, where :meth:`.TypeDe...
def literal_processor(self, dialect):
if self._has_literal_processor: process_param = self.process_literal_param elif self._has_bind_processor: process_param = self.process_bind_param else: process_param = None if process_param: impl_processor = self.impl.literal_processor(dialect) if impl_processor: ...
'Provide a bound value processing function for the given :class:`.Dialect`. This is the method that fulfills the :class:`.TypeEngine` contract for bound value conversion. :class:`.TypeDecorator` will wrap a user-defined implementation of :meth:`process_bind_param` here. User-defined code can override this method dire...
def bind_processor(self, dialect):
if self._has_bind_processor: process_param = self.process_bind_param impl_processor = self.impl.bind_processor(dialect) if impl_processor: def process(value): return impl_processor(process_param(value, dialect)) else: def process(value): ...
'memoized boolean, check if process_result_value is implemented. Allows the base process_result_value to raise NotImplementedError without needing to test an expensive exception throw.'
@util.memoized_property def _has_result_processor(self):
return (self.__class__.process_result_value.__code__ is not TypeDecorator.process_result_value.__code__)
'Provide a result value processing function for the given :class:`.Dialect`. This is the method that fulfills the :class:`.TypeEngine` contract for result value conversion. :class:`.TypeDecorator` will wrap a user-defined implementation of :meth:`process_result_value` here. User-defined code can override this method ...
def result_processor(self, dialect, coltype):
if self._has_result_processor: process_value = self.process_result_value impl_processor = self.impl.result_processor(dialect, coltype) if impl_processor: def process(value): return process_value(impl_processor(value), dialect) else: def process...
'Suggest a type for a \'coerced\' Python value in an expression. By default, returns self. This method is called by the expression system when an object using this type is on the left or right side of an expression against a plain Python object which does not yet have a SQLAlchemy type assigned:: expr = table.c.somec...
def coerce_compared_value(self, op, value):
return self
'Produce a copy of this :class:`.TypeDecorator` instance. This is a shallow copy and is provided to fulfill part of the :class:`.TypeEngine` contract. It usually does not need to be overridden unless the user-defined :class:`.TypeDecorator` has local state that should be deep-copied.'
def copy(self):
instance = self.__class__.__new__(self.__class__) instance.__dict__.update(self.__dict__) return instance
'Return the DBAPI type object represented by this :class:`.TypeDecorator`. By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the underlying "impl".'
def get_dbapi_type(self, dbapi):
return self.impl.get_dbapi_type(dbapi)
'Given two values, compare them for equality. By default this calls upon :meth:`.TypeEngine.compare_values` of the underlying "impl", which in turn usually uses the Python equals operator ``==``. This function is used by the ORM to compare an original-loaded value with an intercepted "changed" value, to determine if a ...
def compare_values(self, x, y):
return self.impl.compare_values(x, y)
'Construct a new :class:`.Variant`. :param base: the base \'fallback\' type :param mapping: dictionary of string dialect names to :class:`.TypeEngine` instances.'
def __init__(self, base, mapping):
self.impl = base self.mapping = mapping
'Return a new :class:`.Variant` which adds the given type + dialect name to the mapping, in addition to the mapping present in this :class:`.Variant`. :param type_: a :class:`.TypeEngine` that will be selected as a variant from the originating type, when a dialect of the given name is in use. :param dialect_name: base ...
def with_variant(self, type_, dialect_name):
if (dialect_name in self.mapping): raise exc.ArgumentError(("Dialect '%s' is already present in the mapping for this Variant" % dialect_name)) mapping = self.mapping.copy() mapping[dialect_name] = type_ return Variant(self.impl, mapping)
'Set the parameters for the statement. This method raises ``NotImplementedError`` on the base class, and is overridden by :class:`.ValuesBase` to provide the SET/VALUES clause of UPDATE and INSERT.'
def params(self, *arg, **kw):
raise NotImplementedError('params() is not supported for INSERT/UPDATE/DELETE statements. To set the values for an INSERT or UPDATE statement, use stmt.values(**parameters).')
'Return a \'bind\' linked to this :class:`.UpdateBase` or a :class:`.Table` associated with it.'
def bind(self):
return (self._bind or self.table.bind)
'Add a :term:`RETURNING` or equivalent clause to this statement. e.g.:: stmt = table.update().\ where(table.c.data == \'value\').\ values(status=\'X\').\ returning(table.c.server_flag, table.c.updated_timestamp) for server_flag, updated_timestamp in connection.execute(stmt): print(server_flag, updated_timestamp) The gi...
@_generative def returning(self, *cols):
self._returning = cols
'Add a table hint for a single table to this INSERT/UPDATE/DELETE statement. .. note:: :meth:`.UpdateBase.with_hint` currently applies only to Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use :meth:`.UpdateBase.prefix_with`. The text of the hint is rendered in the appropriate location for the database b...
@_generative def with_hint(self, text, selectable=None, dialect_name='*'):
if (selectable is None): selectable = self.table self._hints = self._hints.union({(selectable, dialect_name): text})
'specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE. Note that the :class:`.Insert` and :class:`.Update` constructs support per-execution time formatting of the VALUES and/or SET clauses, based on the arguments passed to :meth:`.Connection.execute`. However, the :meth:`.ValuesBase.v...
@_generative def values(self, *args, **kwargs):
if (self.select is not None): raise exc.InvalidRequestError('This construct already inserts from a SELECT') if (self._has_multi_parameters and kwargs): raise exc.InvalidRequestError('This construct already has multiple parameter sets.') if args: if...
'Make use of a :term:`RETURNING` clause for the purpose of fetching server-side expressions and defaults. E.g.:: stmt = table.insert().values(data=\'newdata\').return_defaults() result = connection.execute(stmt) server_created_at = result.returned_defaults[\'created_at\'] When used against a backend that supports RETUR...
@_generative def return_defaults(self, *cols):
self._return_defaults = (cols or True)
'Construct an :class:`.Insert` object. Similar functionality is available via the :meth:`~.TableClause.insert` method on :class:`~.schema.Table`. :param table: :class:`.TableClause` which is the subject of the insert. :param values: collection of values to be inserted; see :meth:`.Insert.values` for a description of al...
def __init__(self, table, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw):
ValuesBase.__init__(self, table, values, prefixes) self._bind = bind self.select = self.select_names = None self.inline = inline self._returning = returning self._validate_dialect_kwargs(dialect_kw) self._return_defaults = return_defaults
'Return a new :class:`.Insert` construct which represents an ``INSERT...FROM SELECT`` statement. e.g.:: sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5) ins = table2.insert().from_select([\'a\', \'b\'], sel) :param names: a sequence of string column names or :class:`.Column` objects representing the target ...
@_generative def from_select(self, names, select):
if self.parameters: raise exc.InvalidRequestError('This construct already inserts value expressions') (self.parameters, self._has_multi_parameters) = self._process_colparams(dict(((n, Null()) for n in names))) self.select_names = names self.select = _interpret_as_select(select)
'Construct an :class:`.Update` object. E.g.:: from sqlalchemy import update stmt = update(users).where(users.c.id==5).\ values(name=\'user #5\') Similar functionality is available via the :meth:`~.TableClause.update` method on :class:`.Table`:: stmt = users.update().\ where(users.c.id==5).\ values(name=\'user #5\') :pa...
def __init__(self, table, whereclause=None, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw):
ValuesBase.__init__(self, table, values, prefixes) self._bind = bind self._returning = returning if (whereclause is not None): self._whereclause = _literal_as_text(whereclause) else: self._whereclause = None self.inline = inline self._validate_dialect_kwargs(dialect_kw) s...
'return a new update() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.'
@_generative def where(self, whereclause):
if (self._whereclause is not None): self._whereclause = and_(self._whereclause, _literal_as_text(whereclause)) else: self._whereclause = _literal_as_text(whereclause)
'Construct :class:`.Delete` object. Similar functionality is available via the :meth:`~.TableClause.delete` method on :class:`~.schema.Table`. :param table: The table to be updated. :param whereclause: A :class:`.ClauseElement` describing the ``WHERE`` condition of the ``UPDATE`` statement. Note that the :meth:`~Delete...
def __init__(self, table, whereclause=None, bind=None, returning=None, prefixes=None, **dialect_kw):
self._bind = bind self.table = _interpret_as_from(table) self._returning = returning if prefixes: self._setup_prefixes(prefixes) if (whereclause is not None): self._whereclause = _literal_as_text(whereclause) else: self._whereclause = None self._validate_dialect_kwarg...
'Add the given WHERE clause to a newly returned delete construct.'
@_generative def where(self, whereclause):
if (self._whereclause is not None): self._whereclause = and_(self._whereclause, _literal_as_text(whereclause)) else: self._whereclause = _literal_as_text(whereclause)
'traverse the given expression structure, returning an iterator of all elements.'
def iterate(self, obj):
return iterate(obj, self.__traverse_options__)
'traverse and visit the given expression structure.'
def traverse(self, obj):
return traverse(obj, self.__traverse_options__, self._visitor_dict)
'iterate through this visitor and each \'chained\' visitor.'
@property def _visitor_iterator(self):
v = self while v: (yield v) v = getattr(v, '_next', None)
'\'chain\' an additional ClauseVisitor onto this ClauseVisitor. the chained visitor will receive all visit events after this one.'
def chain(self, visitor):
tail = list(self._visitor_iterator)[(-1)] tail._next = visitor return self
'Apply cloned traversal to the given list of elements, and return the new list.'
def copy_and_process(self, list_):
return [self.traverse(x) for x in list_]
'traverse and visit the given expression structure.'
def traverse(self, obj):
return cloned_traverse(obj, self.__traverse_options__, self._visitor_dict)
'receive pre-copied elements during a cloning traversal. If the method returns a new element, the element is used instead of creating a simple copy of the element. Traversal will halt on the newly returned element if it is re-encountered.'
def replace(self, elem):
return None
'traverse and visit the given expression structure.'
def traverse(self, obj):
def replace(elem): for v in self._visitor_iterator: e = v.replace(elem) if (e is not None): return e return replacement_traverse(obj, self.__traverse_options__, replace)
'Return a compiler appropriate for this ClauseElement, given a Dialect.'
def _compiler(self, dialect, **kw):
return dialect.ddl_compiler(dialect, self, **kw)
'Execute this DDL immediately. Executes the DDL statement in isolation using the supplied :class:`.Connectable` or :class:`.Connectable` assigned to the ``.bind`` property, if not supplied. If the DDL has a conditional ``on`` criteria, it will be invoked with None as the event. :param bind: Optional, an ``Engine`` or `...
def execute(self, bind=None, target=None):
if (bind is None): bind = _bind_or_error(self) if self._should_execute(target, bind): return bind.execute(self.against(target)) else: bind.engine.logger.info('DDL execution skipped, criteria not met.')
'Link execution of this DDL to the DDL lifecycle of a SchemaItem. Links this ``DDLElement`` to a ``Table`` or ``MetaData`` instance, executing it when that schema item is created or dropped. The DDL statement will be executed using the same Connection and transactional context as the Table create/drop itself. The ``.bi...
@util.deprecated('0.7', 'See :class:`.DDLEvents`, as well as :meth:`.DDLElement.execute_if`.') def execute_at(self, event_name, target):
def call_event(target, connection, **kw): if self._should_execute_deprecated(event_name, target, connection, **kw): return connection.execute(self.against(target)) event.listen(target, ('' + event_name.replace('-', '_')), call_event)
'Return a copy of this DDL against a specific schema item.'
@_generative def against(self, target):
self.target = target
'Return a callable that will execute this DDLElement conditionally. Used to provide a wrapper for event listening:: event.listen( metadata, \'before_create\', DDL("my_ddl").execute_if(dialect=\'postgresql\') :param dialect: May be a string, tuple or a callable predicate. If a string, it will be compared to the name of...
@_generative def execute_if(self, dialect=None, callable_=None, state=None):
self.dialect = dialect self.callable_ = callable_ self.state = state
'Execute the DDL as a ddl_listener.'
def __call__(self, target, bind, **kw):
if self._should_execute(target, bind, **kw): return bind.execute(self.against(target))
'Create a DDL statement. :param statement: A string or unicode string to be executed. Statements will be processed with Python\'s string formatting operator. See the ``context`` argument and the ``execute_at`` method. A literal \'%\' in a statement must be escaped as \'%%\'. SQL bind parameters are not available in D...
def __init__(self, statement, on=None, context=None, bind=None):
if (not isinstance(statement, util.string_types)): raise exc.ArgumentError(("Expected a string or unicode SQL statement, got '%r'" % statement)) self.statement = statement self.context = (context or {}) self._check_ddl_on(on) self.on = on self._bind = bind
'Allow disable of _create_rule using a callable. Pass to _create_rule using util.portable_instancemethod(self._create_rule_disable) to retain serializability.'
def _create_rule_disable(self, compiler):
return False
'Create a new :class:`.CreateSchema` construct.'
def __init__(self, name, quote=None, **kw):
self.quote = quote super(CreateSchema, self).__init__(name, **kw)
'Create a new :class:`.DropSchema` construct.'
def __init__(self, name, quote=None, cascade=False, **kw):
self.quote = quote self.cascade = cascade super(DropSchema, self).__init__(name, **kw)
'Create a :class:`.CreateTable` construct. :param element: a :class:`.Table` that\'s the subject of the CREATE :param on: See the description for \'on\' in :class:`.DDL`. :param bind: See the description for \'bind\' in :class:`.DDL`.'
def __init__(self, element, on=None, bind=None):
super(CreateTable, self).__init__(element, on=on, bind=bind) self.columns = [CreateColumn(column) for column in element.columns]
'Implement the ``&`` operator. When used with SQL expressions, results in an AND operation, equivalent to :func:`~.expression.and_`, that is:: a & b is equivalent to:: from sqlalchemy import and_ and_(a, b) Care should be taken when using ``&`` regarding operator precedence; the ``&`` operator has the highest precedenc...
def __and__(self, other):
return self.operate(and_, other)
'Implement the ``|`` operator. When used with SQL expressions, results in an OR operation, equivalent to :func:`~.expression.or_`, that is:: a | b is equivalent to:: from sqlalchemy import or_ or_(a, b) Care should be taken when using ``|`` regarding operator precedence; the ``|`` operator has the highest precedence. T...
def __or__(self, other):
return self.operate(or_, other)