desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Dictionary of parent object->attribute name on the parent.
This attribute is a so-called "memoized" property. It initializes
itself with a new ``weakref.WeakKeyDictionary`` the first time
it is accessed, returning the same object upon subsequent access.'
| @memoized_property
def _parents(self):
| return weakref.WeakKeyDictionary()
|
'Given a value, coerce it into the target type.
Can be overridden by custom subclasses to coerce incoming
data into a particular type.
By default, raises ``ValueError``.
This method is called in different scenarios depending on if
the parent class is of type :class:`.Mutable` or of type
:class:`.MutableComposite`. In ... | @classmethod
def coerce(cls, key, value):
| if (value is None):
return None
msg = "Attribute '%s' does not accept objects of type %s"
raise ValueError((msg % (key, type(value))))
|
'Establish this type as a mutation listener for the given
mapped descriptor.'
| @classmethod
def _listen_on_attribute(cls, attribute, coerce, parent_cls):
| key = attribute.key
if (parent_cls is not attribute.class_):
return
parent_cls = attribute.class_
def load(state, *args):
"Listen for objects loaded or refreshed.\n\n Wrap the target data member's value with\... |
'Subclasses should call this method whenever change events occur.'
| def changed(self):
| for (parent, key) in self._parents.items():
flag_modified(parent, key)
|
'Establish this type as a mutation listener for the given
mapped descriptor.'
| @classmethod
def associate_with_attribute(cls, attribute):
| cls._listen_on_attribute(attribute, True, attribute.class_)
|
'Associate this wrapper with all future mapped columns
of the given type.
This is a convenience method that calls
``associate_with_attribute`` automatically.
.. warning::
The listeners established by this method are *global*
to all mappers, and are *not* garbage collected. Only use
:meth:`.associate_with` for types t... | @classmethod
def associate_with(cls, sqltype):
| def listen_for_type(mapper, class_):
for prop in mapper.column_attrs:
if isinstance(prop.columns[0].type, sqltype):
cls.associate_with_attribute(getattr(class_, prop.key))
event.listen(mapper, 'mapper_configured', listen_for_type)
|
'Associate a SQL type with this mutable Python type.
This establishes listeners that will detect ORM mappings against
the given type, adding mutation event trackers to those mappings.
The type is returned, unconditionally as an instance, so that
:meth:`.as_mutable` can be used inline::
Table(\'mytable\', metadata,
Colu... | @classmethod
def as_mutable(cls, sqltype):
| sqltype = types.to_instance(sqltype)
def listen_for_type(mapper, class_):
for prop in mapper.column_attrs:
if (prop.columns[0].type is sqltype):
cls.associate_with_attribute(getattr(class_, prop.key))
event.listen(mapper, 'mapper_configured', listen_for_type)
return s... |
'Subclasses should call this method whenever change events occur.'
| def changed(self):
| for (parent, key) in self._parents.items():
prop = object_mapper(parent).get_property(key)
for (value, attr_name) in zip(self.__composite_values__(), prop._attribute_keys):
setattr(parent, attr_name, value)
|
'Detect dictionary set events and emit change events.'
| def __setitem__(self, key, value):
| dict.__setitem__(self, key, value)
self.changed()
|
'Detect dictionary del events and emit change events.'
| def __delitem__(self, key):
| dict.__delitem__(self, key)
self.changed()
|
'Convert plain dictionary to MutableDict.'
| @classmethod
def coerce(cls, key, value):
| if (not isinstance(value, MutableDict)):
if isinstance(value, dict):
return MutableDict(value)
return Mutable.coerce(key, value)
else:
return value
|
'Extract mapped classes and relationships from the :class:`.MetaData` and
perform mappings.
:param engine: an :class:`.Engine` or :class:`.Connection` with which
to perform schema reflection, if specified.
If the :paramref:`.AutomapBase.prepare.reflect` argument is False, this
object is not used.
:param reflect: if Tru... | @classmethod
def prepare(cls, engine=None, reflect=False, classname_for_table=classname_for_table, collection_class=list, name_for_scalar_relationship=name_for_scalar_relationship, name_for_collection_relationship=name_for_collection_relationship, generate_relationship=generate_relationship):
| if reflect:
cls.metadata.reflect(engine, extend_existing=True, autoload_replace=False)
table_to_map_config = dict(((m.local_table, m) for m in _DeferredMapperConfig.classes_for_base(cls, sort=False)))
many_to_many = []
for table in cls.metadata.tables.values():
(lcl_m2m, rem_m2m, m2m_con... |
'Return a collection of factories in play or specified for a
hierarchy.
Traverses the entire inheritance graph of a cls and returns a
collection of instrumentation factories for those classes. Factories
are extracted from active ClassManagers, if available, otherwise
instrumentation_finders is consulted.'
| def _collect_management_factories_for(self, cls):
| hierarchy = util.class_hierarchy(cls)
factories = set()
for member in hierarchy:
manager = self.manager_of_class(member)
if (manager is not None):
factories.add(manager.factory)
else:
for finder in instrumentation_finders:
factory = finder(memb... |
'Install a default InstanceState if none is present.
A private convenience method used by the __init__ decorator.'
| def _new_state_if_none(self, instance):
| if self.has_state(instance):
return False
else:
return self.setup_instance(instance)
|
'Construct a Pool.
:param creator: a callable function that returns a DB-API
connection object. The function will be called with
parameters.
:param recycle: If set to non -1, number of seconds between
connection recycling, which means upon checkout, if this
timeout is surpassed the connection will be closed and
replac... | def __init__(self, creator, recycle=(-1), echo=None, use_threadlocal=False, logging_name=None, reset_on_return=True, listeners=None, events=None, _dispatch=None, _dialect=None):
| if logging_name:
self.logging_name = self._orig_logging_name = logging_name
else:
self._orig_logging_name = None
log.instance_logger(self, echoflag=echo)
self._threadconns = threading.local()
self._creator = creator
self._recycle = recycle
self._invalidate_time = 0
self._... |
'Add a :class:`.PoolListener`-like object to this pool.
``listener`` may be an object that implements some or all of
PoolListener, or a dictionary of callables containing implementations
of some or all of the named methods in PoolListener.'
| @util.deprecated(2.7, 'Pool.add_listener is deprecated. Use event.listen()')
def add_listener(self, listener):
| interfaces.PoolListener._adapt_listener(self, listener)
|
'Produce a DBAPI connection that is not referenced by any
thread-local context.
This method is equivalent to :meth:`.Pool.connect` when the
:paramref:`.Pool.use_threadlocal` flag is not set to True.
When :paramref:`.Pool.use_threadlocal` is True, the :meth:`.Pool.unique_connection`
method provides a means of bypassing ... | def unique_connection(self):
| return _ConnectionFairy._checkout(self)
|
'Called by subclasses to create a new ConnectionRecord.'
| def _create_connection(self):
| return _ConnectionRecord(self)
|
'Mark all connections established within the generation
of the given connection as invalidated.
If this pool\'s last invalidate time is before when the given
connection was created, update the timestamp til now. Otherwise,
no action is performed.
Connections with a start time prior to this pool\'s invalidation
time wi... | def _invalidate(self, connection, exception=None):
| rec = getattr(connection, '_connection_record', None)
if ((not rec) or (self._invalidate_time < rec.starttime)):
self._invalidate_time = time.time()
if getattr(connection, 'is_valid', False):
connection.invalidate(exception)
|
'Return a new :class:`.Pool`, of the same class as this one
and configured with identical creation arguments.
This method is used in conjunection with :meth:`dispose`
to close out an entire :class:`.Pool` and create a new one in
its place.'
| def recreate(self):
| raise NotImplementedError()
|
'Dispose of this pool.
This method leaves the possibility of checked-out connections
remaining open, as it only affects connections that are
idle in the pool.
See also the :meth:`Pool.recreate` method.'
| def dispose(self):
| raise NotImplementedError()
|
'Return a DBAPI connection from the pool.
The connection is instrumented such that when its
``close()`` method is called, the connection will be returned to
the pool.'
| def connect(self):
| if (not self._use_threadlocal):
return _ConnectionFairy._checkout(self)
try:
rec = self._threadconns.current()
except AttributeError:
pass
else:
if (rec is not None):
return rec._checkout_existing()
return _ConnectionFairy._checkout(self, self._threadconns... |
'Given a _ConnectionRecord, return it to the :class:`.Pool`.
This method is called when an instrumented DBAPI connection
has its ``close()`` method called.'
| def _return_conn(self, record):
| if self._use_threadlocal:
try:
del self._threadconns.current
except AttributeError:
pass
self._do_return_conn(record)
|
'Implementation for :meth:`get`, supplied by subclasses.'
| def _do_get(self):
| raise NotImplementedError()
|
'Implementation for :meth:`return_conn`, supplied by subclasses.'
| def _do_return_conn(self, conn):
| raise NotImplementedError()
|
'The ``.info`` dictionary associated with the DBAPI connection.
This dictionary is shared among the :attr:`._ConnectionFairy.info`
and :attr:`.Connection.info` accessors.'
| @util.memoized_property
def info(self):
| return {}
|
'Invalidate the DBAPI connection held by this :class:`._ConnectionRecord`.
This method is called for all connection invalidations, including
when the :meth:`._ConnectionFairy.invalidate` or :meth:`.Connection.invalidate`
methods are called, as well as when any so-called "automatic invalidation"
condition occurs.
.. see... | def invalidate(self, e=None):
| self.__pool.dispatch.invalidate(self.connection, self, e)
if (e is not None):
self.__pool.logger.info('Invalidate connection %r (reason: %s:%s)', self.connection, e.__class__.__name__, e)
else:
self.__pool.logger.info('Invalidate connection %r', self.connection)
self.__... |
'Return True if this :class:`._ConnectionFairy` still refers
to an active DBAPI connection.'
| @property
def is_valid(self):
| return (self.connection is not None)
|
'Info dictionary associated with the underlying DBAPI connection
referred to by this :class:`.ConnectionFairy`, allowing user-defined
data to be associated with the connection.
The data here will follow along with the DBAPI connection including
after it is returned to the connection pool and used again
in subsequent in... | @util.memoized_property
def info(self):
| return self._connection_record.info
|
'Mark this connection as invalidated.
This method can be called directly, and is also called as a result
of the :meth:`.Connection.invalidate` method. When invoked,
the DBAPI connection is immediately closed and discarded from
further use by the pool. The invalidation mechanism proceeds
via the :meth:`._ConnectionRe... | def invalidate(self, e=None):
| if (self.connection is None):
util.warn("Can't invalidate an already-closed connection.")
return
if self._connection_record:
self._connection_record.invalidate(e=e)
self.connection = None
self._checkin()
|
'Return a new DBAPI cursor for the underlying connection.
This method is a proxy for the ``connection.cursor()`` DBAPI
method.'
| def cursor(self, *args, **kwargs):
| return self.connection.cursor(*args, **kwargs)
|
'Separate this connection from its Pool.
This means that the connection will no longer be returned to the
pool when closed, and will instead be literally closed. The
containing ConnectionRecord is separated from the DB-API connection,
and will create a new connection when next used.
Note that any overall connection li... | def detach(self):
| if (self._connection_record is not None):
_refs.remove(self._connection_record)
self._connection_record.fairy_ref = None
self._connection_record.connection = None
self._pool._do_return_conn(self._connection_record)
self.info = self.info.copy()
self._connection_record ... |
'Dispose of this pool.'
| def dispose(self):
| for conn in self._all_conns:
try:
conn.close()
except (SystemExit, KeyboardInterrupt):
raise
except:
pass
self._all_conns.clear()
|
'Construct a QueuePool.
:param creator: a callable function that returns a DB-API
connection object, same as that of :paramref:`.Pool.creator`.
:param pool_size: The size of the pool to be maintained,
defaults to 5. This is the largest number of connections that
will be kept persistently in the pool. Note that the pool... | def __init__(self, creator, pool_size=5, max_overflow=10, timeout=30, **kw):
| Pool.__init__(self, creator, **kw)
self._pool = sqla_queue.Queue(pool_size)
self._overflow = (0 - pool_size)
self._max_overflow = max_overflow
self._timeout = timeout
self._overflow_lock = threading.Lock()
|
'Initializes a new proxy.
module
a DB-API 2.0 module
poolclass
a Pool class, defaulting to QueuePool
Other parameters are sent to the Pool object\'s constructor.'
| def __init__(self, module, poolclass=QueuePool, **kw):
| self.module = module
self.kw = kw
self.poolclass = poolclass
self.pools = {}
self._create_pool_mutex = threading.Lock()
|
'Activate a connection to the database.
Connect to the database using this DBProxy\'s module and the given
connect arguments. If the arguments match an existing pool, the
connection will be returned from the pool\'s current thread-local
connection instance, or if there is no thread-local connection
instance it will be... | def connect(self, *args, **kw):
| return self.get_pool(*args, **kw).connect()
|
'Dispose the pool referenced by the given connect arguments.'
| def dispose(self, *args, **kw):
| key = self._serialize(*args, **kw)
try:
del self.pools[key]
except KeyError:
pass
|
'Sniff out the character set in use for connection results.'
| def _detect_charset(self, connection):
| return 'utf8'
|
'Construct a NUMERIC.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.'
| def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(NUMERIC, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a DECIMAL.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.'
| def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(DECIMAL, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a DOUBLE.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.'
| def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(DOUBLE, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a REAL.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.'
| def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(REAL, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a FLOAT.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.'
| def __init__(self, precision=None, scale=None, asdecimal=False, **kw):
| super(FLOAT, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct an INTEGER.'
| def __init__(self, **kw):
| super(INTEGER, self).__init__(**kw)
|
'Construct a BIGINTEGER.'
| def __init__(self, **kw):
| super(BIGINT, self).__init__(**kw)
|
'Construct a TEXT.
:param length: Optional, if provided the server may optimize storage
by substituting the smallest TEXT type sufficient to store
``length`` characters.
:param collation: Optional, a column-level collation for this string
value. Takes precedence to \'binary\' short-hand.
:param binary: Defaults to Fal... | def __init__(self, length=None, **kw):
| super(TEXT, self).__init__(length=length, **kw)
|
'Construct a VARCHAR.
:param collation: Optional, a column-level collation for this string
value. Takes precedence to \'binary\' short-hand.
:param binary: Defaults to False: short-hand, pick the binary
collation type that matches the column\'s character set. Generates
BINARY in schema. This does not affect the type... | def __init__(self, length=None, **kwargs):
| super(VARCHAR, self).__init__(length=length, **kwargs)
|
'Construct a CHAR.
:param length: Maximum data length, in characters.
:param binary: Optional, use the default binary collation for the
national character set. This does not affect the type of data
stored, use a BINARY type for binary data.
:param collation: Optional, request a particular collation. Must be
compatibl... | def __init__(self, length=None, **kwargs):
| super(CHAR, self).__init__(length=length, **kwargs)
|
'Construct an ENUM.
Example:
Column(\'myenum\', ENUM("foo", "bar", "baz"))
:param enums: The range of valid values for this ENUM. Values will be
quoted when generating the schema according to the quoting flag (see
below).
:param strict: Defaults to False: ensure that a given value is in this
ENUM\'s range of permissib... | def __init__(self, *enums, **kw):
| super(ENUM, self).__init__(*enums, **kw)
|
'Extend a string-type declaration with standard SQL
COLLATE annotations and Drizzle specific extensions.'
| def _extend_string(self, type_, defaults, spec):
| def attr(name):
return getattr(type_, name, defaults.get(name))
if attr('collation'):
collation = ('COLLATE %s' % type_.collation)
elif attr('binary'):
collation = 'BINARY'
else:
collation = None
return ' '.join([c for c in (spec, collation) if (c is not None)])... |
'Force autocommit - Drizzle Bug#707842 doesn\'t set this properly'
| def on_connect(self):
| def connect(conn):
conn.autocommit(False)
return connect
|
'Return a Unicode SHOW TABLES from a given schema.'
| @reflection.cache
def get_table_names(self, connection, schema=None, **kw):
| if (schema is not None):
current_schema = schema
else:
current_schema = self.default_schema_name
charset = 'utf8'
rp = connection.execute(('SHOW TABLES FROM %s' % self.identifier_preparer.quote_identifier(current_schema)))
return [row[0] for row in self._compat_fetchall(rp, ... |
'Sniff out identifier case sensitivity.
Cached per-connection. This value can not change without a server
restart.'
| def _detect_casing(self, connection):
| return 0
|
'Pull the active COLLATIONS list from the server.
Cached per-connection.'
| def _detect_collations(self, connection):
| collations = {}
charset = self._connection_charset
rs = connection.execute('SELECT CHARACTER_SET_NAME, COLLATION_NAME FROM data_dictionary.COLLATIONS')
for row in self._compat_fetchall(rs, charset):
collations[row[0]] = row[1]
return collations
|
'Detect and adjust for the ANSI_QUOTES sql mode.'
| def _detect_ansiquotes(self, connection):
| self._server_ansiquotes = False
self._backslash_escapes = False
|
'detect if the decimal separator character is not \'.\', as
is the case with european locale settings for NLS_LANG.
cx_oracle itself uses similar logic when it formats Python
Decimal objects to strings on the bind side (as of 5.0.3),
as Oracle sends/receives string numerics only in the
current locale.'
| def _detect_decimal_char(self, connection):
| if (self.cx_oracle_ver < (5,)):
return
cx_Oracle = self.dbapi
conn = connection.connection
def output_type_handler(cursor, name, defaultType, size, precision, scale):
return cursor.var(cx_Oracle.STRING, 255, arraysize=cursor.arraysize)
cursor = conn.cursor()
cursor.outputtypehand... |
'create a two-phase transaction ID.
this id will be passed to do_begin_twophase(), do_rollback_twophase(),
do_commit_twophase(). its format is unspecified.'
| def create_xid(self):
| id = random.randint(0, (2 ** 128))
return (4660, ('%032x' % id), ('%032x' % 9))
|
'Construct an INTERVAL.
Note that only DAY TO SECOND intervals are currently supported.
This is due to a lack of support for YEAR TO MONTH intervals
within available DBAPIs (cx_oracle and zxjdbc).
:param day_precision: the day precision value. this is the number of digits
to store for the day field. Defaults to "2"
:... | def __init__(self, day_precision=None, second_precision=None):
| self.day_precision = day_precision
self.second_precision = second_precision
|
'Called when a ``SELECT`` statement has no froms,
and no ``FROM`` clause is to be appended.
The Oracle compiler tacks a "FROM DUAL" to the statement.'
| def default_from(self):
| return ' FROM DUAL'
|
'Oracle doesn\'t like ``FROM table AS alias``. Is the AS standard SQL??'
| def visit_alias(self, alias, asfrom=False, ashint=False, **kwargs):
| if (asfrom or ashint):
alias_name = ((isinstance(alias.name, expression._truncated_label) and self._truncated_identifier('alias', alias.name)) or alias.name)
if ashint:
return alias_name
elif asfrom:
return ((self.process(alias.original, asfrom=asfrom, **kwargs) + ' ') + self.prep... |
'Need to determine how to get ``LIMIT``/``OFFSET`` into a ``UNION`` for Oracle.'
| def _TODO_visit_compound_select(self, select):
| pass
|
'Look for ``LIMIT`` and OFFSET in a select statement, and if
so tries to wrap it in a subquery with ``rownum`` criterion.'
| def visit_select(self, select, **kwargs):
| if (not getattr(select, '_oracle_visit', None)):
if (not self.dialect.use_ansi):
froms = self._display_froms_for_select(select, kwargs.get('asfrom', False))
whereclause = self._get_nonansi_join_whereclause(froms)
if (whereclause is not None):
select = sele... |
'Return True if the given identifier requires quoting.'
| def _bindparam_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))))
|
'search for a local synonym matching the given desired owner/name.
if desired_owner is None, attempts to locate a distinct owner.
returns the actual name, owner, dblink name, and synonym name if found.'
| def _resolve_synonym(self, connection, desired_owner=None, desired_synonym=None, desired_table=None):
| q = 'SELECT owner, table_owner, table_name, db_link, synonym_name FROM all_synonyms WHERE '
clauses = []
params = {}
if desired_synonym:
clauses.append('synonym_name = :synonym_name')
params['synonym_name'] = desired_synonym
if desired_owner:
... |
'kw arguments can be:
oracle_resolve_synonyms
dblink'
| @reflection.cache
def get_columns(self, connection, table_name, schema=None, **kw):
| resolve_synonyms = kw.get('oracle_resolve_synonyms', False)
dblink = kw.get('dblink', '')
info_cache = kw.get('info_cache')
(table_name, schema, dblink, synonym) = self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache)
columns = []
if self.... |
'kw arguments can be:
oracle_resolve_synonyms
dblink'
| @reflection.cache
def get_foreign_keys(self, connection, table_name, schema=None, **kw):
| requested_schema = schema
resolve_synonyms = kw.get('oracle_resolve_synonyms', False)
dblink = kw.get('dblink', '')
info_cache = kw.get('info_cache')
(table_name, schema, dblink, synonym) = self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache)... |
'Return the table id from `table_name` and `schema`.'
| def get_table_id(self, table_name, schema=None):
| return self.dialect.get_table_id(self.bind, table_name, schema, info_cache=self.info_cache)
|
'Must be implemented by subclasses to accommodate DDL executions.
"connection" is the raw unwrapped DBAPI connection. "value"
is True or False. when True, the connection should be configured
such that a DDL can take place subsequently. when False,
a DDL has taken place and the connection should be resumed
into non-... | def set_ddl_autocommit(self, connection, value):
| raise NotImplementedError()
|
'Fetch the id for schema.table_name.
Several reflection methods require the table id. The idea for using
this method is that it can be fetched one time and cached for
subsequent calls.'
| def get_table_id(self, connection, table_name, schema=None, **kw):
| table_id = None
if (schema is None):
schema = self.default_schema_name
TABLEID_SQL = text("\n SELECT o.id AS id\n FROM sysobjects o JOIN sysusers u ON o.uid=u.uid\n ... |
'Convert a MySQL\'s 64 bit, variable length binary string to a long.'
| def result_processor(self, dialect, coltype):
| def process(value):
if (value is not None):
v = 0
for i in util.iterbytes(value):
v = ((v << 8) | i)
return v
return value
return process
|
'Construct a NUMERIC.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as st... | def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(NUMERIC, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a DECIMAL.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as st... | def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(DECIMAL, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a DOUBLE.
.. note::
The :class:`.DOUBLE` type by default converts from float
to Decimal, using a truncation that defaults to 10 digits. Specify
either ``scale=n`` or ``decimal_return_scale=n`` in order to change
this scale, or ``asdecimal=False`` to return values directly as
Python floating points.
:param p... | def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(DOUBLE, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a REAL.
.. note::
The :class:`.REAL` type by default converts from float
to Decimal, using a truncation that defaults to 10 digits. Specify
either ``scale=n`` or ``decimal_return_scale=n`` in order to change
this scale, or ``asdecimal=False`` to return values directly as
Python floating points.
:param preci... | def __init__(self, precision=None, scale=None, asdecimal=True, **kw):
| super(REAL, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct a FLOAT.
:param precision: Total digits in this number. If scale and precision
are both None, values are stored to limits allowed by the server.
:param scale: The number of digits after the decimal point.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as stri... | def __init__(self, precision=None, scale=None, asdecimal=False, **kw):
| super(FLOAT, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal, **kw)
|
'Construct an INTEGER.
:param display_width: Optional, maximum display width for this number.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as strings
left-padded with zeros. Note that this does not effect the values
returned by the underlying database API, which contin... | def __init__(self, display_width=None, **kw):
| super(INTEGER, self).__init__(display_width=display_width, **kw)
|
'Construct a BIGINTEGER.
:param display_width: Optional, maximum display width for this number.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as strings
left-padded with zeros. Note that this does not effect the values
returned by the underlying database API, which cont... | def __init__(self, display_width=None, **kw):
| super(BIGINT, self).__init__(display_width=display_width, **kw)
|
'Construct a MEDIUMINTEGER
:param display_width: Optional, maximum display width for this number.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as strings
left-padded with zeros. Note that this does not effect the values
returned by the underlying database API, which co... | def __init__(self, display_width=None, **kw):
| super(MEDIUMINT, self).__init__(display_width=display_width, **kw)
|
'Construct a TINYINT.
:param display_width: Optional, maximum display width for this number.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as strings
left-padded with zeros. Note that this does not effect the values
returned by the underlying database API, which continu... | def __init__(self, display_width=None, **kw):
| super(TINYINT, self).__init__(display_width=display_width, **kw)
|
'Construct a SMALLINTEGER.
:param display_width: Optional, maximum display width for this number.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as strings
left-padded with zeros. Note that this does not effect the values
returned by the underlying database API, which co... | def __init__(self, display_width=None, **kw):
| super(SMALLINT, self).__init__(display_width=display_width, **kw)
|
'Construct a BIT.
:param length: Optional, number of bits.'
| def __init__(self, length=None):
| self.length = length
|
'Convert a MySQL\'s 64 bit, variable length binary string to a long.
TODO: this is MySQL-db, pyodbc specific. OurSQL and mysqlconnector
already do this, so this logic should be moved to those dialects.'
| def result_processor(self, dialect, coltype):
| def process(value):
if (value is not None):
v = 0
for i in map(ord, value):
v = ((v << 8) | i)
return v
return value
return process
|
'Construct a MySQL TIME type.
:param timezone: not used by the MySQL dialect.
:param fsp: fractional seconds precision value.
MySQL 5.6 supports storage of fractional seconds;
this parameter will be used when emitting DDL
for the TIME type.
.. note::
DBAPI driver support for fractional seconds may
be limited; current s... | def __init__(self, timezone=False, fsp=None):
| super(TIME, self).__init__(timezone=timezone)
self.fsp = fsp
|
'Construct a MySQL TIMESTAMP type.
:param timezone: not used by the MySQL dialect.
:param fsp: fractional seconds precision value.
MySQL 5.6.4 supports storage of fractional seconds;
this parameter will be used when emitting DDL
for the TIMESTAMP type.
.. note::
DBAPI driver support for fractional seconds may
be limite... | def __init__(self, timezone=False, fsp=None):
| super(TIMESTAMP, self).__init__(timezone=timezone)
self.fsp = fsp
|
'Construct a MySQL DATETIME type.
:param timezone: not used by the MySQL dialect.
:param fsp: fractional seconds precision value.
MySQL 5.6.4 supports storage of fractional seconds;
this parameter will be used when emitting DDL
for the DATETIME type.
.. note::
DBAPI driver support for fractional seconds may
be limited;... | def __init__(self, timezone=False, fsp=None):
| super(DATETIME, self).__init__(timezone=timezone)
self.fsp = fsp
|
'Construct a TEXT.
:param length: Optional, if provided the server may optimize storage
by substituting the smallest TEXT type sufficient to store
``length`` characters.
:param charset: Optional, a column-level character set for this string
value. Takes precedence to \'ascii\' or \'unicode\' short-hand.
:param collati... | def __init__(self, length=None, **kw):
| super(TEXT, self).__init__(length=length, **kw)
|
'Construct a TINYTEXT.
:param charset: Optional, a column-level character set for this string
value. Takes precedence to \'ascii\' or \'unicode\' short-hand.
:param collation: Optional, a column-level collation for this string
value. Takes precedence to \'binary\' short-hand.
:param ascii: Defaults to False: short-ha... | def __init__(self, **kwargs):
| super(TINYTEXT, self).__init__(**kwargs)
|
'Construct a MEDIUMTEXT.
:param charset: Optional, a column-level character set for this string
value. Takes precedence to \'ascii\' or \'unicode\' short-hand.
:param collation: Optional, a column-level collation for this string
value. Takes precedence to \'binary\' short-hand.
:param ascii: Defaults to False: short-... | def __init__(self, **kwargs):
| super(MEDIUMTEXT, self).__init__(**kwargs)
|
'Construct a LONGTEXT.
:param charset: Optional, a column-level character set for this string
value. Takes precedence to \'ascii\' or \'unicode\' short-hand.
:param collation: Optional, a column-level collation for this string
value. Takes precedence to \'binary\' short-hand.
:param ascii: Defaults to False: short-ha... | def __init__(self, **kwargs):
| super(LONGTEXT, self).__init__(**kwargs)
|
'Construct a VARCHAR.
:param charset: Optional, a column-level character set for this string
value. Takes precedence to \'ascii\' or \'unicode\' short-hand.
:param collation: Optional, a column-level collation for this string
value. Takes precedence to \'binary\' short-hand.
:param ascii: Defaults to False: short-han... | def __init__(self, length=None, **kwargs):
| super(VARCHAR, self).__init__(length=length, **kwargs)
|
'Construct a CHAR.
:param length: Maximum data length, in characters.
:param binary: Optional, use the default binary collation for the
national character set. This does not affect the type of data
stored, use a BINARY type for binary data.
:param collation: Optional, request a particular collation. Must be
compatibl... | def __init__(self, length=None, **kwargs):
| super(CHAR, self).__init__(length=length, **kwargs)
|
'Construct an NVARCHAR.
:param length: Maximum data length, in characters.
:param binary: Optional, use the default binary collation for the
national character set. This does not affect the type of data
stored, use a BINARY type for binary data.
:param collation: Optional, request a particular collation. Must be
comp... | def __init__(self, length=None, **kwargs):
| kwargs['national'] = True
super(NVARCHAR, self).__init__(length=length, **kwargs)
|
'Construct an NCHAR.
:param length: Maximum data length, in characters.
:param binary: Optional, use the default binary collation for the
national character set. This does not affect the type of data
stored, use a BINARY type for binary data.
:param collation: Optional, request a particular collation. Must be
compati... | def __init__(self, length=None, **kwargs):
| kwargs['national'] = True
super(NCHAR, self).__init__(length=length, **kwargs)
|
'Construct an ENUM.
E.g.::
Column(\'myenum\', ENUM("foo", "bar", "baz"))
:param enums: The range of valid values for this ENUM. Values will be
quoted when generating the schema according to the quoting flag (see
below).
:param strict: Defaults to False: ensure that a given value is in this
ENUM\'s range of permissible... | def __init__(self, *enums, **kw):
| (values, length) = self._init_values(enums, kw)
self.strict = kw.pop('strict', False)
kw.pop('metadata', None)
kw.pop('schema', None)
kw.pop('name', None)
kw.pop('quote', None)
kw.pop('native_enum', None)
kw.pop('inherit_schema', None)
_StringType.__init__(self, length=length, **kw)
... |
'Construct a SET.
E.g.::
Column(\'myset\', SET("foo", "bar", "baz"))
:param values: The range of valid values for this SET. Values will be
quoted when generating the schema according to the quoting flag (see
below).
.. versionchanged:: 0.9.0 quoting is applied automatically to
:class:`.mysql.SET` in the same way as fo... | def __init__(self, *values, **kw):
| (values, length) = self._init_values(values, kw)
self.values = tuple(values)
kw.setdefault('length', length)
super(SET, self).__init__(**kw)
|
'Add special MySQL keywords in place of DISTINCT.
.. note::
this usage is deprecated. :meth:`.Select.prefix_with`
should be used for special keywords at the start
of a SELECT.'
| def get_select_precolumns(self, select):
| if isinstance(select._distinct, util.string_types):
return (select._distinct.upper() + ' ')
elif select._distinct:
return 'DISTINCT '
else:
return ''
|
'Get table constraints.'
| def create_table_constraints(self, table):
| constraint_string = super(MySQLDDLCompiler, self).create_table_constraints(table)
is_innodb = (('engine' in table.dialect_options[self.dialect.name]) and (table.dialect_options[self.dialect.name]['engine'].lower() == 'innodb'))
auto_inc_column = table._autoincrement_column
if (is_innodb and (auto_inc_co... |
'Builds column DDL.'
| def get_column_specification(self, column, **kw):
| colspec = [self.preparer.format_column(column), self.dialect.type_compiler.process(column.type)]
default = self.get_column_default_string(column)
if (default is not None):
colspec.append(('DEFAULT ' + default))
is_timestamp = isinstance(column.type, sqltypes.TIMESTAMP)
if ((not column.nul... |
'Build table-level CREATE options like ENGINE and COLLATE.'
| def post_create_table(self, table):
| table_opts = []
opts = dict(((k[(len(self.dialect.name) + 1):].upper(), v) for (k, v) in table.kwargs.items() if k.startswith(('%s_' % self.dialect.name))))
for opt in topological.sort([('DEFAULT_CHARSET', 'COLLATE'), ('DEFAULT_CHARACTER_SET', 'COLLATE'), ('PARTITION_BY', 'PARTITIONS')], opts):
arg ... |
'Extend a numeric-type declaration with MySQL specific extensions.'
| def _extend_numeric(self, type_, spec):
| if (not self._mysql_type(type_)):
return spec
if type_.unsigned:
spec += ' UNSIGNED'
if type_.zerofill:
spec += ' ZEROFILL'
return spec
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.