class documentation

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 :class:`.TypeEngine` class. Alternatively, the :meth:`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 :attr:`.TypeDecorator.cache_ok` class-level flag indicates if this custom :class:`.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 :class:`.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 :attr:`.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 :meth:`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 :meth:`~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 :class:`.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 :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types; the default rules of :meth:`.TypeEngine.coerce_compared_value` should be used in order to deal with operators like index operations:: from sqlalchemy import JSON from sqlalchemy import TypeDecorator class MyJsonType(TypeDecorator): impl = 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. Similarly, when working with the :class:`.ARRAY` datatype, the type coercion for index operations (e.g. ``mycol[5]``) is also handled by :meth:`.TypeDecorator.coerce_compared_value`, where again a simple override is sufficient unless special rules are needed for particular operators:: from sqlalchemy import ARRAY from sqlalchemy import TypeDecorator class MyArrayType(TypeDecorator): impl = ARRAY cache_ok = True def coerce_compared_value(self, op, value): return self.impl.coerce_compared_value(op, value)

Class Comparator A :class:`.TypeEngine.Comparator` that is specific to :class:`.TypeDecorator`.
Method __getattr__ Proxy all other undefined accessors to the underlying implementation.
Method __init__ Construct a :class:`.TypeDecorator`.
Method __repr__ Undocumented
Method bind_expression Given a bind value (i.e. a :class:`.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 :class:`.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 :class:`.TypeDecorator` instance.
Method get_dbapi_type Return the DBAPI type object represented by this :class:`.TypeDecorator`.
Method literal_processor Provide a literal processing function for the given :class:`.Dialect`.
Method load_dialect_impl Return a :class:`.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 :class:`.Dialect`.
Method type_engine Return a dialect-specific :class:`.TypeEngine` instance for this :class:`.TypeDecorator`.
Class Variable __visit_name__ Undocumented
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 ``!=``).
Instance Variable impl Undocumented
Property comparator_factory Undocumented
Property impl_instance Undocumented
Property sort_key_function A sorting function that can be passed as the key to sorted.
Method _gen_dialect_impl Undocumented
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 _is_type_decorator 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 Return a rudimental 'affinity' value expressing the general class of type.

Inherited from SchemaEventTarget:

Class Variable dispatch Undocumented

Inherited from EventTarget (via SchemaEventTarget):

Class Variable __slots__ Undocumented

Inherited from ExternalType (via SchemaEventTarget, EventTarget):

Class Variable cache_ok Indicate if statements using this :class:`.ExternalType` are "safe to cache".
Property _static_cache_key Undocumented

Inherited from TypeEngineMixin (via SchemaEventTarget, EventTarget, ExternalType):

Method adapt Undocumented
Method dialect_impl Undocumented

Inherited from TypeEngine (via SchemaEventTarget, EventTarget, ExternalType, TypeEngineMixin):

Method __str__ Undocumented
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 :class:`.TypeEngine`.
Method copy_value Undocumented
Method evaluates_none Return a copy of this type which has the :attr:`.should_evaluate_none` flag set to True.
Method with_variant Produce a copy of this 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 render_bind_cast Render bind casts for :attr:`.BindTyping.RENDER_CASTS` mode.
Class Variable render_literal_cast render casts when rendering a value as an inline literal, e.g. with :meth:`.TypeEngine.literal_processor`.
Class Variable should_evaluate_none If True, the Python constant ``None`` is considered to be handled explicitly by this type.
Property python_type Return the Python type object expected to be returned by instances of this type, if known.
Static Method _to_instance Undocumented
Method _cached_bind_processor Return a dialect-specific bind processor for this type.
Method _cached_custom_processor return a dialect-specific processing object for custom purposes.
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 _resolve_for_python_type given a Python type (e.g. ``int``, ``str``, etc. ) return an instance of this :class:`.TypeEngine` that's appropriate for this type.
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

Inherited from Visitable (via SchemaEventTarget, EventTarget, ExternalType, TypeEngineMixin, TypeEngine):

Method __class_getitem__ Undocumented
Method __init_subclass__ Undocumented
Class Method _generate_compiler_dispatch Undocumented
Method _compiler_dispatch Undocumented
Class Variable _original_compiler_dispatch Undocumented
def __getattr__(self, key: str) -> Any: (source)

Proxy all other undefined accessors to the underlying implementation.

def __init__(self, *args: Any, **kwargs: Any): (source)

Construct a :class:`.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.

def __repr__(self) -> str: (source)
def bind_expression(self, bindparam: BindParameter[_T]) -> Optional[ColumnElement[_T]]: (source)

Given a bind value (i.e. a :class:`.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 :meth:`_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 :class:`_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.

def bind_processor(self, dialect: Dialect) -> Optional[_BindProcessorType[_T]]: (source)

Provide a bound value processing function for the given :class:`.Dialect`. This is the method that fulfills the :class:`.TypeEngine` contract for bound value conversion which normally occurs via the :meth:`_types.TypeEngine.bind_processor` method. .. note:: User-defined subclasses of :class:`_types.TypeDecorator` should **not** implement this method, and should instead implement :meth:`_types.TypeDecorator.process_bind_param` so that the "inner" processing provided by the implementing type is maintained. :param dialect: Dialect instance in use.

def coerce_compared_value(self, op: Optional[OperatorType], value: Any) -> Any: (source)

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.

def column_expression(self, column: ColumnElement[_T]) -> Optional[ColumnElement[_T]]: (source)

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 :meth:`_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 :class:`_types.TypeDecorator` can override this method to provide custom column expression behavior for the type. This implementation will **replace** that of the underlying implementation type. See the description of :meth:`_types.TypeEngine.column_expression` for a complete description of the method's use.

def compare_values(self, x: Any, y: Any) -> bool: (source)

Given two values, compare them for equality. By default this calls upon :meth:`.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.

def copy(self, **kw: Any) -> Self: (source)

Produce a copy of this :class:`.TypeDecorator` instance. This is a shallow copy and is provided to fulfill part of the :class:`.TypeEngine` contract. It usually does not need to be overridden unless the user-defined :class:`.TypeDecorator` has local state that should be deep-copied.

def get_dbapi_type(self, dbapi: ModuleType) -> Optional[Any]: (source)

Return the DBAPI type object represented by this :class:`.TypeDecorator`. By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the underlying "impl".

def literal_processor(self, dialect: Dialect) -> Optional[_LiteralProcessorType[_T]]: (source)

Provide a literal processing function for the given :class:`.Dialect`. This is the method that fulfills the :class:`.TypeEngine` contract for literal value conversion which normally occurs via the :meth:`_types.TypeEngine.literal_processor` method. .. note:: User-defined subclasses of :class:`_types.TypeDecorator` should **not** implement this method, and should instead implement :meth:`_types.TypeDecorator.process_literal_param` so that the "inner" processing provided by the implementing type is maintained.

def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]: (source)

Return a :class:`.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 :class:`.TypeDecorator` implementation of :meth:`type_engine` to help determine what type should ultimately be returned for a given :class:`.TypeDecorator`. By default returns ``self.impl``.

def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any: (source)

Receive a bound parameter value to be converted. Custom subclasses of :class:`_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. :param value: Data to operate upon, of any type expected by this method in the subclass. Can be ``None``. :param dialect: the :class:`.Dialect` in use. .. seealso:: :ref:`types_typedecorator` :meth:`_types.TypeDecorator.process_result_value`

def process_literal_param(self, value: Optional[_T], dialect: Dialect) -> str: (source)

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 :meth:`_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 :class:`_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.

def process_result_value(self, value: Optional[Any], dialect: Dialect) -> Optional[_T]: (source)

Receive a result-row column value to be converted. Custom subclasses of :class:`_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. :param value: Data to operate upon, of any type expected by this method in the subclass. Can be ``None``. :param dialect: the :class:`.Dialect` in use. .. seealso:: :ref:`types_typedecorator` :meth:`_types.TypeDecorator.process_bind_param`

def result_processor(self, dialect: Dialect, coltype: Any) -> Optional[_ResultProcessorType[_T]]: (source)

Provide a result value processing function for the given :class:`.Dialect`. This is the method that fulfills the :class:`.TypeEngine` contract for bound value conversion which normally occurs via the :meth:`_types.TypeEngine.result_processor` method. .. note:: User-defined subclasses of :class:`_types.TypeDecorator` should **not** implement this method, and should instead implement :meth:`_types.TypeDecorator.process_result_value` so that the "inner" processing provided by the implementing type is maintained. :param dialect: Dialect instance in use. :param coltype: A SQLAlchemy data type

def type_engine(self, dialect: Dialect) -> TypeEngine[Any]: (source)

Return a dialect-specific :class:`.TypeEngine` instance for this :class:`.TypeDecorator`. In most cases this returns a dialect-adapted form of the :class:`.TypeEngine` type represented by ``self.impl``. Makes usage of :meth:`dialect_impl`. Behavior can be customized here by overriding :meth:`load_dialect_impl`.

coerce_to_is_types: Sequence[Type[Any]] = (source)

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``. :class:`.TypeDecorator` modifies this list to only include ``NoneType``, as typedecorator implementations that deal with boolean types are common. Custom :class:`.TypeDecorator` classes can override this attribute to return an empty tuple, in which case no values will be coerced to constants.

Undocumented

@util.memoized_property
impl_instance: TypeEngine[Any] = (source)

Undocumented

@property
sort_key_function: Optional[Callable[[Any], Any]] = (source)

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. .. versionadded:: 1.3.8

def _gen_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]: (source)
def _set_parent(self, parent: SchemaEventTarget, outer: bool = False, **kw: Any): (source)

Support SchemaEventTarget

def _set_parent_with_dispatch(self, parent: SchemaEventTarget, **kw: Any): (source)
def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]: (source)

Return the 'unwrapped' dialect impl for this type. This is used by the :meth:`.DefaultDialect.set_input_sizes` method.

@util.memoized_property
_has_bind_expression: bool = (source)

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_bind_processor: bool = (source)

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.

@util.memoized_property
_has_column_expression: bool = (source)

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
_has_literal_processor: bool = (source)

memoized boolean, check if process_literal_param is implemented.

@util.memoized_property
_has_result_processor: bool = (source)

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.

@util.ro_non_memoized_property
_type_affinity: Optional[Type[TypeEngine[Any]]] = (source)

Return a rudimental 'affinity' value expressing the general class of type.