class documentation

class TypeEngine(Traversible):

Known subclasses: sqlalchemy.dialects.mssql.MONEY, sqlalchemy.dialects.mssql.SMALLMONEY, sqlalchemy.dialects.mssql.SQL_VARIANT, sqlalchemy.dialects.mssql.UNIQUEIDENTIFIER, sqlalchemy.dialects.mysql.types.BIT, sqlalchemy.dialects.mysql.types.YEAR, sqlalchemy.dialects.postgresql.DATERANGE, sqlalchemy.dialects.postgresql.hstore.HSTORE, sqlalchemy.dialects.postgresql.ranges.INT4RANGE, sqlalchemy.dialects.postgresql.ranges.INT8RANGE, sqlalchemy.dialects.postgresql.ranges.NUMRANGE, sqlalchemy.dialects.postgresql.TSRANGE, sqlalchemy.dialects.postgresql.TSTZRANGE, sqlalchemy.sql.sqltypes.NullType, sqlalchemy.types.ARRAY, sqlalchemy.types.Boolean, sqlalchemy.types.Date, sqlalchemy.types.DateTime, sqlalchemy.types.Integer, sqlalchemy.types.JSON, sqlalchemy.types.JSON.JSONElementType, sqlalchemy.types.Numeric, sqlalchemy.types.String, sqlalchemy.types.Time, sqlalchemy.types.TypeDecorator, sqlalchemy.databases.sybase.UNIQUEIDENTIFIER, sqlalchemy.dialects.sybase.BIT, sqlalchemy.dialects.sybase.MONEY, sqlalchemy.dialects.sybase.SMALLMONEY, sqlalchemy.sql.sqltypes._AbstractInterval, sqlalchemy.sql.sqltypes._Binary, sqlalchemy.sql.sqltypes.TableValueType, sqlalchemy.types.TupleType

View In Hierarchy

The ultimate base class for all SQL datatypes.

Common subclasses of .TypeEngine include .String, .Integer, and .Boolean.

For an overview of the SQLAlchemy typing system, see :ref:`types_toplevel`.

Class ​Comparator Base class for custom comparison operations defined at the type level. See .TypeEngine.comparator_factory.
Method adapt Produce an "adapted" form of this type, given an "impl" class to work with.
Method as​_generic Return an instance of the generic type corresponding to this type using heuristic rule. The method may be overridden if this heuristic rule is not sufficient.
Method bind​_expression Given a bind value (i.e. a .BindParameter instance), return a SQL expression in its place.
Method bind​_processor Return a conversion function for processing bind values.
Method coerce​_compared​_value Suggest a type for a 'coerced' Python value in an expression.
Method column​_expression Given a SELECT column expression, return a wrapping SQL expression.
Method compare​_against​_backend Compare this type against the given backend type.
Method compare​_values Compare two values for equality.
Method compile Produce a string-compiled form of this .TypeEngine.
Method dialect​_impl Return a dialect-specific implementation for this .TypeEngine.
Method evaluates​_none Return a copy of this type which has the .should_evaluate_none flag set to True.
Method get​_dbapi​_type Return the corresponding type object from the underlying DB-API, if any.
Method literal​_processor Return a conversion function for processing literal values that are to be rendered directly without using binds.
Method result​_processor Return a conversion function for processing result row values.
Method with​_variant Produce a new type object that will utilize the given type when applied to the dialect of the given name.
Class Variable hashable Flag, if False, means values from this type aren't hashable.
Class Variable should​_evaluate​_none If True, the Python constant None is considered to be handled explicitly by this type.
Class Variable sort​_key​_function A sorting function that can be passed as the key to sorted.
Static Method ​_to​_instance Undocumented
Method __repr__ Undocumented
Method __str__ Undocumented
Method ​_cached​_bind​_processor Return a dialect-specific bind processor for this type.
Method ​_cached​_custom​_processor Undocumented
Method ​_cached​_literal​_processor Return a dialect-specific literal processor for this type.
Method ​_cached​_result​_processor Return a dialect-specific result processor for this type.
Method ​_compare​_type​_affinity Undocumented
Method ​_default​_dialect Undocumented
Method ​_dialect​_info Return a dialect-specific registry which caches a dialect-specific implementation, bind processing function, and one or more result processing functions.
Method ​_gen​_dialect​_impl Undocumented
Method ​_resolve​_for​_literal adjust this type given a literal Python value that will be stored in a bound parameter.
Method ​_unwrapped​_dialect​_impl Return the 'unwrapped' dialect impl for this type.
Method copy Undocumented
Method copy​_value Undocumented
Class Variable ​_is​_array Undocumented
Class Variable ​_is​_table​_value Undocumented
Class Variable ​_is​_tuple​_type Undocumented
Class Variable ​_is​_type​_decorator Undocumented
Class Variable ​_isnull Undocumented
Class Variable ​_sqla​_type Undocumented
Property ​_generic​_type​_affinity Undocumented
Property ​_has​_bind​_expression memoized boolean, check if bind_expression is implemented.
Property ​_has​_column​_expression memoized boolean, check if column_expression is implemented.
Property ​_static​_cache​_key Undocumented
Property ​_type​_affinity Return a rudimental 'affinity' value expressing the general class of type.
Property python​_type Return the Python type object expected to be returned by instances of this type, if known.

Inherited from Traversible:

Method get​_children Return immediate child .visitors.Traversible elements of this .visitors.Traversible.
Method __class​_getitem__ Undocumented
def adapt(self, cls, **kw):

Produce an "adapted" form of this type, given an "impl" class to work with.

This method is used internally to associate generic types with "implementation" types that are specific to a particular dialect.

def as_generic(self, allow_nulltype=False):

Return an instance of the generic type corresponding to this type using heuristic rule. The method may be overridden if this heuristic rule is not sufficient.

>>> from sqlalchemy.dialects.mysql import INTEGER
>>> INTEGER(display_width=4).as_generic()
Integer()
>>> from sqlalchemy.dialects.mysql import NVARCHAR
>>> NVARCHAR(length=100).as_generic()
Unicode(length=100)
New in version 1.4.0b2.

See Also

:ref:`metadata_reflection_dbagnostic_types` - describes the use of _types.TypeEngine.as_generic in conjunction with the _sql.DDLEvents.column_reflect event, which is its intended use.

def bind_expression(self, bindvalue):

Given a bind value (i.e. a .BindParameter instance), return a SQL expression in its place.

This is typically a SQL function that wraps the existing bound parameter within the statement. It is used for special data types that require literals being wrapped in some special database function in order to coerce an application-level value into a database-specific format. It is the SQL analogue of the .TypeEngine.bind_processor method.

This method is called during the SQL compilation phase of a statement, when rendering a SQL string. It is not called against specific values.

Note that this method, when implemented, should always return the exact same structure, without any conditional logic, as it may be used in an executemany() call against an arbitrary number of bound parameter sets.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.bind_expression method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.bind_expression, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.bind_expression.

def bind_processor(self, dialect):

Return a conversion function for processing bind values.

Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API.

If processing is not necessary, the method should return None.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.bind_processor method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.bind_processor, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_bind_param.

Parameters
dialectDialect instance in use.
def coerce_compared_value(self, op, value):

Suggest a type for a 'coerced' Python value in an expression.

Given an operator and value, gives the type a chance to return a type which the value should be coerced into.

The default behavior here is conservative; if the right-hand side is already coerced into a SQL type based on its Python type, it is usually left alone.

End-user functionality extension here should generally be via .TypeDecorator, which provides more liberal behavior in that it defaults to coercing the other side of the expression into this type, thus applying special Python conversions above and beyond those needed by the DBAPI to both ides. It also provides the public method .TypeDecorator.coerce_compared_value which is intended for end-user customization of this behavior.

def column_expression(self, colexpr):

Given a SELECT column expression, return a wrapping SQL expression.

This is typically a SQL function that wraps a column expression as rendered in the columns clause of a SELECT statement. It is used for special data types that require columns to be wrapped in some special database function in order to coerce the value before being sent back to the application. It is the SQL analogue of the .TypeEngine.result_processor method.

This method is called during the SQL compilation phase of a statement, when rendering a SQL string. It is not called against specific values.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.column_expression method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.column_expression, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.column_expression.

def compare_against_backend(self, dialect, conn_type):

Compare this type against the given backend type.

This function is currently not implemented for SQLAlchemy types, and for all built in types will return None. However, it can be implemented by a user-defined type where it can be consumed by schema comparison tools such as Alembic autogenerate.

A future release of SQLAlchemy will potentially implement this method for builtin types as well.

The function should return True if this type is equivalent to the given type; the type is typically reflected from the database so should be database specific. The dialect in use is also passed. It can also return False to assert that the type is not equivalent.

New in version 1.0.3.
Parameters
dialecta .Dialect that is involved in the comparison.
conn​_typethe type object reflected from the backend.
def compare_values(self, x, y):
Compare two values for equality.
def compile(self, dialect=None):

Produce a string-compiled form of this .TypeEngine.

When called with no arguments, uses a "default" dialect to produce a string result.

Parameters
dialecta .Dialect instance.
def dialect_impl(self, dialect):
Return a dialect-specific implementation for this .TypeEngine.
def evaluates_none(self):

Return a copy of this type which has the .should_evaluate_none flag set to True.

E.g.:

Table(
    'some_table', metadata,
    Column(
        String(50).evaluates_none(),
        nullable=True,
        server_default='no value')
)

The ORM uses this flag to indicate that a positive value of None is passed to the column in an INSERT statement, rather than omitting the column from the INSERT statement which has the effect of firing off column-level defaults. It also allows for types which have special behavior associated with the Python None value to indicate that the value doesn't necessarily translate into SQL NULL; a prime example of this is a JSON type which may wish to persist the JSON value 'null'.

In all cases, the actual NULL SQL value can be always be persisted in any column by using the _expression.null SQL construct in an INSERT statement or associated with an ORM-mapped attribute.

Note

The "evaluates none" flag does not apply to a value of None passed to :paramref:`_schema.Column.default` or :paramref:`_schema.Column.server_default`; in these cases, None still means "no default".

New in version 1.1.

See Also

:ref:`session_forcing_null` - in the ORM documentation

:paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON interaction with this flag.

.TypeEngine.should_evaluate_none - class-level flag

def literal_processor(self, dialect):

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the "literal_binds" flag, typically used in DDL generation as well as in certain scenarios where backends don't accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param.

def result_processor(self, dialect, coltype):

Return a conversion function for processing result row values.

Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user.

If processing is not necessary, the method should return None.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.result_processor method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.result_processor, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_result_value.

Parameters
dialectDialect instance in use.
coltypeDBAPI coltype argument received in cursor.description.
def with_variant(self, type_, dialect_name):

Produce a new type object that will utilize the given type when applied to the dialect of the given name.

e.g.:

from sqlalchemy.types import String
from sqlalchemy.dialects import mysql

s = String()

s = s.with_variant(mysql.VARCHAR(collation='foo'), 'mysql')

The construction of .TypeEngine.with_variant is always from the "fallback" type to that which is dialect specific. The returned type is an instance of .Variant, which itself provides a .Variant.with_variant that can be called repeatedly.

Parameters
type​_a .TypeEngine that will be selected as a variant from the originating type, when a dialect of the given name is in use.
dialect​_namebase name of the dialect which uses this type. (i.e. 'postgresql', 'mysql', etc.)
hashable: bool =

Flag, if False, means values from this type aren't hashable.

Used by the ORM when uniquing result lists.

should_evaluate_none: bool =
overridden in sqlalchemy.types.JSON

If True, the Python constant None is considered to be handled explicitly by this type.

The ORM uses this flag to indicate that a positive value of None is passed to the column in an INSERT statement, rather than omitting the column from the INSERT statement which has the effect of firing off column-level defaults. It also allows types which have special behavior for Python None, such as a JSON type, to indicate that they'd like to handle the None value explicitly.

To set this flag on an existing type, use the .TypeEngine.evaluates_none method.

See Also

.TypeEngine.evaluates_none

New in version 1.1.
sort_key_function =

A sorting function that can be passed as the key to sorted.

The default value of None indicates that the values stored by this type are self-sorting.

New in version 1.3.8.
@staticmethod
def _to_instance(cls_or_self):

Undocumented

def __str__(self):

Undocumented

def _cached_bind_processor(self, dialect):
Return a dialect-specific bind processor for this type.
def _cached_custom_processor(self, dialect, key, fn):

Undocumented

def _cached_literal_processor(self, dialect):
Return a dialect-specific literal processor for this type.
def _cached_result_processor(self, dialect, coltype):
Return a dialect-specific result processor for this type.
def _compare_type_affinity(self, other):

Undocumented

@util.preload_module('sqlalchemy.engine.default')
def _default_dialect(self):

Undocumented

def _dialect_info(self, dialect):
Return a dialect-specific registry which caches a dialect-specific implementation, bind processing function, and one or more result processing functions.
def _gen_dialect_impl(self, dialect):

Undocumented

def _resolve_for_literal(self, value):

adjust this type given a literal Python value that will be stored in a bound parameter.

Used exclusively by _resolve_value_to_type().

New in version 1.4.30: or 2.0
def _unwrapped_dialect_impl(self, dialect):

Return the 'unwrapped' dialect impl for this type.

For a type that applies wrapping logic (e.g. TypeDecorator), give us the real, actual dialect-level type that is used.

This is used by TypeDecorator itself as well at least one case where dialects need to check that a particular specific dialect-level type is in use, within the .DefaultDialect.set_input_sizes method.

def copy(self, **kw):
def copy_value(self, value):

Undocumented

_is_array: bool =

Undocumented

_is_table_value: bool =

Undocumented

_is_tuple_type: bool =

Undocumented

_is_type_decorator: bool =

Undocumented

_isnull: bool =

Undocumented

_sqla_type: bool =

Undocumented

@util.memoized_property
_generic_type_affinity =

Undocumented

@util.memoized_property
_has_bind_expression =

memoized boolean, check if bind_expression is implemented.

Allows the method to be skipped for the vast majority of expression types that don't use this feature.

@util.memoized_property
_has_column_expression =

memoized boolean, check if column_expression is implemented.

Allows the method to be skipped for the vast majority of expression types that don't use this feature.

@util.memoized_property
_static_cache_key =

Undocumented

@util.memoized_property
_type_affinity =
Return a rudimental 'affinity' value expressing the general class of type.
@property
python_type =

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.