desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Produce an OVER clause against this function.
Used against aggregate or so-called "window" functions,
for database backends that support window functions.
The expression::
func.row_number().over(order_by=\'x\')
is shorthand for::
from sqlalchemy import over
over(func.row_number(), order_by=\'x\')
See :func:`~.expressi... | def over(self, partition_by=None, order_by=None):
| return Over(self, partition_by=partition_by, order_by=order_by)
|
'Produce a :func:`~.expression.select` construct
against this :class:`.FunctionElement`.
This is shorthand for::
s = select([function_element])'
| def select(self):
| s = Select([self])
if self._execution_options:
s = s.execution_options(**self._execution_options)
return s
|
'Execute this :class:`.FunctionElement` against an embedded
\'bind\' and return a scalar value.
This first calls :meth:`~.FunctionElement.select` to
produce a SELECT construct.
Note that :class:`.FunctionElement` can be passed to
the :meth:`.Connectable.scalar` method of :class:`.Connection`
or :class:`.Engine`.'
| def scalar(self):
| return self.select().execute().scalar()
|
'Execute this :class:`.FunctionElement` against an embedded
\'bind\'.
This first calls :meth:`~.FunctionElement.select` to
produce a SELECT construct.
Note that :class:`.FunctionElement` can be passed to
the :meth:`.Connectable.execute` method of :class:`.Connection`
or :class:`.Engine`.'
| def execute(self):
| return self.select().execute()
|
'Construct a :class:`.Function`.
The :data:`.func` construct is normally used to construct
new :class:`.Function` instances.'
| def __init__(self, name, *clauses, **kw):
| self.packagenames = (kw.pop('packagenames', None) or [])
self.name = name
self._bind = kw.get('bind', None)
self.type = sqltypes.to_instance(kw.get('type_', None))
FunctionElement.__init__(self, *clauses, **kw)
|
'Initialize the list of child items for this SchemaItem.'
| def _init_items(self, *args):
| for item in args:
if (item is not None):
item._set_parent_with_dispatch(self)
|
'used to allow SchemaVisitor access'
| def get_children(self, **kwargs):
| return []
|
'Return the value of the ``quote`` flag passed
to this schema object, for those schema items which
have a ``name`` field.'
| @property
@util.deprecated('0.9', 'Use ``<obj>.name.quote``')
def quote(self):
| return self.name.quote
|
'Info dictionary associated with the object, allowing user-defined
data to be associated with this :class:`.SchemaItem`.
The dictionary is automatically generated when first accessed.
It can also be specified in the constructor of some objects,
such as :class:`.Table` and :class:`.Column`.'
| @util.memoized_property
def info(self):
| return {}
|
'Return the value of the ``quote_schema`` flag passed
to this :class:`.Table`.'
| @property
@util.deprecated('0.9', 'Use ``table.schema.quote``')
def quote_schema(self):
| return self.schema.quote
|
'Return the set of constraints as a list, sorted by creation
order.'
| @property
def _sorted_constraints(self):
| return sorted(self.constraints, key=(lambda c: c._creation_order))
|
'Return the \'key\' for this :class:`.Table`.
This value is used as the dictionary key within the
:attr:`.MetaData.tables` collection. It is typically the same
as that of :attr:`.Table.name` for a table with no :attr:`.Table.schema`
set; otherwise it is typically of the form ``schemaname.tablename``.'
| @property
def key(self):
| return _get_table_key(self.name, self.schema)
|
'Return the connectable associated with this Table.'
| @property
def bind(self):
| return ((self.metadata and self.metadata.bind) or None)
|
'Add a \'dependency\' for this Table.
This is another Table object which must be created
first before this one can, or dropped after this one.
Usually, dependencies between tables are determined via
ForeignKey objects. However, for other situations that
create dependencies outside of foreign keys (rules, inheriting),... | def add_is_dependent_on(self, table):
| self._extra_dependencies.add(table)
|
'Append a :class:`~.schema.Column` to this :class:`~.schema.Table`.
The "key" of the newly added :class:`~.schema.Column`, i.e. the
value of its ``.key`` attribute, will then be available
in the ``.c`` collection of this :class:`~.schema.Table`, and the
column definition will be included in any CREATE TABLE, SELECT,
UP... | def append_column(self, column):
| column._set_parent_with_dispatch(self)
|
'Append a :class:`~.schema.Constraint` to this
:class:`~.schema.Table`.
This has the effect of the constraint being included in any
future CREATE TABLE statement, assuming specific DDL creation
events have not been associated with the given
:class:`~.schema.Constraint` object.
Note that this does **not** produce the co... | def append_constraint(self, constraint):
| constraint._set_parent_with_dispatch(self)
|
'Append a DDL event listener to this ``Table``.
.. deprecated:: 0.7
See :class:`.DDLEvents`.'
| def append_ddl_listener(self, event_name, listener):
| def adapt_listener(target, connection, **kw):
listener(event_name, target, connection)
event.listen(self, ('' + event_name.replace('-', '_')), adapt_listener)
|
'Return True if this table exists.'
| def exists(self, bind=None):
| if (bind is None):
bind = _bind_or_error(self)
return bind.run_callable(bind.dialect.has_table, self.name, schema=self.schema)
|
'Issue a ``CREATE`` statement for this
:class:`.Table`, using the given :class:`.Connectable`
for connectivity.
.. seealso::
:meth:`.MetaData.create_all`.'
| def create(self, bind=None, checkfirst=False):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
|
'Issue a ``DROP`` statement for this
:class:`.Table`, using the given :class:`.Connectable`
for connectivity.
.. seealso::
:meth:`.MetaData.drop_all`.'
| def drop(self, bind=None, checkfirst=False):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
|
'Return a copy of this :class:`.Table` associated with a different
:class:`.MetaData`.
E.g.::
m1 = MetaData()
user = Table(\'user\', m1, Column(\'id\', Integer, priamry_key=True))
m2 = MetaData()
user_copy = user.tometadata(m2)
:param metadata: Target :class:`.MetaData` object, into which the
new :class:`.Table` object... | def tometadata(self, metadata, schema=RETAIN_SCHEMA, referred_schema_fn=None):
| if (schema is RETAIN_SCHEMA):
schema = self.schema
elif (schema is None):
schema = metadata.schema
key = _get_table_key(self.name, schema)
if (key in metadata.tables):
util.warn(("Table '%s' already exists within the given MetaData - not copying." % ... |
'Construct a new ``Column`` object.
:param name: The name of this column as represented in the database.
This argument may be the first positional argument, or specified
via keyword.
Names which contain no upper case characters
will be treated as case insensitive names, and will not be quoted
unless they are a reserved... | def __init__(self, *args, **kwargs):
| name = kwargs.pop('name', None)
type_ = kwargs.pop('type_', None)
args = list(args)
if args:
if isinstance(args[0], util.string_types):
if (name is not None):
raise exc.ArgumentError('May not pass name positionally and as a keyword.')
... |
'Return True if this Column references the given column via foreign
key.'
| def references(self, column):
| for fk in self.foreign_keys:
if fk.column.proxy_set.intersection(column.proxy_set):
return True
else:
return False
|
'Create a copy of this ``Column``, unitialized.
This is used in ``Table.tometadata``.'
| def copy(self, **kw):
| args = ([c.copy(**kw) for c in self.constraints] + [c.copy(**kw) for c in self.foreign_keys if (not c.constraint)])
type_ = self.type
if isinstance(type_, SchemaEventTarget):
type_ = type_.copy(**kw)
c = self._constructor(name=self.name, type_=type_, key=self.key, primary_key=self.primary_key, n... |
'Create a *proxy* for this column.
This is a copy of this ``Column`` referenced by a different parent
(such as an alias or select statement). The column should
be used only in select scenarios, as its full DDL/default
information is not transferred.'
| def _make_proxy(self, selectable, name=None, key=None, name_is_truncatable=False, **kw):
| fk = [ForeignKey(f.column, _constraint=f.constraint) for f in self.foreign_keys]
if ((name is None) and (self.name is None)):
raise exc.InvalidRequestError("Cannot initialize a sub-selectable with this Column object until it's 'name' has been assigned.")
try:
... |
'Construct a column-level FOREIGN KEY.
The :class:`.ForeignKey` object when constructed generates a
:class:`.ForeignKeyConstraint` which is associated with the parent
:class:`.Table` object\'s collection of constraints.
:param column: A single target column for the key relationship. A
:class:`.Column` object or a colum... | def __init__(self, column, _constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, link_to_name=False, match=None, **dialect_kw):
| self._colspec = column
if isinstance(self._colspec, util.string_types):
self._table_column = None
else:
if hasattr(self._colspec, '__clause_element__'):
self._table_column = self._colspec.__clause_element__()
else:
self._table_column = self._colspec
if... |
'Produce a copy of this :class:`.ForeignKey` object.
The new :class:`.ForeignKey` will not be bound
to any :class:`.Column`.
This method is usually used by the internal
copy procedures of :class:`.Column`, :class:`.Table`,
and :class:`.MetaData`.
:param schema: The returned :class:`.ForeignKey` will
reference the origi... | def copy(self, schema=None):
| fk = ForeignKey(self._get_colspec(schema=schema), use_alter=self.use_alter, name=self.name, onupdate=self.onupdate, ondelete=self.ondelete, deferrable=self.deferrable, initially=self.initially, link_to_name=self.link_to_name, match=self.match, **self._unvalidated_dialect_kw)
return self._schema_item_copy(fk)
|
'Return a string based \'column specification\' for this
:class:`.ForeignKey`.
This is usually the equivalent of the string-based "tablename.colname"
argument first passed to the object\'s constructor.'
| def _get_colspec(self, schema=None):
| if schema:
(_schema, tname, colname) = self._column_tokens
return ('%s.%s.%s' % (schema, tname, colname))
elif (self._table_column is not None):
return ('%s.%s' % (self._table_column.table.fullname, self._table_column.key))
else:
return self._colspec
|
'Return True if the given :class:`.Table` is referenced by this
:class:`.ForeignKey`.'
| def references(self, table):
| return (table.corresponding_column(self.column) is not None)
|
'Return the :class:`.Column` in the given :class:`.Table`
referenced by this :class:`.ForeignKey`.
Returns None if this :class:`.ForeignKey` does not reference the given
:class:`.Table`.'
| def get_referent(self, table):
| return table.corresponding_column(self.column)
|
'parse a string-based _colspec into its component parts.'
| @util.memoized_property
def _column_tokens(self):
| m = self._get_colspec().split('.')
if (m is None):
raise exc.ArgumentError(('Invalid foreign key column specification: %s' % self._colspec))
if (len(m) == 1):
tname = m.pop()
colname = None
else:
colname = m.pop()
tname = m.pop()
if (len(m) > 0)... |
'Return the target :class:`.Column` referenced by this
:class:`.ForeignKey`.
If no target column has been established, an exception
is raised.
.. versionchanged:: 0.9.0
Foreign key target column resolution now occurs as soon as both
the ForeignKey object and the remote Column to which it refers
are both associated with... | @util.memoized_property
def column(self):
| if isinstance(self._colspec, util.string_types):
(parenttable, tablekey, colname) = self._resolve_col_tokens()
if (tablekey not in parenttable.metadata):
raise exc.NoReferencedTableError(("Foreign key associated with column '%s' could not find table '%s' ... |
'Return the connectable associated with this default.'
| @property
def bind(self):
| if (getattr(self, 'column', None) is not None):
return self.column.table.bind
else:
return None
|
'"Construct a new :class:`.ColumnDefault`.
:param arg: argument representing the default value.
May be one of the following:
* a plain non-callable Python value, such as a
string, integer, boolean, or other simple type.
The default value will be used as is each time.
* a SQL expression, that is one which derives from
:... | def __init__(self, arg, **kwargs):
| super(ColumnDefault, self).__init__(**kwargs)
if isinstance(arg, FetchedValue):
raise exc.ArgumentError('ColumnDefault may not be a server-side default type.')
if util.callable(arg):
arg = self._maybe_wrap_callable(arg)
self.arg = arg
|
'Wrap callables that don\'t accept a context.
This is to allow easy compatiblity with default callables
that aren\'t specific to accepting of a context.'
| def _maybe_wrap_callable(self, fn):
| try:
argspec = util.get_callable_argspec(fn, no_self=True)
except TypeError:
return (lambda ctx: fn())
defaulted = (((argspec[3] is not None) and len(argspec[3])) or 0)
positionals = (len(argspec[0]) - defaulted)
if (positionals == 0):
return (lambda ctx: fn())
elif (posi... |
'Construct a :class:`.Sequence` object.
:param name: The name of the sequence.
:param start: the starting index of the sequence. This value is
used when the CREATE SEQUENCE command is emitted to the database
as the value of the "START WITH" clause. If ``None``, the
clause is omitted, which on most platforms indicate... | def __init__(self, name, start=None, increment=None, schema=None, optional=False, quote=None, metadata=None, quote_schema=None, for_update=False):
| super(Sequence, self).__init__(for_update=for_update)
self.name = quoted_name(name, quote)
self.start = start
self.increment = increment
self.optional = optional
if ((metadata is not None) and (schema is None) and metadata.schema):
self.schema = schema = metadata.schema
else:
... |
'Return a :class:`.next_value` function element
which will render the appropriate increment function
for this :class:`.Sequence` within any SQL expression.'
| @util.dependencies('sqlalchemy.sql.functions.func')
def next_value(self, func):
| return func.next_value(self, bind=self.bind)
|
'Creates this sequence in the database.'
| def create(self, bind=None, checkfirst=True):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
|
'Drops this sequence from the database.'
| def drop(self, bind=None, checkfirst=True):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
|
'Create a SQL constraint.
:param name:
Optional, the in-database name of this ``Constraint``.
:param deferrable:
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
issuing DDL for this constraint.
:param initially:
Optional string. If set, emit INITIALLY <value> when issuing DDL
for this constraint.
:param... | def __init__(self, name=None, deferrable=None, initially=None, _create_rule=None, **dialect_kw):
| self.name = name
self.deferrable = deferrable
self.initially = initially
self._create_rule = _create_rule
util.set_creation_order(self)
self._validate_dialect_kwargs(dialect_kw)
|
':param \*columns:
A sequence of column names or Column objects.
:param name:
Optional, the in-database name of this constraint.
:param deferrable:
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
issuing DDL for this constraint.
:param initially:
Optional string. If set, emit INITIALLY <value> when issu... | def __init__(self, *columns, **kw):
| Constraint.__init__(self, **kw)
ColumnCollectionMixin.__init__(self, *columns)
|
'Construct a CHECK constraint.
:param sqltext:
A string containing the constraint definition, which will be used
verbatim, or a SQL expression construct. If given as a string,
the object is converted to a :class:`.Text` object. If the textual
string includes a colon character, escape this using a backslash::
CheckC... | def __init__(self, sqltext, name=None, deferrable=None, initially=None, table=None, _create_rule=None, _autoattach=True):
| super(CheckConstraint, self).__init__(name, deferrable, initially, _create_rule)
self.sqltext = _literal_as_text(sqltext)
if (table is not None):
self._set_parent_with_dispatch(table)
elif _autoattach:
cols = _find_columns(self.sqltext)
tables = set([c.table for c in cols if isin... |
'Construct a composite-capable FOREIGN KEY.
:param columns: A sequence of local column names. The named columns
must be defined and present in the parent Table. The names should
match the ``key`` given to each column (defaults to the name) unless
``link_to_name`` is True.
:param refcolumns: A sequence of foreign column... | def __init__(self, columns, refcolumns, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, use_alter=False, link_to_name=False, match=None, table=None, **dialect_kw):
| super(ForeignKeyConstraint, self).__init__(name, deferrable, initially, **dialect_kw)
self.onupdate = onupdate
self.ondelete = ondelete
self.link_to_name = link_to_name
if ((self.name is None) and use_alter):
raise exc.ArgumentError('Alterable Constraint requires a name')
sel... |
'repopulate this :class:`.PrimaryKeyConstraint` given
a set of columns.
Existing columns in the table that are marked as primary_key=True
are maintained.
Also fires a new event.
This is basically like putting a whole new
:class:`.PrimaryKeyConstraint` object on the parent
:class:`.Table` object without actually replaci... | def _reload(self, columns):
| for col in columns:
col.primary_key = True
self.columns.extend(columns)
self._set_parent_with_dispatch(self.table)
|
'Construct an index object.
:param name:
The name of the index
:param \*expressions:
Column expressions to include in the index. The expressions
are normally instances of :class:`.Column`, but may also
be arbitrary SQL expressions which ultmately refer to a
:class:`.Column`.
:param unique=False:
Keyword only argument... | def __init__(self, name, *expressions, **kw):
| self.table = None
columns = []
for expr in expressions:
if (not isinstance(expr, ClauseElement)):
columns.append(expr)
else:
cols = []
visitors.traverse(expr, {}, {'column': cols.append})
if cols:
columns.append(cols[0])
... |
'Return the connectable associated with this Index.'
| @property
def bind(self):
| return self.table.bind
|
'Issue a ``CREATE`` statement for this
:class:`.Index`, using the given :class:`.Connectable`
for connectivity.
.. seealso::
:meth:`.MetaData.create_all`.'
| def create(self, bind=None):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaGenerator, self)
return self
|
'Issue a ``DROP`` statement for this
:class:`.Index`, using the given :class:`.Connectable`
for connectivity.
.. seealso::
:meth:`.MetaData.drop_all`.'
| def drop(self, bind=None):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaDropper, self)
|
'Create a new MetaData object.
:param bind:
An Engine or Connection to bind to. May also be a string or URL
instance, these are passed to create_engine() and this MetaData will
be bound to the resulting engine.
:param reflect:
Optional, automatically load all tables from the bound database.
Defaults to False. ``bind``... | def __init__(self, bind=None, reflect=False, schema=None, quote_schema=None, naming_convention=DEFAULT_NAMING_CONVENTION):
| self.tables = util.immutabledict()
self.schema = quoted_name(schema, quote_schema)
self.naming_convention = naming_convention
self._schemas = set()
self._sequences = {}
self._fk_memos = collections.defaultdict(list)
self.bind = bind
if reflect:
util.warn_deprecated('reflect=True ... |
'True if this MetaData is bound to an Engine or Connection.'
| def is_bound(self):
| return (self._bind is not None)
|
'An :class:`.Engine` or :class:`.Connection` to which this
:class:`.MetaData` is bound.
Typically, a :class:`.Engine` is assigned to this attribute
so that "implicit execution" may be used, or alternatively
as a means of providing engine binding information to an
ORM :class:`.Session` object::
engine = create_engine("s... | def bind(self):
| return self._bind
|
'Bind this MetaData to an Engine, Connection, string or URL.'
| @util.dependencies('sqlalchemy.engine.url')
def _bind_to(self, url, bind):
| if isinstance(bind, (util.string_types + (url.URL,))):
self._bind = sqlalchemy.create_engine(bind)
else:
self._bind = bind
|
'Clear all Table objects from this MetaData.'
| def clear(self):
| dict.clear(self.tables)
self._schemas.clear()
self._fk_memos.clear()
|
'Remove the given Table object from this MetaData.'
| def remove(self, table):
| self._remove_table(table.name, table.schema)
|
'Returns a list of :class:`.Table` objects sorted in order of
foreign key dependency.
The sorting will place :class:`.Table` objects that have dependencies
first, before the dependencies themselves, representing the
order in which they can be created. To get the order in which
the tables would be dropped, use the ``r... | @property
def sorted_tables(self):
| return ddl.sort_tables(self.tables.values())
|
'Load all available table definitions from the database.
Automatically creates ``Table`` entries in this ``MetaData`` for any
table available in the database but not yet present in the
``MetaData``. May be called multiple times to pick up tables recently
added to the database, however no special action is taken if a t... | def reflect(self, bind=None, schema=None, views=False, only=None, extend_existing=False, autoload_replace=True, **dialect_kwargs):
| if (bind is None):
bind = _bind_or_error(self)
with bind.connect() as conn:
reflect_opts = {'autoload': True, 'autoload_with': conn, 'extend_existing': extend_existing, 'autoload_replace': autoload_replace}
reflect_opts.update(dialect_kwargs)
if (schema is None):
sche... |
'Append a DDL event listener to this ``MetaData``.
.. deprecated:: 0.7
See :class:`.DDLEvents`.'
| def append_ddl_listener(self, event_name, listener):
| def adapt_listener(target, connection, **kw):
tables = kw['tables']
listener(event, target, connection, tables=tables)
event.listen(self, ('' + event_name.replace('-', '_')), adapt_listener)
|
'Create all tables stored in this metadata.
Conditional by default, will not attempt to recreate tables already
present in the target database.
:param bind:
A :class:`.Connectable` used to access the
database; if None, uses the existing bind on this ``MetaData``, if
any.
:param tables:
Optional list of ``Table`` object... | def create_all(self, bind=None, tables=None, checkfirst=True):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables)
|
'Drop all tables stored in this metadata.
Conditional by default, will not attempt to drop tables not present in
the target database.
:param bind:
A :class:`.Connectable` used to access the
database; if None, uses the existing bind on this ``MetaData``, if
any.
:param tables:
Optional list of ``Table`` objects, which i... | def drop_all(self, bind=None, tables=None, checkfirst=True):
| if (bind is None):
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst, tables=tables)
|
'Construct a ThreadLocalMetaData.'
| def __init__(self):
| self.context = util.threading.local()
self.__engines = {}
super(ThreadLocalMetaData, self).__init__()
|
'The bound Engine or Connection for this thread.
This property may be assigned an Engine or Connection, or assigned a
string or URL to automatically create a basic Engine for this bind
with ``create_engine()``.'
| def bind(self):
| return getattr(self.context, '_engine', None)
|
'Bind to a Connectable in the caller\'s thread.'
| @util.dependencies('sqlalchemy.engine.url')
def _bind_to(self, url, bind):
| if isinstance(bind, (util.string_types + (url.URL,))):
try:
self.context._engine = self.__engines[bind]
except KeyError:
e = sqlalchemy.create_engine(bind)
self.__engines[bind] = e
self.context._engine = e
else:
if (bind not in self.__engin... |
'True if there is a bind for this thread.'
| def is_bound(self):
| return (hasattr(self.context, '_engine') and (self.context._engine is not None))
|
'Dispose all bound engines, in all thread contexts.'
| def dispose(self):
| for e in self.__engines.values():
if hasattr(e, 'dispose'):
e.dispose()
|
'Construct a new ``Compiled`` object.
:param dialect: ``Dialect`` to compile against.
:param statement: ``ClauseElement`` to be compiled.
:param bind: Optional Engine or Connection to compile this
statement against.
:param compile_kwargs: additional kwargs that will be
passed to the initial call to :meth:`.Compiled.pro... | def __init__(self, dialect, statement, bind=None, compile_kwargs=util.immutabledict()):
| self.dialect = dialect
self.bind = bind
if (statement is not None):
self.statement = statement
self.can_execute = statement.supports_execution
self.string = self.process(self.statement, **compile_kwargs)
|
'Produce the internal string representation of this element.'
| @util.deprecated('0.7', ':class:`.Compiled` objects now compile within the constructor.')
def compile(self):
| pass
|
'Return a Compiled that is capable of processing SQL expressions.
If this compiler is one, it would likely just return \'self\'.'
| @property
def sql_compiler(self):
| raise NotImplementedError()
|
'Return the string text of the generated SQL or DDL.'
| def __str__(self):
| return (self.string or '')
|
'Return the bind params for this compiled object.
:param params: a dict of string/object pairs whose values will
override bind values compiled in to the
statement.'
| def construct_params(self, params=None):
| raise NotImplementedError()
|
'Return the bind params for this compiled object.'
| @property
def params(self):
| return self.construct_params()
|
'Execute this compiled object.'
| def execute(self, *multiparams, **params):
| e = self.bind
if (e is None):
raise exc.UnboundExecutionError('This Compiled object is not bound to any Engine or Connection.')
return e._execute_compiled(self, multiparams, params)
|
'Execute this compiled object and return the result\'s
scalar value.'
| def scalar(self, *multiparams, **params):
| return self.execute(*multiparams, **params).scalar()
|
'Construct a new ``DefaultCompiler`` object.
dialect
Dialect to be used
statement
ClauseElement to be compiled
column_keys
a list of column names to be compiled into an INSERT or UPDATE
statement.'
| def __init__(self, dialect, statement, column_keys=None, inline=False, **kwargs):
| self.column_keys = column_keys
self.inline = (inline or getattr(statement, 'inline', False))
self.binds = {}
self.bind_names = util.column_dict()
self.stack = []
self.result_map = {}
self.positional = dialect.positional
if self.positional:
self.positiontup = []
self.bindtempl... |
'Initialize collections related to CTEs only if
a CTE is located, to save on the overhead of
these collections otherwise.'
| @util.memoized_instancemethod
def _init_cte_state(self):
| self.ctes = util.OrderedDict()
self.ctes_by_name = {}
self.ctes_recursive = False
if self.positional:
self.cte_positional = []
|
'return a dictionary of bind parameter keys and values'
| def construct_params(self, params=None, _group_number=None, _check=True):
| if params:
pd = {}
for (bindparam, name) in self.bind_names.items():
if (bindparam.key in params):
pd[name] = params[bindparam.key]
elif (name in params):
pd[name] = params[name]
elif (_check and bindparam.required):
... |
'Return the bind param dictionary embedded into this
compiled object, for those values that are present.'
| @property
def params(self):
| return self.construct_params(_check=False)
|
'Called when a SELECT statement has no froms, and no FROM clause is
to be appended.
Gives Oracle a chance to tack on a ``FROM DUAL`` to the string output.'
| def default_from(self):
| return ''
|
'provide escaping for the literal_column() construct.'
| def escape_literal_column(self, text):
| return text.replace('%', '%%')
|
'Render the value of a bind parameter as a quoted literal.
This is used for statement sections that do not accept bind parameters
on the target driver/database.
This should be implemented by subclasses using the quoting services
of the DBAPI.'
| def render_literal_value(self, value, type_):
| processor = type_._cached_literal_processor(self.dialect)
if processor:
return processor(value)
else:
raise NotImplementedError(("Don't know how to literal-quote value %r" % value))
|
'produce labeled columns present in a select().'
| def _label_select_column(self, select, column, populate_result_map, asfrom, column_clause_args, name=None, within_columns_clause=True):
| if (column.type._has_column_expression and populate_result_map):
col_expr = column.type.column_expression(column)
add_to_result_map = (lambda keyname, name, objects, type_: self._add_to_result_map(keyname, name, (objects + (column,)), type_))
else:
col_expr = column
if populate_r... |
'Rewrite any "a JOIN (b JOIN c)" expression as
"a JOIN (select * from b JOIN c) AS anon", to support
databases that can\'t parse a parenthesized join correctly
(i.e. sqlite the main one).'
| def _transform_select_for_nested_joins(self, select):
| cloned = {}
column_translate = [{}]
def visit(element, **kw):
if (element in column_translate[(-1)]):
return column_translate[(-1)][element]
elif (element in cloned):
return cloned[element]
newelem = cloned[element] = element._clone()
if (newelem.is_se... |
'Called when building a ``SELECT`` statement, position is just
before column list.'
| def get_select_precolumns(self, select):
| return ((select._distinct and 'DISTINCT ') or '')
|
'Provide a hook for MySQL to add LIMIT to the UPDATE'
| def update_limit_clause(self, update_stmt):
| return None
|
'Provide a hook to override the initial table clause
in an UPDATE statement.
MySQL overrides this.'
| def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw):
| return from_table._compiler_dispatch(self, asfrom=True, iscrud=True, **kw)
|
'Provide a hook to override the generation of an
UPDATE..FROM clause.
MySQL and MSSQL override this.'
| def update_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw):
| return ('FROM ' + ', '.join((t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw) for t in extra_froms)))
|
'create a set of tuples representing column/string pairs for use
in an INSERT or UPDATE statement.
Also generates the Compiled object\'s postfetch, prefetch, and
returning column collections, used for default handling and ultimately
populating the ResultProxy\'s prefetch_cols() and postfetch_cols()
collections.'
| def _get_colparams(self, stmt, **kw):
| self.postfetch = []
self.prefetch = []
self.returning = []
if ((self.column_keys is None) and (stmt.parameters is None)):
return [(c, self._create_crud_bind_param(c, None, required=True)) for c in stmt.table.columns]
if stmt._has_multi_parameters:
stmt_parameters = stmt.parameters[0]... |
'Format the remote table clause of a CREATE CONSTRAINT clause.'
| def define_constraint_remote_table(self, constraint, table, preparer):
| return preparer.format_table(table)
|
'Construct a new ``IdentifierPreparer`` object.
initial_quote
Character that begins a delimited identifier.
final_quote
Character that ends a delimited identifier. Defaults to
`initial_quote`.
omit_schema
Prevent prepending schema name. Useful for databases that do
not support schemae.'
| def __init__(self, dialect, initial_quote='"', final_quote=None, escape_quote='"', omit_schema=False):
| self.dialect = dialect
self.initial_quote = initial_quote
self.final_quote = (final_quote or self.initial_quote)
self.escape_quote = escape_quote
self.escape_to_quote = (self.escape_quote * 2)
self.omit_schema = omit_schema
self._strings = {}
|
'Escape an identifier.
Subclasses should override this to provide database-dependent
escaping behavior.'
| def _escape_identifier(self, value):
| return value.replace(self.escape_quote, self.escape_to_quote)
|
'Canonicalize an escaped identifier.
Subclasses should override this to provide database-dependent
unescaping behavior that reverses _escape_identifier.'
| def _unescape_identifier(self, value):
| return value.replace(self.escape_to_quote, self.escape_quote)
|
'Quote an identifier.
Subclasses should override this to provide database-dependent
quoting behavior.'
| def quote_identifier(self, value):
| return ((self.initial_quote + self._escape_identifier(value)) + self.final_quote)
|
'Return True if the given identifier requires quoting.'
| def _requires_quotes(self, value):
| lc_value = value.lower()
return ((lc_value in self.reserved_words) or (value[0] in self.illegal_initial_characters) or (not self.legal_characters.match(util.text_type(value))) or (lc_value != value))
|
'Conditionally quote a schema.
Subclasses can override this to provide database-dependent
quoting behavior for schema names.
the \'force\' flag should be considered deprecated.'
| def quote_schema(self, schema, force=None):
| return self.quote(schema, force)
|
'Conditionally quote an identifier.
the \'force\' flag should be considered deprecated.'
| def quote(self, ident, force=None):
| force = getattr(ident, 'quote', None)
if (force is None):
if (ident in self._strings):
return self._strings[ident]
else:
if self._requires_quotes(ident):
self._strings[ident] = self.quote_identifier(ident)
else:
self._strings[id... |
'Prepare a quoted table and schema name.'
| def format_table(self, table, use_schema=True, name=None):
| if (name is None):
name = table.name
result = self.quote(name)
if ((not self.omit_schema) and use_schema and getattr(table, 'schema', None)):
result = ((self.quote_schema(table.schema) + '.') + result)
return result
|
'Prepare a quoted schema name.'
| def format_schema(self, name, quote=None):
| return self.quote(name, quote)
|
'Prepare a quoted column name.'
| def format_column(self, column, use_table=False, name=None, table_name=None):
| if (name is None):
name = column.name
if (not getattr(column, 'is_literal', False)):
if use_table:
return ((self.format_table(column.table, use_schema=False, name=table_name) + '.') + self.quote(name))
else:
return self.quote(name)
elif use_table:
retu... |
'Format table name and schema as a tuple.'
| def format_table_seq(self, table, use_schema=True):
| if ((not self.omit_schema) and use_schema and getattr(table, 'schema', None)):
return (self.quote_schema(table.schema), self.format_table(table, use_schema=False))
else:
return (self.format_table(table, use_schema=False),)
|
'Unpack \'schema.table.column\'-like strings into components.'
| def unformat_identifiers(self, identifiers):
| r = self._r_identifiers
return [self._unescape_identifier(i) for i in [(a or b) for (a, b) in r.findall(identifiers)]]
|
'Create a \'join\' of this :class:`._Dispatch` and another.
This new dispatcher will dispatch events to both
:class:`._Dispatch` objects.'
| def _join(self, other):
| if ('_joined_dispatch_cls' not in self.__class__.__dict__):
cls = type(('Joined%s' % self.__class__.__name__), (_JoinedDispatcher, self.__class__), {})
for ls in _event_descriptors(self):
setattr(cls, ls.name, _JoinedDispatchDescriptor(ls.name))
self.__class__._joined_dispatch_cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.