class TypeDecorator(ExternalType, SchemaEventTarget, TypeEngine):
Known subclasses: sqlalchemy.sql.type_api.Variant
, sqlalchemy.types.Interval
, sqlalchemy.types.PickleType
, sqlalchemy.dialects.mssql.information_schema.CoerceUnicode
, sqlalchemy.dialects.mssql.information_schema.IdentitySqlVariant
Allows the creation of types which add additional functionality to an existing type.
This method is preferred to direct subclassing of SQLAlchemy's built-in types as it ensures that all required functionality of the underlying type is kept in place.
Typical usage:
import sqlalchemy.types as types class MyType(types.TypeDecorator): '''Prefixes Unicode values with "PREFIX:" on the way in and strips it off on the way out. ''' impl = types.Unicode cache_ok = True def process_bind_param(self, value, dialect): return "PREFIX:" + value def process_result_value(self, value, dialect): return value[7:] def copy(self, **kw): return MyType(self.impl.length)
The class-level impl attribute is required, and can reference any
.TypeEngine
class. Alternatively, the load_dialect_impl
method can be used to provide different type classes based on the dialect
given; in this case, the impl variable can reference
TypeEngine as a placeholder.
The .TypeDecorator.cache_ok
class-level flag indicates if this
custom .TypeDecorator
is safe to be used as part of a cache key.
This flag defaults to None which will initially generate a warning
when the SQL compiler attempts to generate a cache key for a statement
that uses this type. If the .TypeDecorator
is not guaranteed
to produce the same bind/result behavior and SQL generation
every time, this flag should be set to False; otherwise if the
class produces the same behavior each time, it may be set to True.
See .TypeDecorator.cache_ok
for further notes on how this works.
Types that receive a Python type that isn't similar to the ultimate type
used may want to define the TypeDecorator.coerce_compared_value
method. This is used to give the expression system a hint when coercing
Python objects into bind parameters within expressions. Consider this
expression:
mytable.c.somecol + datetime.date(2009, 5, 15)
Above, if "somecol" is an Integer variant, it makes sense that we're doing date arithmetic, where above is usually interpreted by databases as adding a number of days to the given date. The expression system does the right thing by not attempting to coerce the "date()" value into an integer-oriented bind parameter.
However, in the case of TypeDecorator, we are usually changing an incoming Python type to something new - TypeDecorator by default will "coerce" the non-typed side to be the same type as itself. Such as below, we define an "epoch" type that stores a date value as an integer:
class MyEpochType(types.TypeDecorator): impl = types.Integer epoch = datetime.date(1970, 1, 1) def process_bind_param(self, value, dialect): return (value - self.epoch).days def process_result_value(self, value, dialect): return self.epoch + timedelta(days=value)
Our expression of somecol + date with the above type will coerce the "date" on the right side to also be treated as MyEpochType.
This behavior can be overridden via the
~TypeDecorator.coerce_compared_value
method, which returns a type
that should be used for the value of the expression. Below we set it such
that an integer value will be treated as an Integer, and any other
value is assumed to be a date and will be treated as a MyEpochType:
def coerce_compared_value(self, op, value): if isinstance(value, int): return Integer() else: return self
Warning
Note that the behavior of coerce_compared_value is not inherited
by default from that of the base type.
If the .TypeDecorator
is augmenting a
type that requires special logic for certain types of operators,
this method must be overridden. A key example is when decorating
the _postgresql.JSON
and _postgresql.JSONB
types;
the default rules of .TypeEngine.coerce_compared_value
should
be used in order to deal with operators like index operations:
class MyJsonType(TypeDecorator): impl = postgresql.JSON cache_ok = True def coerce_compared_value(self, op, value): return self.impl.coerce_compared_value(op, value)
Without the above step, index operations such as mycol['foo'] will cause the index value 'foo' to be JSON encoded.
Class | Comparator |
A .TypeEngine.Comparator that is specific to .TypeDecorator . |
Method | __init__ |
Construct a .TypeDecorator . |
Method | bind_expression |
Given a bind value (i.e. a .BindParameter instance), return a SQL expression which will typically wrap the given parameter. |
Method | bind_processor |
Provide a bound value processing function for the given .Dialect . |
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_values |
Given two values, compare them for equality. |
Method | copy |
Produce a copy of this .TypeDecorator instance. |
Method | get_dbapi_type |
Return the DBAPI type object represented by this .TypeDecorator . |
Method | literal_processor |
Provide a literal processing function for the given .Dialect . |
Method | load_dialect_impl |
Return a .TypeEngine object corresponding to a dialect. |
Method | process_bind_param |
Receive a bound parameter value to be converted. |
Method | process_literal_param |
Receive a literal parameter value to be rendered inline within a statement. |
Method | process_result_value |
Receive a result-row column value to be converted. |
Method | result_processor |
Provide a result value processing function for the given .Dialect . |
Method | type_engine |
Return a dialect-specific .TypeEngine instance for this .TypeDecorator . |
Class Variable | coerce_to_is_types |
Specify those Python types which should be coerced at the expression level to "IS <constant>" when compared using == (and same for IS NOT in conjunction with !=). |
Method | __getattr__ |
Proxy all other undefined accessors to the underlying implementation. |
Method | __repr__ |
Undocumented |
Method | _gen_dialect_impl |
#todo |
Method | _set_parent |
Support SchemaEventTarget |
Method | _set_parent_with_dispatch |
Support SchemaEventTarget |
Method | _unwrapped_dialect_impl |
Return the 'unwrapped' dialect impl for this type. |
Class Variable | __visit_name__ |
Undocumented |
Class Variable | _is_type_decorator |
Undocumented |
Instance Variable | impl |
Undocumented |
Property | _has_bind_expression |
memoized boolean, check if bind_expression is implemented. |
Property | _has_bind_processor |
memoized boolean, check if process_bind_param is implemented. |
Property | _has_column_expression |
memoized boolean, check if column_expression is implemented. |
Property | _has_literal_processor |
memoized boolean, check if process_literal_param is implemented. |
Property | _has_result_processor |
memoized boolean, check if process_result_value is implemented. |
Property | _type_affinity |
#todo |
Property | comparator_factory |
Undocumented |
Property | sort_key_function |
A sorting function that can be passed as the key to sorted. |
Inherited from ExternalType
:
Class Variable | cache_ok |
Indicate if statements using this .ExternalType are "safe to cache". |
Property | _static_cache_key |
Undocumented |
Inherited from TypeEngine
:
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 | compare_against_backend |
Compare this type against the given backend type. |
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 | 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. |
Static Method | _to_instance |
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 | _resolve_for_literal |
adjust this type given a literal Python value that will be stored in a bound parameter. |
Method | copy_value |
Undocumented |
Class Variable | _is_array |
Undocumented |
Class Variable | _is_table_value |
Undocumented |
Class Variable | _is_tuple_type |
Undocumented |
Class Variable | _isnull |
Undocumented |
Class Variable | _sqla_type |
Undocumented |
Property | _generic_type_affinity |
Undocumented |
Property | _static_cache_key |
Undocumented |
Property | python_type |
Return the Python type object expected to be returned by instances of this type, if known. |
Inherited from Traversible
(via TypeEngine
):
Method | get_children |
Return immediate child .visitors.Traversible elements of this .visitors.Traversible . |
Method | __class_getitem__ |
Undocumented |
sqlalchemy.sql.type_api.Variant
, sqlalchemy.types.Interval
, sqlalchemy.types.PickleType
Construct a .TypeDecorator
.
Arguments sent here are passed to the constructor of the class assigned to the impl class level attribute, assuming the impl is a callable, and the resulting object is assigned to the self.impl instance attribute (thus overriding the class attribute of the same name).
If the class level impl is not a callable (the unusual case), it will be assigned to the same instance attribute 'as-is', ignoring those arguments passed to the constructor.
Subclasses can override this to customize the generation of self.impl entirely.
Given a bind value (i.e. a .BindParameter
instance),
return a SQL expression which will typically wrap the given parameter.
Note
This method is called during the SQL compilation phase of a
statement, when rendering a SQL string. It is not necessarily
called against specific values, and should not be confused with the
_types.TypeDecorator.process_bind_param
method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Subclasses of _types.TypeDecorator
can override this method
to provide custom bind expression behavior for the type. This
implementation will replace that of the underlying implementation
type.
sqlalchemy.types.Interval
, sqlalchemy.types.PickleType
Provide a bound value processing function for the
given .Dialect
.
This is the method that fulfills the .TypeEngine
contract for bound value conversion which normally occurs via
the _types.TypeEngine.bind_processor
method.
Note
User-defined subclasses of _types.TypeDecorator
should
not implement this method, and should instead implement
_types.TypeDecorator.process_bind_param
so that the "inner"
processing provided by the implementing type is maintained.
Parameters | |
dialect | Dialect instance in use. |
sqlalchemy.sql.type_api.Variant
Suggest a type for a 'coerced' Python value in an expression.
By default, returns self. This method is called by the expression system when an object using this type is on the left or right side of an expression against a plain Python object which does not yet have a SQLAlchemy type assigned:
expr = table.c.somecolumn + 35
Where above, if somecolumn uses this type, this method will be called with the value operator.add and 35. The return value is whatever SQLAlchemy type should be used for 35 for this particular operation.
Given a SELECT column expression, return a wrapping SQL expression.
Note
This method is called during the SQL compilation phase of a
statement, when rendering a SQL string. It is not called
against specific values, and should not be confused with the
_types.TypeDecorator.process_result_value
method, which is
the more typical method that processes the actual value returned
in a result row subsequent to statement execution time.
Subclasses of _types.TypeDecorator
can override this method
to provide custom column expresion behavior for the type. This
implementation will replace that of the underlying implementation
type.
See the description of _types.TypeEngine.column_expression
for a complete description of the method's use.
sqlalchemy.types.PickleType
Given two values, compare them for equality.
By default this calls upon .TypeEngine.compare_values
of the underlying "impl", which in turn usually
uses the Python equals operator ==.
This function is used by the ORM to compare an original-loaded value with an intercepted "changed" value, to determine if a net change has occurred.
sqlalchemy.types.TypeEngine.copy
Produce a copy of this .TypeDecorator
instance.
This is a shallow copy and is provided to fulfill part of
the .TypeEngine
contract. It usually does not
need to be overridden unless the user-defined .TypeDecorator
has local state that should be deep-copied.
Return the DBAPI type object represented by this
.TypeDecorator
.
By default this calls upon .TypeEngine.get_dbapi_type
of the
underlying "impl".
Provide a literal processing function for the given
.Dialect
.
This is the method that fulfills the .TypeEngine
contract for literal value conversion which normally occurs via
the _types.TypeEngine.literal_processor
method.
Note
User-defined subclasses of _types.TypeDecorator
should
not implement this method, and should instead implement
_types.TypeDecorator.process_literal_param
so that the
"inner" processing provided by the implementing type is maintained.
sqlalchemy.sql.type_api.Variant
Return a .TypeEngine
object corresponding to a dialect.
This is an end-user override hook that can be used to provide
differing types depending on the given dialect. It is used
by the .TypeDecorator
implementation of type_engine
to help determine what type should ultimately be returned
for a given .TypeDecorator
.
By default returns self.impl.
Receive a bound parameter value to be converted.
Custom subclasses of _types.TypeDecorator
should override
this method to provide custom behaviors for incoming data values.
This method is called at statement execution time and is passed
the literal Python data value which is to be associated with a bound
parameter in the statement.
The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic.
Parameters | |
value | Data to operate upon, of any type expected by this method in the subclass. Can be None. |
dialect | the .Dialect in use. |
Receive a literal parameter value to be rendered inline within a statement.
Note
This method is called during the SQL compilation phase of a
statement, when rendering a SQL string. Unlike other SQL
compilation methods, it is passed a specific Python value to be
rendered as a string. However it should not be confused with the
_types.TypeDecorator.process_bind_param
method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Custom subclasses of _types.TypeDecorator
should override
this method to provide custom behaviors for incoming data values
that are in the special case of being rendered as literals.
The returned string will be rendered into the output string.
Receive a result-row column value to be converted.
Custom subclasses of _types.TypeDecorator
should override
this method to provide custom behaviors for data values
being received in result rows coming from the database.
This method is called at result fetching time and is passed
the literal Python data value that's extracted from a database result
row.
The operation could be anything desired to perform custom behavior, such as transforming or deserializing data.
Parameters | |
value | Data to operate upon, of any type expected by this method in the subclass. Can be None. |
dialect | the .Dialect in use. |
sqlalchemy.types.Interval
, sqlalchemy.types.PickleType
Provide a result value processing function for the given
.Dialect
.
This is the method that fulfills the .TypeEngine
contract for bound value conversion which normally occurs via
the _types.TypeEngine.result_processor
method.
Note
User-defined subclasses of _types.TypeDecorator
should
not implement this method, and should instead implement
_types.TypeDecorator.process_result_value
so that the
"inner" processing provided by the implementing type is maintained.
Parameters | |
dialect | Dialect instance in use. |
coltype | A SQLAlchemy data type |
Return a dialect-specific .TypeEngine
instance
for this .TypeDecorator
.
In most cases this returns a dialect-adapted form of
the .TypeEngine
type represented by self.impl.
Makes usage of dialect_impl
.
Behavior can be customized here by overriding
load_dialect_impl
.
Specify those Python types which should be coerced at the expression level to "IS <constant>" when compared using == (and same for IS NOT in conjunction with !=).
For most SQLAlchemy types, this includes NoneType, as well as bool.
.TypeDecorator
modifies this list to only include NoneType,
as typedecorator implementations that deal with boolean types are common.
Custom .TypeDecorator
classes can override this attribute to
return an empty tuple, in which case no values will be coerced to
constants.
sqlalchemy.sql.type_api.Variant
sqlalchemy.sql.type_api.Variant
Return the 'unwrapped' dialect impl for this type.
This is used by the .DefaultDialect.set_input_sizes
method.
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.
memoized boolean, check if process_bind_param is implemented.
Allows the base process_bind_param to raise NotImplementedError without needing to test an expensive exception throw.
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.
memoized boolean, check if process_result_value is implemented.
Allows the base process_result_value to raise NotImplementedError without needing to test an expensive exception throw.