desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Extend a string-type declaration with standard SQL CHARACTER SET /
COLLATE annotations and MySQL specific extensions.'
| def _extend_string(self, type_, defaults, spec):
| def attr(name):
return getattr(type_, name, defaults.get(name))
if attr('charset'):
charset = ('CHARACTER SET %s' % attr('charset'))
elif attr('ascii'):
charset = 'ASCII'
elif attr('unicode'):
charset = 'UNICODE'
else:
charset = None
if attr('collati... |
'Unilaterally identifier-quote any number of strings.'
| def _quote_free_identifiers(self, *ids):
| return tuple([self.quote_identifier(i) for i in ids if (i is not None)])
|
'Execute a COMMIT.'
| def do_commit(self, dbapi_connection):
| try:
dbapi_connection.commit()
except:
if (self.server_version_info < (3, 23, 15)):
args = sys.exc_info()[1].args
if (args and (args[0] == 1064)):
return
raise
|
'Execute a ROLLBACK.'
| def do_rollback(self, dbapi_connection):
| try:
dbapi_connection.rollback()
except:
if (self.server_version_info < (3, 23, 15)):
args = sys.exc_info()[1].args
if (args and (args[0] == 1064)):
return
raise
|
'Proxy result rows to smooth over MySQL-Python driver
inconsistencies.'
| def _compat_fetchall(self, rp, charset=None):
| return [_DecodingRowProxy(row, charset) for row in rp.fetchall()]
|
'Proxy a result row to smooth over MySQL-Python driver
inconsistencies.'
| def _compat_fetchone(self, rp, charset=None):
| return _DecodingRowProxy(rp.fetchone(), charset)
|
'Proxy a result row to smooth over MySQL-Python driver
inconsistencies.'
| def _compat_first(self, rp, charset=None):
| return _DecodingRowProxy(rp.first(), charset)
|
'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 = self._connection_charset
if (self.server_version_info < (5, 0, 2)):
rp = connection.execute(('SHOW TABLES FROM %s' % self.identifier_preparer.quote_identifier(curre... |
'return the MySQLTableDefinitionParser, generate if needed.
The deferred creation ensures that the dialect has
retrieved server version information first.'
| @util.memoized_property
def _tabledef_parser(self):
| if ((self.server_version_info < (4, 1)) and self._server_ansiquotes):
preparer = self.preparer(self, server_ansiquotes=False)
else:
preparer = self.identifier_preparer
return MySQLTableDefinitionParser(self, preparer)
|
'Sniff out identifier case sensitivity.
Cached per-connection. This value can not change without a server
restart.'
| def _detect_casing(self, connection):
| charset = self._connection_charset
row = self._compat_first(connection.execute("SHOW VARIABLES LIKE 'lower_case_table_names'"), charset=charset)
if (not row):
cs = 0
elif (row[1] == 'OFF'):
cs = 0
elif (row[1] == 'ON'):
cs = 1
else:
cs = int(row[1])
r... |
'Pull the active COLLATIONS list from the server.
Cached per-connection.'
| def _detect_collations(self, connection):
| collations = {}
if (self.server_version_info < (4, 1, 0)):
pass
else:
charset = self._connection_charset
rs = connection.execute('SHOW COLLATION')
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):
| row = self._compat_first(connection.execute("SHOW VARIABLES LIKE 'sql_mode'"), charset=self._connection_charset)
if (not row):
mode = ''
else:
mode = (row[1] or '')
if mode.isdigit():
mode_no = int(mode)
mode = ((((mode_no | 4) == mode_no) and 'ANSI_Q... |
'Run SHOW CREATE TABLE for a ``Table``.'
| def _show_create_table(self, connection, table, charset=None, full_name=None):
| if (full_name is None):
full_name = self.identifier_preparer.format_table(table)
st = ('SHOW CREATE TABLE %s' % full_name)
rp = None
try:
rp = connection.execute(st)
except exc.DBAPIError as e:
if (self._extract_error_code(e.orig) == 1146):
raise exc.NoSu... |
'Run DESCRIBE for a ``Table`` and return processed rows.'
| def _describe_table(self, connection, table, charset=None, full_name=None):
| if (full_name is None):
full_name = self.identifier_preparer.format_table(table)
st = ('DESCRIBE %s' % full_name)
(rp, rows) = (None, None)
try:
try:
rp = connection.execute(st)
except exc.DBAPIError as e:
if (self._extract_error_code(e.orig) == 1146):
... |
'Parse a KEY or CONSTRAINT line.
:param line: A line of SHOW CREATE TABLE output'
| def _parse_constraints(self, line):
| m = self._re_key.match(line)
if m:
spec = m.groupdict()
spec['columns'] = self._parse_keyexprs(spec['columns'])
return ('key', spec)
m = self._re_constraint.match(line)
if m:
spec = m.groupdict()
spec['table'] = self.preparer.unformat_identifiers(spec['table'])
... |
'Extract the table name.
:param line: The first line of SHOW CREATE TABLE'
| def _parse_table_name(self, line, state):
| (regex, cleanup) = self._pr_name
m = regex.match(line)
if m:
state.table_name = cleanup(m.group('name'))
|
'Build a dictionary of all reflected table-level options.
:param line: The final line of SHOW CREATE TABLE output.'
| def _parse_table_options(self, line, state):
| options = {}
if ((not line) or (line == ')')):
pass
else:
rest_of_line = line[:]
for (regex, cleanup) in self._pr_options:
m = regex.search(rest_of_line)
if (not m):
continue
(directive, value) = (m.group('directive'), m.group('val'... |
'Extract column details.
Falls back to a \'minimal support\' variant if full parse fails.
:param line: Any column-bearing line from SHOW CREATE TABLE'
| def _parse_column(self, line, state):
| spec = None
m = self._re_column.match(line)
if m:
spec = m.groupdict()
spec['full'] = True
else:
m = self._re_column_loose.match(line)
if m:
spec = m.groupdict()
spec['full'] = False
if (not spec):
util.warn(('Unknown column defin... |
'Re-format DESCRIBE output as a SHOW CREATE TABLE string.
DESCRIBE is a much simpler reflection and is sufficient for
reflecting views for runtime use. This method formats DDL
for columns only- keys are omitted.
:param columns: A sequence of DESCRIBE or SHOW COLUMNS 6-tuples.
SHOW FULL COLUMNS FROM rows must be rearra... | def _describe_to_create(self, table_name, columns):
| buffer = []
for row in columns:
(name, col_type, nullable, default, extra) = [row[i] for i in (0, 1, 2, 4, 5)]
line = [' ']
line.append(self.preparer.quote_identifier(name))
line.append(col_type)
if (not nullable):
line.append('NOT NULL')
if defa... |
'Unpack \'"col"(2),"col" ASC\'-ish strings into components.'
| def _parse_keyexprs(self, identifiers):
| return self._re_keyexprs.findall(identifiers)
|
'Pre-compile regular expressions.'
| def _prep_regexes(self):
| self._re_columns = []
self._pr_options = []
_final = self.preparer.final_quote
quotes = dict(zip(('iq', 'fq', 'esc_fq'), [re.escape(s) for s in (self.preparer.initial_quote, _final, self.preparer._escape_identifier(_final))]))
self._pr_name = _pr_compile(('^CREATE (?:\\w+ +)?TABLE +%(iq)s(?... |
'MySQL-connector already converts mysql bits, so.'
| def result_processor(self, dialect, coltype):
| return None
|
'oursql already converts mysql bits, so.'
| def result_processor(self, dialect, coltype):
| return None
|
'Provide an implementation of *cursor.execute(statement, parameters)*.'
| def do_execute(self, cursor, statement, parameters, context=None):
| if (context and context.plain_query):
cursor.execute(statement, plain_query=True)
else:
cursor.execute(statement, parameters)
|
'Sniff out the character set in use for connection results.'
| def _detect_charset(self, connection):
| return connection.connection.charset
|
'oursql isn\'t super-broken like MySQLdb, yaaay.'
| def _compat_fetchall(self, rp, charset=None):
| return rp.fetchall()
|
'oursql isn\'t super-broken like MySQLdb, yaaay.'
| def _compat_fetchone(self, rp, charset=None):
| return rp.fetchone()
|
'Converts boolean or byte arrays from MySQL Connector/J to longs.'
| def result_processor(self, dialect, coltype):
| def process(value):
if (value is None):
return value
if isinstance(value, bool):
return int(value)
v = 0
for i in value:
v = ((v << 8) | (i & 255))
value = v
return value
return process
|
'Sniff out the character set in use for connection results.'
| def _detect_charset(self, connection):
| rs = connection.execute("SHOW VARIABLES LIKE 'character_set%%'")
opts = dict(((row[0], row[1]) for row in self._compat_fetchall(rs)))
for key in ('character_set_connection', 'character_set'):
if opts.get(key, None):
return opts[key]
util.warn('Could not detect the ... |
'return kw arg dict to be sent to connect().'
| def _driver_kwargs(self):
| return dict(characterEncoding='UTF-8', yearIsDateType='false')
|
'Sniff out the character set in use for connection results.'
| def _detect_charset(self, connection):
| rs = connection.execute("SHOW VARIABLES LIKE 'character_set%%'")
opts = dict([(row[0], row[1]) for row in self._compat_fetchall(rs)])
for key in ('character_set_connection', 'character_set'):
if opts.get(key, None):
return opts[key]
util.warn('Could not detect the ... |
'Format the remote table clause of a CREATE CONSTRAINT clause.'
| def define_constraint_remote_table(self, constraint, table, preparer):
| return preparer.format_table(table, use_schema=False)
|
'Prepare a quoted index and schema name.'
| def format_index(self, index, use_schema=True, name=None):
| if (name is None):
name = index.name
result = self.quote(name, index.quote)
if ((not self.omit_schema) and use_schema and getattr(index.table, 'schema', None)):
result = ((self.quote_schema(index.table.schema, index.table.quote_schema) + '.') + result)
return result
|
'Return a data type from a reflected column, using affinity tules.
SQLite\'s goal for universal compatability introduces some complexity
during reflection, as a column\'s defined type might not actually be a
type that SQLite understands - or indeed, my not be defined *at all*.
Internally, SQLite handles this with a \'d... | def _resolve_type_affinity(self, type_):
| match = re.match('([\\w ]+)(\\(.*?\\))?', type_)
if match:
coltype = match.group(1)
args = match.group(2)
else:
coltype = ''
args = ''
if (coltype in self.ischema_names):
coltype = self.ischema_names[coltype]
elif ('INT' in coltype):
coltype = sqlty... |
'Construct a UUID type.
:param as_uuid=False: if True, values will be interpreted
as Python uuid objects, converting to/from string via the
DBAPI.'
| def __init__(self, as_uuid=False):
| if (as_uuid and (_python_UUID is None)):
raise NotImplementedError('This version of Python does not support the native UUID type.')
self.as_uuid = as_uuid
|
'Return ``other operator ANY (array)`` clause.
Argument places are switched, because ANY requires array
expression to be on the right hand-side.
E.g.::
from sqlalchemy.sql import operators
conn.execute(
select([table.c.data]).where(
table.c.data.any(7, operator=operators.lt)
:param other: expression to be compared
:par... | def any(self, other, operator=operators.eq):
| return Any(other, self.expr, operator=operator)
|
'Return ``other operator ALL (array)`` clause.
Argument places are switched, because ALL requires array
expression to be on the right hand-side.
E.g.::
from sqlalchemy.sql import operators
conn.execute(
select([table.c.data]).where(
table.c.data.all(7, operator=operators.lt)
:param other: expression to be compared
:par... | def all(self, other, operator=operators.eq):
| return All(other, self.expr, operator=operator)
|
'Boolean expression. Test if elements are a superset of the
elements of the argument array expression.'
| def contains(self, other, **kwargs):
| return self.expr.op('@>')(other)
|
'Boolean expression. Test if elements are a proper subset of the
elements of the argument array expression.'
| def contained_by(self, other):
| return self.expr.op('<@')(other)
|
'Boolean expression. Test if array has elements in common with
an argument array expression.'
| def overlap(self, other):
| return self.expr.op('&&')(other)
|
'Construct an ARRAY.
E.g.::
Column(\'myarray\', ARRAY(Integer))
Arguments are:
:param item_type: The data type of items of this array. Note that
dimensionality is irrelevant here, so multi-dimensional arrays like
``INTEGER[][]``, are constructed as ``ARRAY(Integer)``, not as
``ARRAY(ARRAY(Integer))`` or such.
:param as... | def __init__(self, item_type, as_tuple=False, dimensions=None):
| if isinstance(item_type, ARRAY):
raise ValueError('Do not nest ARRAY types; ARRAY(basetype) handles multi-dimensional arrays of basetype')
if isinstance(item_type, type):
item_type = item_type()
self.item_type = item_type
self.as_tuple = as_tuple
self.di... |
'Construct an :class:`~.postgresql.ENUM`.
Arguments are the same as that of
:class:`.types.Enum`, but also including
the following parameters.
:param create_type: Defaults to True.
Indicates that ``CREATE TYPE`` should be
emitted, after optionally checking for the
presence of the type, when the parent
table is being cr... | def __init__(self, *enums, **kw):
| self.create_type = kw.pop('create_type', True)
super(ENUM, self).__init__(*enums, **kw)
|
'Emit ``CREATE TYPE`` for this
:class:`~.postgresql.ENUM`.
If the underlying dialect does not support
Postgresql CREATE TYPE, no action is taken.
:param bind: a connectable :class:`.Engine`,
:class:`.Connection`, or similar object to emit
SQL.
:param checkfirst: if ``True``, a query against
the PG catalog will be first... | def create(self, bind=None, checkfirst=True):
| if (not bind.dialect.supports_native_enum):
return
if ((not checkfirst) or (not bind.dialect.has_type(bind, self.name, schema=self.schema))):
bind.execute(CreateEnumType(self))
|
'Emit ``DROP TYPE`` for this
:class:`~.postgresql.ENUM`.
If the underlying dialect does not support
Postgresql DROP TYPE, no action is taken.
:param bind: a connectable :class:`.Engine`,
:class:`.Connection`, or similar object to emit
SQL.
:param checkfirst: if ``True``, a query against
the PG catalog will be first per... | def drop(self, bind=None, checkfirst=True):
| if (not bind.dialect.supports_native_enum):
return
if ((not checkfirst) or bind.dialect.has_type(bind, self.name, schema=self.schema)):
bind.execute(DropEnumType(self))
|
'Look in the \'ddl runner\' for \'memos\', then
note our name in that collection.
This to ensure a particular named enum is operated
upon only once within any kind of create/drop
sequence without relying upon "checkfirst".'
| def _check_for_name_in_memos(self, checkfirst, kw):
| if (not self.create_type):
return True
if ('_ddl_runner' in kw):
ddl_runner = kw['_ddl_runner']
if ('_pg_enums' in ddl_runner.memo):
pg_enums = ddl_runner.memo['_pg_enums']
else:
pg_enums = ddl_runner.memo['_pg_enums'] = set()
present = (self.name ... |
'Return the oid from `table_name` and `schema`.'
| def get_table_oid(self, table_name, schema=None):
| return self.dialect.get_table_oid(self.bind, table_name, schema, info_cache=self.info_cache)
|
'Fetch the oid for schema.table_name.
Several reflection methods require the table oid. The idea for using
this method is that it can be fetched one time and cached for
subsequent calls.'
| @reflection.cache
def get_table_oid(self, connection, table_name, schema=None, **kw):
| table_oid = None
if (schema is not None):
schema_where_clause = 'n.nspname = :schema'
else:
schema_where_clause = 'pg_catalog.pg_table_is_visible(c.oid)'
query = ("\n SELECT c.oid\n FRO... |
'Convert this :class:`.JSONElement` to use the \'astext\' operator
when evaluated.
E.g.::
select([data_table.c.data[\'some key\'].astext])
.. seealso::
:meth:`.JSONElement.cast`'
| @property
def astext(self):
| if self._astext:
return self
else:
return JSONElement(self.left, self.right, astext=True, opstring=(self._json_opstring + '>'), result_type=sqltypes.String(convert_unicode=True))
|
'Convert this :class:`.JSONElement` to apply both the \'astext\' operator
as well as an explicit type cast when evaulated.
E.g.::
select([data_table.c.data[\'some key\'].cast(Integer)])
.. seealso::
:attr:`.JSONElement.astext`'
| def cast(self, type_):
| if (not self._astext):
return self.astext.cast(type_)
else:
return sql.cast(self, type_)
|
'Get the value at a given key.'
| def __getitem__(self, other):
| return JSONElement(self.expr, other)
|
':param \*elements:
A sequence of two tuples of the form ``(column, operator)`` where
column must be a column name or Column object and operator must
be a string containing the operator to use.
:param name:
Optional, the in-database name of this constraint.
:param deferrable:
Optional bool. If set, emit DEFERRABLE or ... | def __init__(self, *elements, **kw):
| ColumnCollectionConstraint.__init__(self, name=kw.get('name'), deferrable=kw.get('deferrable'), initially=kw.get('initially'), *[col for (col, op) in elements])
self.operators = {}
for (col_or_string, op) in elements:
name = getattr(col_or_string, 'name', col_or_string)
self.operators[name] ... |
'Boolean expression. Returns true if two ranges are not equal'
| def __ne__(self, other):
| return self.expr.op('<>')(other)
|
'Boolean expression. Returns true if the right hand operand,
which can be an element or a range, is contained within the
column.'
| def contains(self, other, **kw):
| return self.expr.op('@>')(other)
|
'Boolean expression. Returns true if the column is contained
within the right hand operand.'
| def contained_by(self, other):
| return self.expr.op('<@')(other)
|
'Boolean expression. Returns true if the column overlaps
(has points in common with) the right hand operand.'
| def overlaps(self, other):
| return self.expr.op('&&')(other)
|
'Boolean expression. Returns true if the column is strictly
left of the right hand operand.'
| def strictly_left_of(self, other):
| return self.expr.op('<<')(other)
|
'Boolean expression. Returns true if the column is strictly
right of the right hand operand.'
| def strictly_right_of(self, other):
| return self.expr.op('>>')(other)
|
'Boolean expression. Returns true if the range in the column
does not extend right of the range in the operand.'
| def not_extend_right_of(self, other):
| return self.expr.op('&<')(other)
|
'Boolean expression. Returns true if the range in the column
does not extend left of the range in the operand.'
| def not_extend_left_of(self, other):
| return self.expr.op('&>')(other)
|
'Boolean expression. Returns true if the range in the column
is adjacent to the range in the operand.'
| def adjacent_to(self, other):
| return self.expr.op('-|-')(other)
|
'Range expression. Returns the union of the two ranges.
Will raise an exception if the resulting range is not
contigous.'
| def __add__(self, other):
| return self.expr.op('+')(other)
|
'Boolean expression. Test for presence of a key. Note that the
key may be a SQLA expression.'
| def has_key(self, other):
| return self.expr.op('?')(other)
|
'Boolean expression. Test for presence of all keys in the PG
array.'
| def has_all(self, other):
| return self.expr.op('?&')(other)
|
'Boolean expression. Test for presence of any key in the PG
array.'
| def has_any(self, other):
| return self.expr.op('?|')(other)
|
'Boolean expression. Test for presence of a non-NULL value for
the key. Note that the key may be a SQLA expression.'
| def defined(self, key):
| return _HStoreDefinedFunction(self.expr, key)
|
'Boolean expression. Test if keys are a superset of the keys of
the argument hstore expression.'
| def contains(self, other, **kwargs):
| return self.expr.op('@>')(other)
|
'Boolean expression. Test if keys are a proper subset of the
keys of the argument hstore expression.'
| def contained_by(self, other):
| return self.expr.op('<@')(other)
|
'Text expression. Get the value at a given key. Note that the
key may be a SQLA expression.'
| def __getitem__(self, other):
| return self.expr.op('->', precedence=5)(other)
|
'HStore expression. Returns the contents of this hstore with the
given key deleted. Note that the key may be a SQLA expression.'
| def delete(self, key):
| if isinstance(key, dict):
key = _serialize_hstore(key)
return _HStoreDeleteFunction(self.expr, key)
|
'HStore expression. Returns a subset of an hstore defined by
array of keys.'
| def slice(self, array):
| return _HStoreSliceFunction(self.expr, array)
|
'Text array expression. Returns array of keys.'
| def keys(self):
| return _HStoreKeysFunction(self.expr)
|
'Text array expression. Returns array of values.'
| def vals(self):
| return _HStoreValsFunction(self.expr)
|
'Text array expression. Returns array of alternating keys and
values.'
| def array(self):
| return _HStoreArrayFunction(self.expr)
|
'Text array expression. Returns array of [key, value] pairs.'
| def matrix(self):
| return _HStoreMatrixFunction(self.expr)
|
'Called when building a ``SELECT`` statement, position is just
before column list Firebird puts the limit and offset right
after the ``SELECT``...'
| def get_select_precolumns(self, select):
| result = ''
if select._limit:
result += ('FIRST %s ' % self.process(sql.literal(select._limit)))
if select._offset:
result += ('SKIP %s ' % self.process(sql.literal(select._offset)))
if select._distinct:
result += 'DISTINCT '
return result
|
'Already taken care of in the `get_select_precolumns` method.'
| def limit_clause(self, select):
| return ''
|
'Generate a ``CREATE GENERATOR`` statement for the sequence.'
| def visit_create_sequence(self, create):
| if (create.element.start is not None):
raise NotImplemented("Firebird SEQUENCE doesn't support START WITH")
if (create.element.increment is not None):
raise NotImplemented("Firebird SEQUENCE doesn't support INCREMENT BY")
if self.dialect._version_two:
re... |
'Generate a ``DROP GENERATOR`` statement for the sequence.'
| def visit_drop_sequence(self, drop):
| if self.dialect._version_two:
return ('DROP SEQUENCE %s' % self.preparer.format_sequence(drop.element))
else:
return ('DROP GENERATOR %s' % self.preparer.format_sequence(drop.element))
|
'Get the next value from the sequence using ``gen_id()``.'
| def fire_sequence(self, seq, type_):
| return self._execute_scalar(('SELECT gen_id(%s, 1) FROM rdb$database' % self.dialect.identifier_preparer.format_sequence(seq)), type_)
|
'Return ``True`` if the given table exists, ignoring
the `schema`.'
| def has_table(self, connection, table_name, schema=None):
| tblqry = '\n SELECT 1 AS has_table FROM rdb$database\n WHERE EXISTS (SELECT rdb$relation_name\n FROM rdb$relations\n ... |
'Return ``True`` if the given sequence (generator) exists.'
| def has_sequence(self, connection, sequence_name, schema=None):
| genqry = '\n SELECT 1 AS has_sequence FROM rdb$database\n WHERE EXISTS (SELECT rdb$generator_name\n FROM rdb$generators\n ... |
'Get the version of the Firebird server used by a connection.
Returns a tuple of (`major`, `minor`, `build`), three integers
representing the version of the attached server.'
| def _get_server_version_info(self, connection):
| isc_info_firebird_version = 103
fbconn = connection.connection
version = fbconn.db_info(isc_info_firebird_version)
return self._parse_version_info(version)
|
'Get the version of the Firebird server used by a connection.
Returns a tuple of (`major`, `minor`, `build`), three integers
representing the version of the attached server.'
| def _get_server_version_info(self, connection):
| fbconn = connection.connection
version = fbconn.server_version
return self._parse_version_info(version)
|
'Extend a string-type declaration with standard SQL
COLLATE annotations.'
| def _extend(self, spec, type_, length=None):
| if getattr(type_, 'collation', None):
collation = ('COLLATE %s' % type_.collation)
else:
collation = None
if (not length):
length = type_.length
if length:
spec = (spec + ('(%s)' % length))
return ' '.join([c for c in (spec, collation) if (c is not None)])
|
'Activate IDENTITY_INSERT if needed.'
| def pre_exec(self):
| if self.isinsert:
tbl = self.compiled.statement.table
seq_column = tbl._autoincrement_column
insert_has_sequence = (seq_column is not None)
if insert_has_sequence:
self._enable_identity_insert = (seq_column.key in self.compiled_parameters[0])
else:
sel... |
'Disable IDENTITY_INSERT if enabled.'
| def post_exec(self):
| conn = self.root_connection
if self._select_lastrowid:
if self.dialect.use_scope_identity:
conn._cursor_execute(self.cursor, 'SELECT scope_identity() AS lastrowid', (), self)
else:
conn._cursor_execute(self.cursor, 'SELECT @@identity AS lastrowid', (), s... |
'MS-SQL puts TOP, it\'s version of LIMIT here'
| def get_select_precolumns(self, select):
| if (select._distinct or (select._limit is not None)):
s = ((select._distinct and 'DISTINCT ') or '')
if (select._limit is not None):
if (not select._offset):
s += ('TOP %d ' % select._limit)
return s
return compiler.SQLCompiler.get_select_precolumns(s... |
'Look for ``LIMIT`` and OFFSET in a select statement, and if
so tries to wrap it in a subquery with ``row_number()`` criterion.'
| def visit_select(self, select, **kwargs):
| if (select._offset and (not getattr(select, '_mssql_visit', None))):
if (not select._order_by_clause.clauses):
raise exc.CompileError('MSSQL requires an order_by when using an offset.')
_offset = select._offset
_limit = select._limit
_order_by_clauses... |
'Move bind parameters to the right-hand side of an operator, where
possible.'
| def visit_binary(self, binary, **kwargs):
| if (isinstance(binary.left, expression.BindParameter) and (binary.operator == operator.eq) and (not isinstance(binary.right, expression.BindParameter))):
return self.process(expression.BinaryExpression(binary.right, binary.left, binary.operator), **kwargs)
return super(MSSQLCompiler, self).visit_binary(... |
'Render the UPDATE..FROM clause specific to MSSQL.
In MSSQL, if the UPDATE statement involves an alias of the table to
be updated, then the table itself must be added to the FROM list as
well. Otherwise, it is optional. Here, we add it regardless.'
| 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 ([from_table] + extra_froms))))
|
'For date and datetime values, convert to a string
format acceptable to MSSQL. That seems to be the
so-called ODBC canonical date format which looks
like this:
yyyy-mm-dd hh:mi:ss.mmm(24h)
For other data types, call the base class implementation.'
| def render_literal_value(self, value, type_):
| if issubclass(type(value), datetime.date):
return (("'" + str(value)) + "'")
else:
return super(MSSQLStrictCompiler, self).render_literal_value(value, type_)
|
'Prepare a quoted table and schema name.'
| def quote_schema(self, schema, force=None):
| result = '.'.join([self.quote(x, force) for x in schema.split('.')])
return result
|
'where appropriate, issue "select scope_identity()" in the same
statement.
Background on why "scope_identity()" is preferable to "@@identity":
http://msdn.microsoft.com/en-us/library/ms190315.aspx
Background on why we attempt to embed "scope_identity()" into the same
statement as the INSERT:
http://code.google.com/p/py... | def pre_exec(self):
| super(MSExecutionContext_pyodbc, self).pre_exec()
if (self._select_lastrowid and self.dialect.use_scope_identity and len(self.parameters[0])):
self._embedded_scope_identity = True
self.statement += '; select scope_identity()'
|
'Initialize a queue object with a given maximum size.
If `maxsize` is <= 0, the queue size is infinite.'
| def __init__(self, maxsize=0):
| self._init(maxsize)
self.mutex = threading.RLock()
self.not_empty = threading.Condition(self.mutex)
self.not_full = threading.Condition(self.mutex)
|
'Return the approximate size of the queue (not reliable!).'
| def qsize(self):
| self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
|
'Return True if the queue is empty, False otherwise (not
reliable!).'
| def empty(self):
| self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
|
'Return True if the queue is full, False otherwise (not
reliable!).'
| def full(self):
| self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
|
'Put an item into the queue.
If optional args `block` is True and `timeout` is None (the
default), block if necessary until a free slot is
available. If `timeout` is a positive number, it blocks at
most `timeout` seconds and raises the ``Full`` exception if no
free slot was available within that time. Otherwise (`bloc... | def put(self, item, block=True, timeout=None):
| self.not_full.acquire()
try:
if (not block):
if self._full():
raise Full
elif (timeout is None):
while self._full():
self.not_full.wait()
else:
if (timeout < 0):
raise ValueError("'timeout' must be ... |
'Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the ``Full`` exception.'
| def put_nowait(self, item):
| return self.put(item, False)
|
'Remove and return an item from the queue.
If optional args `block` is True and `timeout` is None (the
default), block if necessary until an item is available. If
`timeout` is a positive number, it blocks at most `timeout`
seconds and raises the ``Empty`` exception if no item was
available within that time. Otherwise ... | def get(self, block=True, timeout=None):
| self.not_empty.acquire()
try:
if (not block):
if self._empty():
raise Empty
elif (timeout is None):
while self._empty():
self.not_empty.wait()
else:
if (timeout < 0):
raise ValueError("'timeout' must ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.