--- /dev/null
+-- temporary notes --
+
+
+- make sure input() function in dogpile example works in py2
+- we want to get rid of any support for sets.Set entirely; check to see what
+impact this has
def get_column_default_string(self, column):
if (isinstance(column.server_default, schema.DefaultClause) and
- isinstance(column.server_default.arg, util.string_type)):
+ isinstance(column.server_default.arg, util.string_types)):
if isinstance(column.type, (sqltypes.Integer, sqltypes.Numeric)):
return self.sql_compiler.process(text(column.server_default.arg))
def process(value):
if isinstance(value, datetime.datetime):
return value.date()
- elif isinstance(value, util.string_type):
+ elif isinstance(value, util.string_types):
return datetime.date(*[
int(x or 0)
for x in self._reg.match(value).groups()
def process(value):
if isinstance(value, datetime.datetime):
return value.time()
- elif isinstance(value, util.string_type):
+ elif isinstance(value, util.string_types):
return datetime.time(*[
int(x or 0)
for x in self._reg.match(value).groups()])
# handle other included columns
if index.kwargs.get("mssql_include"):
inclusions = [index.table.c[col]
- if isinstance(col, util.string_type) else col
+ if isinstance(col, util.string_types) else col
for col in index.kwargs["mssql_include"]]
text += " INCLUDE (%s)" \
from ... import Table, MetaData, Column
from ...types import String, Unicode, Integer, TypeDecorator
from ... import cast
+from ... import util
ischema = MetaData()
impl = Unicode
def process_bind_param(self, value, dialect):
-# start Py2K
-# if isinstance(value, str):
-# value = value.decode(dialect.encoding)
-# end Py2K
+ if util.py2k and isinstance(value, util.binary_type):
+ value = value.decode(dialect.encoding)
return value
def bind_expression(self, bindvalue):
super_convert = super(SET, self).bind_processor(dialect)
def process(value):
- if value is None or isinstance(value, (int, str)):
+ if value is None or isinstance(value, util.int_types + util.string_types):
pass
else:
if None in value:
of a SELECT.
"""
- if isinstance(select._distinct, str):
+ if isinstance(select._distinct, util.string_types):
return select._distinct.upper() + " "
elif select._distinct:
return "DISTINCT "
k[len(self.dialect.name) + 1:].upper(),
v
)
- for k, v in list(table.kwargs.items())
+ for k, v in table.kwargs.items()
if k.startswith('%s_' % self.dialect.name)
)
for nope in ('auto_increment', 'data directory', 'index directory'):
options.pop(nope, None)
- for opt, val in list(options.items()):
+ for opt, val in options.items():
state.table_options['%s_%s' % (self.dialect.name, opt)] = val
def _parse_column(self, line, state):
_final = self.preparer.final_quote
- quotes = dict(list(zip(('iq', 'fq', 'esc_fq'),
+ quotes = dict(zip(('iq', 'fq', 'esc_fq'),
[re.escape(s) for s in
(self.preparer.initial_quote,
_final,
- self.preparer._escape_identifier(_final))])))
+ self.preparer._escape_identifier(_final))]))
self._pr_name = _pr_compile(
r'^CREATE (?:\w+ +)?TABLE +'
item = self.rowproxy[index]
if isinstance(item, _array):
item = item.tostring()
-# start Py2K
-# if self.charset and isinstance(item, str):
-# end Py2K
-# start Py3K
- if self.charset and isinstance(item, bytes):
-# end Py3K
+
+ if self.charset and isinstance(item, util.binary_type):
return item.decode(self.charset)
else:
return item
item = getattr(self.rowproxy, attr)
if isinstance(item, _array):
item = item.tostring()
-# start Py2K
-# if self.charset and isinstance(item, str):
-# end Py2K
-# start Py3K
- if self.charset and isinstance(item, bytes):
-# end Py3K
+ if self.charset and isinstance(item, util.binary_type):
return item.decode(self.charset)
else:
return item
def process(value):
if value is not None:
-# start Py2K
-# v = 0L
-# for i in map(ord, value):
-# v = v << 8 | i
-# end Py2K
-# start Py3K
v = 0
- for i in value:
+ for i in util.iterbytes(value):
v = v << 8 | i
-# end Py3K
return v
return value
return process
class MySQLDialect_oursql(MySQLDialect):
driver = 'oursql'
-# start Py2K
-# supports_unicode_binds = True
-# supports_unicode_statements = True
-# end Py2K
+
+ if util.py2k:
+ supports_unicode_binds = True
+ supports_unicode_statements = True
supports_native_decimal = True
connection.cursor().execute('BEGIN', plain_query=True)
def _xa_query(self, connection, query, xid):
-# start Py2K
-# arg = connection.connection._escape_string(xid)
-# end Py2K
-# start Py3K
- charset = self._connection_charset
- arg = connection.connection._escape_string(xid.encode(charset)).decode(charset)
-# end Py3K
+ if util.py2k:
+ arg = connection.connection._escape_string(xid)
+ else:
+ charset = self._connection_charset
+ arg = connection.connection._escape_string(xid.encode(charset)).decode(charset)
arg = "'%s'" % arg
connection.execution_options(_oursql_plain_query=True).execute(query % arg)
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
+from __future__ import with_statement
"""Defines :class:`.Connection` and :class:`.Engine`.
distilled_params = _distill_params(multiparams, params)
if distilled_params:
- keys = list(distilled_params[0].keys())
+ keys = list(distilled_params[0])
else:
keys = []
Compiled: _execute_compiled,
schema.SchemaItem: _execute_default,
schema.DDLElement: _execute_ddl,
- str: _execute_text
+ util.string_types[0]: _execute_text
}
def default_schema_name(self):
tables = list(metadata.tables.values())
collection = [t for t in sql_util.sort_tables(tables)
if self._can_create_table(t)]
- seq_coll = [s for s in list(metadata._sequences.values())
+ seq_coll = [s for s in metadata._sequences.values()
if s.column is None and self._can_create_sequence(s)]
metadata.dispatch.before_create(metadata, self.connection,
seq_coll = [
s
- for s in list(metadata._sequences.values())
+ for s in metadata._sequences.values()
if s.column is None and self._can_drop_sequence(s)
]
# *not* the FLOAT type however.
supports_native_decimal = False
-# start Py3K
- supports_unicode_statements = True
- supports_unicode_binds = True
- returns_unicode_strings = True
- description_encoding = None
-# end Py3K
-# start Py2K
-# supports_unicode_statements = False
-# supports_unicode_binds = False
-# returns_unicode_strings = False
-# description_encoding = 'use_encoding'
-# end Py2K
+ if util.py3k:
+ supports_unicode_statements = True
+ supports_unicode_binds = True
+ returns_unicode_strings = True
+ description_encoding = None
+ else:
+ supports_unicode_statements = False
+ supports_unicode_binds = False
+ returns_unicode_strings = False
+ description_encoding = 'use_encoding'
name = 'default'
return None
def _check_unicode_returns(self, connection):
-# start Py2K
-# if self.supports_unicode_statements:
-# cast_to = unicode
-# else:
-# cast_to = str
-# end Py2K
-# start Py3K
- cast_to = str
-# end Py3K
+ if util.py2k and not self.supports_unicode_statements:
+ cast_to = util.binary_type
+ else:
+ cast_to = util.text_type
def check_unicode(formatstr, type_):
cursor = connection.connection.cursor()
cursor.execute(
cast_to(
expression.select(
- [expression.cast(
- expression.literal_column(
+ [expression.cast(
+ expression.literal_column(
"'test %s returns'" % formatstr),
type_)
]).compile(dialect=self)
)
row = cursor.fetchone()
- return isinstance(row[0], str)
+ return isinstance(row[0], util.string_types)
except self.dbapi.Error as de:
util.warn("Exception attempting to "
"detect unicode returns: %r" % de)
self.execution_options.update(connection._execution_options)
if not dialect.supports_unicode_statements:
- self.unicode_statement = str(compiled)
+ self.unicode_statement = util.text_type(compiled)
self.statement = dialect._encoder(self.unicode_statement)[0]
else:
- self.statement = self.unicode_statement = str(compiled)
+ self.statement = self.unicode_statement = util.text_type(compiled)
self.cursor = self.create_cursor()
self.compiled_parameters = []
self.result_map = compiled.result_map
- self.unicode_statement = str(compiled)
+ self.unicode_statement = util.text_type(compiled)
if not dialect.supports_unicode_statements:
self.statement = self.unicode_statement.encode(
self.dialect.encoding)
self.executemany = len(parameters) > 1
if not dialect.supports_unicode_statements and \
- isinstance(statement, str):
+ isinstance(statement, util.text_type):
self.unicode_statement = statement
self.statement = dialect._encoder(statement)[0]
else:
"""
conn = self.root_connection
- if isinstance(stmt, str) and \
- not self.dialect.supports_unicode_statements:
+ if isinstance(stmt, util.text_type) and \
+ not self.dialect.supports_unicode_statements:
stmt = self.dialect._encoder(stmt)[0]
if self.dialect.positional:
if not _registrars[k]:
del _registrars[k]
-
-class Events(object, metaclass=_EventMeta):
+class Events(object): #util.with_metaclass(_EventMeta, object)):
"""Define event listening functions for a particular target type."""
+ __metaclass__ = _EventMeta
+
@classmethod
def _accept_with(cls, target):
# Mapper, ClassManager, Session override this to
nullable=self.nullable,
quote=self.quote,
_proxies=[self], *fk)
- except TypeError as e:
-# start Py3K
- raise TypeError(
- "Could not create a copy of this %r object. "
- "Ensure the class includes a _constructor() "
- "attribute or method which accepts the "
- "standard Column constructor arguments, or "
- "references the Column class itself." % self.__class__) from e
-# end Py3K
-# start Py2K
-# raise TypeError(
-# "Could not create a copy of this %r object. "
-# "Ensure the class includes a _constructor() "
-# "attribute or method which accepts the "
-# "standard Column constructor arguments, or "
-# "references the Column class itself. "
-# "Original error: %s" % (self.__class__, e))
-# end Py2K
+ except TypeError:
+ util.raise_from_cause(
+ TypeError(
+ "Could not create a copy of this %r object. "
+ "Ensure the class includes a _constructor() "
+ "attribute or method which accepts the "
+ "standard Column constructor arguments, or "
+ "references the Column class itself." % self.__class__)
+ )
c.table = selectable
selectable._columns.add(c)
cls._compiler_dispatch = _compiler_dispatch
-class Visitable(object, metaclass=VisitableType):
+class Visitable(util.with_metaclass(VisitableType, object)):
"""Base class for visitable objects, applies the
``VisitableType`` metaclass.
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from .compat import callable, cmp, reduce, \
- threading, py3k, py3k_warning, jython, pypy, cpython, win32, set_types, \
+ threading, py3k, py2k, jython, pypy, cpython, win32, \
pickle, dottedgetter, parse_qsl, namedtuple, next, WeakSet, reraise, \
- raise_from_cause, text_type, string_type, binary_type, quote_plus
+ raise_from_cause, text_type, string_types, int_types, binary_type, \
+ quote_plus, with_metaclass
from ._collections import KeyedTuple, ImmutableContainer, immutabledict, \
Properties, OrderedProperties, ImmutableProperties, OrderedDict, \
import dummy_threading as threading
py32 = sys.version_info >= (3, 2)
-py3k_warning = getattr(sys, 'py3kwarning', False) or sys.version_info >= (3, 0)
py3k = sys.version_info >= (3, 0)
+py2k = not py3k
jython = sys.platform.startswith('java')
pypy = hasattr(sys, 'pypy_version_info')
win32 = sys.platform.startswith('win')
cpython = not pypy and not jython # TODO: something better for this ?
-if py3k:
- set_types = set
-else:
- # 2.6 deprecates sets.Set, but we still need to be able to detect them
- # in user code and as return values from DB-APIs
- ignore = ('ignore', None, DeprecationWarning, None, 0)
- import warnings
- try:
- warnings.filters.insert(0, ignore)
- except Exception:
- import sets
- else:
- import sets
- warnings.filters.remove(ignore)
-
- set_types = set, sets.Set
if sys.version_info < (2, 6):
def next(iter):
except ImportError:
import pickle
-from urllib.parse import parse_qsl
if py3k:
from inspect import getfullargspec as inspect_getfullargspec
- from urllib.parse import quote_plus, unquote_plus
+ from urllib.parse import quote_plus, unquote_plus, parse_qsl
string_types = str,
binary_type = bytes
text_type = str
+ int_types = int,
+ iterbytes = iter
else:
from inspect import getargspec as inspect_getfullargspec
from urllib import quote_plus, unquote_plus
+ from urlparse import parse_qsl
string_types = basestring,
binary_type = str
text_type = unicode
+ int_types = int, long
+ def iterbytes(buf):
+ return (ord(byte) for byte in buf)
-if py3k_warning:
+if py3k:
# they're bringing it back in 3.2. brilliant !
def callable(fn):
return hasattr(fn, '__call__')
raise value.with_traceback(tb)
raise value
- def raise_from_cause(exception, exc_info):
+ def raise_from_cause(exception, exc_info=None):
+ if exc_info is None:
+ exc_info = sys.exc_info()
exc_type, exc_value, exc_tb = exc_info
reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
else:
exec("def reraise(tp, value, tb=None, cause=None):\n"
" raise tp, value, tb\n")
- def raise_from_cause(exception, exc_info):
+ def raise_from_cause(exception, exc_info=None):
# not as nice as that of Py3K, but at least preserves
# the code line where the issue occurred
+ if exc_info is None:
+ exc_info = sys.exc_info()
exc_type, exc_value, exc_tb = exc_info
reraise(type(exception), exception, tb=exc_tb)
+def with_metaclass(meta, *bases):
+ """Create a base class with a metaclass."""
-
+ return meta("MetaBase", bases, {})
import sys
import types
import warnings
-from .compat import set_types, threading, \
- callable, inspect_getfullargspec
+from .compat import threading, \
+ callable, inspect_getfullargspec, py3k
from functools import update_wrapper
from .. import exc
import hashlib
else:
self_arg = None
-# start Py3K
- apply_pos = inspect.formatargspec(spec[0], spec[1],
- spec[2], None, spec[4])
- num_defaults = 0
- if spec[3]:
- num_defaults += len(spec[3])
- if spec[4]:
- num_defaults += len(spec[4])
- name_args = spec[0] + spec[4]
-# end Py3K
-# start Py2K
-# apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2])
-# num_defaults = 0
-# if spec[3]:
-# num_defaults += len(spec[3])
-# name_args = spec[0]
-# end Py2K
+ if py3k:
+ apply_pos = inspect.formatargspec(spec[0], spec[1],
+ spec[2], None, spec[4])
+ num_defaults = 0
+ if spec[3]:
+ num_defaults += len(spec[3])
+ if spec[4]:
+ num_defaults += len(spec[4])
+ name_args = spec[0] + spec[4]
+ else:
+ apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2])
+ num_defaults = 0
+ if spec[3]:
+ num_defaults += len(spec[3])
+ name_args = spec[0]
if num_defaults:
defaulted_vals = name_args[0 - num_defaults:]
if hasattr(specimen, '__emulates__'):
# canonicalize set vs sets.Set to a standard: the builtin set
if (specimen.__emulates__ is not None and
- issubclass(specimen.__emulates__, set_types)):
+ issubclass(specimen.__emulates__, set)):
return set
else:
return specimen.__emulates__
isa = isinstance(specimen, type) and issubclass or isinstance
if isa(specimen, list):
return list
- elif isa(specimen, set_types):
+ elif isa(specimen, set):
return set
elif isa(specimen, dict):
return dict