produces BLOB, BYTEA, or a similar "long binary" type.
New base BINARY and VARBINARY
types have been added to access these MySQL/MS-SQL specific
types in an agnostic way [ticket:1664].
FLOAT, DECIMAL don't generate any length or scale unless
specified.
+ - types.Binary is renamed to types.LargeBinary, it only
+ produces BLOB, BYTEA, or a similar "long binary" type.
+ New base BINARY and VARBINARY
+ types have been added to access these MySQL/MS-SQL specific
+ types in an agnostic way [ticket:1664].
+
- String/Text/Unicode types now skip the unicode() check
on each result column value if the dialect has
detected the DBAPI as returning Python unicode objects
type is emitted in ``CREATE TABLE``, such as ``VARCHAR`` see `SQL
Standard Types`_ and the other sections of this chapter.
-.. autoclass:: Binary
- :show-inheritance:
-
.. autoclass:: Boolean
:show-inheritance:
.. autoclass:: Interval
:show-inheritance:
+.. autoclass:: LargeBinary
+ :show-inheritance:
+
.. autoclass:: Numeric
:show-inheritance:
:members:
name when ``CREATE TABLE`` is issued. Some types may not be supported
on all databases.
+.. autoclass:: BINARY
+ :show-inheritance:
+
.. autoclass:: BLOB
:show-inheritance:
.. autoclass:: TIMESTAMP
:show-inheritance:
+.. autoclass:: VARBINARY
+ :show-inheritance:
+
.. autoclass:: VARCHAR
:show-inheritance:
INTEGER,
Integer,
Interval,
+ LargeBinary,
NCHAR,
NVARCHAR,
NUMERIC,
def get_col_spec(self):
return "TEXT" + (self.length and ("(%d)" % self.length) or "")
-class AcBinary(types.Binary):
+class AcBinary(types.LargeBinary):
def get_col_spec(self):
return "BINARY"
types.DateTime : AcDateTime,
types.Date : AcDate,
types.String : AcString,
- types.Binary : AcBinary,
+ types.LargeBinary : AcBinary,
types.Boolean : AcBoolean,
types.Text : AcText,
types.CHAR: AcChar,
7 : sqltypes.DATE, # DATE
8 : sqltypes.Numeric, # MONEY
10 : sqltypes.DATETIME, # DATETIME
- 11 : sqltypes.Binary, # BYTE
+ 11 : sqltypes.LargeBinary, # BYTE
12 : sqltypes.TEXT, # TEXT
13 : sqltypes.VARCHAR, # VARCHAR
15 : sqltypes.NCHAR, # NCHAR
def visit_TIME(self, type_):
return "DATETIME HOUR TO SECOND"
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return "BYTE"
def visit_boolean(self, type_):
return process
-class MaxBlob(sqltypes.Binary):
+class MaxBlob(sqltypes.LargeBinary):
def bind_processor(self, dialect):
def process(value):
if value is None:
def visit_string(self, type_):
return self._string_spec("VARCHAR", type_)
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return "LONG BYTE"
def visit_numeric(self, type_):
sqltypes.Time: MaxTime,
sqltypes.String: MaxString,
sqltypes.Unicode:MaxUnicode,
- sqltypes.Binary: MaxBlob,
+ sqltypes.LargeBinary: MaxBlob,
sqltypes.Text: MaxText,
sqltypes.CHAR: MaxChar,
sqltypes.TIMESTAMP: MaxTimestamp,
from sqlalchemy import types as sqltypes
from decimal import Decimal as _python_Decimal
from sqlalchemy.types import INTEGER, BIGINT, SMALLINT, DECIMAL, NUMERIC, \
- FLOAT, TIMESTAMP, DATETIME, DATE
+ FLOAT, TIMESTAMP, DATETIME, DATE, BINARY,\
+ VARBINARY, BLOB
from sqlalchemy.dialects.mssql import information_schema as ischema
_StringType.__init__(self, collation)
sqltypes.NCHAR.__init__(self, *args, **kw)
-class BINARY(sqltypes.Binary):
- __visit_name__ = 'BINARY'
-
-class VARBINARY(sqltypes.Binary):
- __visit_name__ = 'VARBINARY'
-
-class IMAGE(sqltypes.Binary):
+class IMAGE(sqltypes.LargeBinary):
__visit_name__ = 'IMAGE'
class BIT(sqltypes.TypeEngine):
else:
return self.visit_TIME(type_)
- def visit_binary(self, type_):
- if type_.length:
- return self.visit_BINARY(type_)
- else:
- return self.visit_IMAGE(type_)
-
- def visit_BINARY(self, type_):
- if type_.length:
- return "BINARY(%s)" % type_.length
- else:
- return "BINARY"
+ def visit_large_binary(self, type_):
+ return self.visit_IMAGE(type_)
def visit_IMAGE(self, type_):
return "IMAGE"
- def visit_VARBINARY(self, type_):
- if type_.length:
- return "VARBINARY(%s)" % type_.length
- else:
- return "VARBINARY"
-
def visit_boolean(self, type_):
return self.visit_BIT(type_)
coltype = self.ischema_names.get(type, None)
kwargs = {}
- if coltype in (MSString, MSChar, MSNVarchar, MSNChar, MSText, MSNText, MSBinary, MSVarBinary, sqltypes.Binary):
+ if coltype in (MSString, MSChar, MSNVarchar, MSNChar, MSText, MSNText, MSBinary, MSVarBinary, sqltypes.LargeBinary):
kwargs['length'] = charlen
if collation:
kwargs['collation'] = collation
from sqlalchemy.engine import base as engine_base, default
from sqlalchemy import types as sqltypes
-from sqlalchemy.types import DATE, DATETIME, BOOLEAN, TIME
+from sqlalchemy.types import DATE, DATETIME, BOOLEAN, TIME, \
+ BLOB, BINARY, VARBINARY
RESERVED_WORDS = set(
['accessible', 'add', 'all', 'alter', 'analyze','and', 'as', 'asc',
', '.join(['%s=%r' % (k, params[k]) for k in params]))
-class _BinaryType(sqltypes.Binary):
- """Base for MySQL binary types."""
-
- pass
-
class NUMERIC(_NumericType, sqltypes.NUMERIC):
"""MySQL NUMERIC type."""
-class VARBINARY(_BinaryType):
- """MySQL VARBINARY type, for variable length binary data."""
-
- __visit_name__ = 'VARBINARY'
-
- def __init__(self, length=None, **kw):
- """Construct a VARBINARY. Arguments are:
-
- :param length: Maximum data length, in characters.
-
- """
- super(VARBINARY, self).__init__(length=length, **kw)
-
-class BINARY(_BinaryType):
- """MySQL BINARY type, for fixed length binary data"""
-
- __visit_name__ = 'BINARY'
-
- def __init__(self, length=None, **kw):
- """Construct a BINARY.
-
- This is a fixed length type, and short values will be right-padded
- with a server-version-specific pad value.
-
- :param length: Maximum data length, in bytes.
-
- """
- super(BINARY, self).__init__(length=length, **kw)
-class BLOB(_BinaryType, sqltypes.BLOB):
- """MySQL BLOB type, for binary data up to 2^16 bytes"""
-
- __visit_name__ = 'BLOB'
-
- def __init__(self, length=None, **kw):
- """Construct a BLOB. Arguments are:
-
- :param length: Optional, if provided the server may optimize storage
- by substituting the smallest TEXT type sufficient to store
- ``length`` characters.
-
- """
- super(BLOB, self).__init__(length=length, **kw)
-
-
-class TINYBLOB(_BinaryType):
+class TINYBLOB(sqltypes._Binary):
"""MySQL TINYBLOB type, for binary data up to 2^8 bytes."""
__visit_name__ = 'TINYBLOB'
-class MEDIUMBLOB(_BinaryType):
+class MEDIUMBLOB(sqltypes._Binary):
"""MySQL MEDIUMBLOB type, for binary data up to 2^24 bytes."""
__visit_name__ = 'MEDIUMBLOB'
-class LONGBLOB(_BinaryType):
+class LONGBLOB(sqltypes._Binary):
"""MySQL LONGBLOB type, for binary data up to 2^32 bytes."""
__visit_name__ = 'LONGBLOB'
colspecs = {
sqltypes.Numeric: NUMERIC,
sqltypes.Float: FLOAT,
- sqltypes.Binary: _BinaryType,
sqltypes.Time: _MSTime,
sqltypes.Enum: ENUM,
}
return 'CHAR(%s)' % type_.length
else:
return 'CHAR'
- elif isinstance(type_, sqltypes.Binary):
+ elif isinstance(type_, sqltypes._Binary):
return 'BINARY'
elif isinstance(type_, NUMERIC):
return self.dialect.type_compiler.process(type_).replace('NUMERIC', 'DECIMAL')
if c is not None])
def _mysql_type(self, type_):
- return isinstance(type_, (_StringType, _NumericType, _BinaryType))
+ return isinstance(type_, (_StringType, _NumericType))
def visit_NUMERIC(self, type_):
if type_.precision is None:
return self._extend_string(type_, {'national':True}, "CHAR")
def visit_VARBINARY(self, type_):
- if type_.length:
- return "VARBINARY(%d)" % type_.length
- else:
- return self.visit_BLOB(type_)
+ return "VARBINARY(%d)" % type_.length
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return self.visit_BLOB(type_)
def visit_enum(self, type_):
else:
return self.visit_ENUM(type_)
- def visit_BINARY(self, type_):
- if type_.length:
- return "BINARY(%d)" % type_.length
- else:
- return "BINARY"
-
def visit_BLOB(self, type_):
if type_.length:
return "BLOB(%d)" % type_.length
RESERVED_WORDS = set('''SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR DECIMAL UNION PUBLIC AND START UID COMMENT'''.split())
-class RAW(sqltypes.Binary):
+class RAW(sqltypes.LargeBinary):
pass
OracleRaw = RAW
super(DOUBLE_PRECISION, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal)
-class BFILE(sqltypes.Binary):
+class BFILE(sqltypes.LargeBinary):
__visit_name__ = 'BFILE'
class LONG(sqltypes.Text):
def visit_unicode_text(self, type_):
return self.visit_NCLOB(type_)
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return self.visit_BLOB(type_)
def visit_big_integer(self, type_):
return val
return to_int
-class _OracleBinary(_LOBMixin, sqltypes.Binary):
+class _OracleBinary(_LOBMixin, sqltypes.LargeBinary):
def get_dbapi_type(self, dbapi):
return dbapi.BLOB
colspecs = {
sqltypes.Date : _OracleDate,
- sqltypes.Binary : _OracleBinary,
+ sqltypes.LargeBinary : _OracleBinary,
sqltypes.Boolean : oracle._OracleBoolean,
sqltypes.Interval : _OracleInterval,
oracle.INTERVAL : _OracleInterval,
class REAL(sqltypes.Float):
__visit_name__ = "REAL"
-class BYTEA(sqltypes.Binary):
+class BYTEA(sqltypes.LargeBinary):
__visit_name__ = 'BYTEA'
class DOUBLE_PRECISION(sqltypes.Float):
def visit_UUID(self, type_):
return "UUID"
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return self.visit_BYTEA(type_)
def visit_BYTEA(self, type_):
return text
class SQLiteTypeCompiler(compiler.GenericTypeCompiler):
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return self.visit_BLOB(type_)
class SQLiteIdentifierPreparer(compiler.IdentifierPreparer):
])
-class SybaseImage(sqltypes.Binary):
+class SybaseImage(sqltypes.LargeBinary):
__visit_name__ = 'IMAGE'
class SybaseBit(sqltypes.TypeEngine):
return process
class SybaseTypeCompiler(compiler.GenericTypeCompiler):
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return self.visit_IMAGE(type_)
def visit_boolean(self, type_):
return "UNIQUEIDENTIFIER"
colspecs = {
- sqltypes.Binary : SybaseImage,
+ sqltypes.LargeBinary : SybaseImage,
sqltypes.Boolean : SybaseBoolean,
}
'numeric' : sqltypes.NUMERIC,
'float' : sqltypes.FLOAT,
'double' : sqltypes.Numeric,
- 'binary' : sqltypes.Binary,
- 'long binary' : sqltypes.Binary,
- 'varbinary' : sqltypes.Binary,
+ 'binary' : sqltypes.LargeBinary,
+ 'long binary' : sqltypes.LargeBinary,
+ 'varbinary' : sqltypes.LargeBinary,
'bit': SybaseBit,
'image' : SybaseImage,
'timestamp': sqltypes.TIMESTAMP,
arguments and flags to those types.
d. the visit_lowercase methods are overridden to provide an interpretation of a generic
- type. E.g. visit_binary() might be overridden to say "return self.visit_BIT(type_)".
+ type. E.g. visit_large_binary() might be overridden to say "return self.visit_BIT(type_)".
e. visit_lowercase methods should *never* render strings directly - it should always
be via calling a visit_UPPERCASE() method.
def visit_BLOB(self, type_):
return "BLOB"
+
+ def visit_BINARY(self, type_):
+ return "BINARY" + (type_.length and "(%d)" % type_.length or "")
+
+ def visit_VARBINARY(self, type_):
+ return "VARBINARY" + (type_.length and "(%d)" % type_.length or "")
def visit_BOOLEAN(self, type_):
return "BOOLEAN"
def visit_TEXT(self, type_):
return "TEXT"
- def visit_binary(self, type_):
+ def visit_large_binary(self, type_):
return self.visit_BLOB(type_)
def visit_boolean(self, type_):
'FLOAT', 'NUMERIC', 'DECIMAL', 'TIMESTAMP', 'DATETIME', 'CLOB',
'BLOB', 'BOOLEAN', 'SMALLINT', 'INTEGER', 'DATE', 'TIME',
'String', 'Integer', 'SmallInteger', 'BigInteger', 'Numeric',
- 'Float', 'DateTime', 'Date', 'Time', 'Binary', 'Boolean',
+ 'Float', 'DateTime', 'Date', 'Time', 'LargeBinary', 'Binary', 'Boolean',
'Unicode', 'MutableType', 'Concatenable', 'UnicodeText',
'PickleType', 'Interval', 'type_map', 'Enum' ]
def get_dbapi_type(self, dbapi):
return dbapi.DATETIME
-
-class Binary(TypeEngine):
- """A type for binary byte data.
-
- The Binary type generates BLOB or BYTEA when tables are created,
- and also converts incoming values using the ``Binary`` callable
- provided by each DB-API.
-
- """
-
- __visit_name__ = 'binary'
+class _Binary(TypeEngine):
+ """Define base behavior for binary types."""
def __init__(self, length=None):
- """
- Construct a Binary type.
-
- :param length: optional, a length for the column for use in
- DDL statements. May be safely omitted if no ``CREATE
- TABLE`` will be issued. Certain databases may require a
- *length* for use in DDL, and will raise an exception when
- the ``CREATE TABLE`` DDL is issued.
-
- """
self.length = length
# Python 3 - sqlite3 doesn't need the `Binary` conversion
def get_dbapi_type(self, dbapi):
return dbapi.BINARY
+
+class LargeBinary(_Binary):
+ """A type for large binary byte data.
+
+ The Binary type generates BLOB or BYTEA when tables are created,
+ and also converts incoming values using the ``Binary`` callable
+ provided by each DB-API.
+
+ """
+
+ __visit_name__ = 'large_binary'
+
+ def __init__(self, length=None):
+ """
+ Construct a LargeBinary type.
+
+ :param length: optional, a length for the column for use in
+ DDL statements, for those BLOB types that accept a length
+ (i.e. MySQL). It does *not* produce a small BINARY/VARBINARY
+ type - use the BINARY/VARBINARY types specifically for those.
+ May be safely omitted if no ``CREATE
+ TABLE`` will be issued. Certain databases may require a
+ *length* for use in DDL, and will raise an exception when
+ the ``CREATE TABLE`` DDL is issued.
+
+ """
+ _Binary.__init__(self, length=length)
+
+class Binary(LargeBinary):
+ """Deprecated. Renamed to LargeBinary."""
+
+ def __init__(self, *arg, **kw):
+ util.warn_deprecated("The Binary type has been renamed to LargeBinary.")
+ LargeBinary.__init__(self, *arg, **kw)
class SchemaType(object):
"""Mark a type as possibly requiring schema-level DDL for usage.
"""
- impl = Binary
+ impl = LargeBinary
def __init__(self, protocol=pickle.HIGHEST_PROTOCOL, pickler=None, mutable=True, comparator=None):
"""
__visit_name__ = 'NCHAR'
-class BLOB(Binary):
+class BLOB(LargeBinary):
"""The SQL BLOB type."""
__visit_name__ = 'BLOB'
+class BINARY(_Binary):
+ """The SQL BINARY type."""
+
+ __visit_name__ = 'BINARY'
+
+class VARBINARY(_Binary):
+ """The SQL VARBINARY type."""
+
+ __visit_name__ = 'VARBINARY'
+
class BOOLEAN(Boolean):
"""The SQL BOOLEAN type."""
( mysql.MSSmallInteger(4), mysql.MSSmallInteger(4), ),
( mysql.MSMediumInteger(), mysql.MSMediumInteger(), ),
( mysql.MSMediumInteger(8), mysql.MSMediumInteger(8), ),
- ( Binary(3), mysql.TINYBLOB(), ),
- ( Binary(), mysql.BLOB() ),
+ ( LargeBinary(3), mysql.TINYBLOB(), ),
+ ( LargeBinary(), mysql.BLOB() ),
( mysql.MSBinary(3), mysql.MSBinary(3), ),
( mysql.MSVarBinary(3),),
- ( mysql.MSVarBinary(), mysql.MSBlob()),
( mysql.MSTinyBlob(),),
( mysql.MSBlob(),),
( mysql.MSBlob(1234), mysql.MSBlob()),
(m.MSNChar, "CAST(t.col AS CHAR)"),
(m.MSNVarChar, "CAST(t.col AS CHAR)"),
- (Binary, "CAST(t.col AS BINARY)"),
+ (LargeBinary, "CAST(t.col AS BINARY)"),
(BLOB, "CAST(t.col AS BINARY)"),
(m.MSBlob, "CAST(t.col AS BINARY)"),
(m.MSBlob(32), "CAST(t.col AS BINARY)"),
sa.ForeignKey('engine_users.user_id')),
Column('test6', sa.Date, nullable=False),
Column('test7', sa.Text),
- Column('test8', sa.Binary),
+ Column('test8', sa.LargeBinary),
Column('test_passivedefault2', sa.Integer, server_default='5'),
- Column('test9', sa.Binary(100)),
+ Column('test9', sa.LargeBinary(100)),
Column('test10', sa.Numeric(10, 2)),
test_needs_fk=True,
)
parent_user_id,
Column('test6', sa.Date, nullable=False),
Column('test7', sa.Text),
- Column('test8', sa.Binary),
+ Column('test8', sa.LargeBinary),
Column('test_passivedefault2', sa.Integer, server_default='5'),
- Column('test9', sa.Binary(100)),
+ Column('test9', sa.LargeBinary(100)),
Column('test10', sa.Numeric(10, 2)),
schema=schema,
test_needs_fk=True,
).intersection(ctype_def.__mro__)
.intersection([sql_types.Integer, sql_types.Numeric,
sql_types.DateTime, sql_types.Date, sql_types.Time,
- sql_types.String, sql_types.Binary])
+ sql_types.String, sql_types._Binary])
) > 0
,("%s(%s), %s(%s)" % (col.name, col.type, cols[i]['name'],
ctype)))
Column('last_updated', DateTime, default=lambda:datetime.now(),
onupdate=lambda:datetime.now()),
Column('name', String(128)),
- Column('data', Binary),
+ Column('data', LargeBinary),
Column('size', Integer, default=0),
)
def define_tables(cls, metadata):
Table('t1', metadata,
Column('id', sa.Integer, primary_key=True, test_needs_autoincrement=True),
- Column('data', sa.Binary),
+ Column('data', sa.LargeBinary),
)
@classmethod
(Integer(), Integer(), True),
(Text(), String(), True),
(Text(), Unicode(), True),
- (Binary(), Integer(), False),
- (Binary(), PickleType(), True),
- (PickleType(), Binary(), True),
+ (LargeBinary(), Integer(), False),
+ (LargeBinary(), PickleType(), True),
+ (PickleType(), LargeBinary(), True),
(PickleType(), PickleType(), True),
]:
eq_(t1._compare_type_affinity(t2), comp, "%s %s" % (t1, t2))
binary_table = Table('binary_table', MetaData(testing.db),
Column('primary_id', Integer, Sequence('binary_id_seq', optional=True), primary_key=True),
- Column('data', Binary),
- Column('data_slice', Binary(100)),
+ Column('data', LargeBinary),
+ Column('data_slice', LargeBinary(100)),
Column('misc', String(30)),
# construct PickleType with non-native pickle module, since cPickle uses relative module
# loading and confuses this test's parent package 'sql' with the 'sqlalchemy.sql' package relative
binary_table.select(order_by=binary_table.c.primary_id),
text(
"select * from binary_table order by binary_table.primary_id",
- typemap={'pickled':PickleType, 'mypickle':MyPickleType, 'data':Binary, 'data_slice':Binary},
+ typemap={'pickled':PickleType, 'mypickle':MyPickleType, 'data':LargeBinary, 'data_slice':LargeBinary},
bind=testing.db)
):
l = stmt.execute().fetchall()