class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[
Known subclasses: sqlalchemy.sql.sqltypes.Interval
, sqlalchemy.sql.sqltypes.PickleType
, sqlalchemy.sql.type_api.Variant
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 |
|
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 |
Given a bind value (i.e. a :class:`.BindParameter` instance), return a SQL expression which will typically wrap the given parameter. |
Method | bind |
Provide a bound value processing function for the given :class:`.Dialect`. |
Method | coerce |
Suggest a type for a 'coerced' Python value in an expression. |
Method | column |
Given a SELECT column expression, return a wrapping SQL expression. |
Method | compare |
Given two values, compare them for equality. |
Method | copy |
Produce a copy of this :class:`.TypeDecorator` instance. |
Method | get |
Return the DBAPI type object represented by this :class:`.TypeDecorator`. |
Method | literal |
Provide a literal processing function for the given :class:`.Dialect`. |
Method | load |
Return a :class:`.TypeEngine` object corresponding to a dialect. |
Method | process |
Receive a bound parameter value to be converted. |
Method | process |
Receive a literal parameter value to be rendered inline within a statement. |
Method | process |
Receive a result-row column value to be converted. |
Method | result |
Provide a result value processing function for the given :class:`.Dialect`. |
Method | type |
Return a dialect-specific :class:`.TypeEngine` instance for this :class:`.TypeDecorator`. |
Class Variable | __visit |
Undocumented |
Class Variable | coerce |
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 |
Undocumented |
Property | impl |
Undocumented |
Property | sort |
A sorting function that can be passed as the key to sorted. |
Method | _gen |
Undocumented |
Method | _set |
Support SchemaEventTarget |
Method | _set |
Support SchemaEventTarget |
Method | _unwrapped |
Return the 'unwrapped' dialect impl for this type. |
Class Variable | _is |
Undocumented |
Property | _has |
memoized boolean, check if bind_expression is implemented. |
Property | _has |
memoized boolean, check if process_bind_param is implemented. |
Property | _has |
memoized boolean, check if column_expression is implemented. |
Property | _has |
memoized boolean, check if process_literal_param is implemented. |
Property | _has |
memoized boolean, check if process_result_value is implemented. |
Property | _type |
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 |
Indicate if statements using this :class:`.ExternalType` are "safe to cache". |
Property | _static |
Undocumented |
Inherited from TypeEngineMixin
(via SchemaEventTarget
, EventTarget
, ExternalType
):
Method | adapt |
Undocumented |
Method | dialect |
Undocumented |
Inherited from TypeEngine
(via SchemaEventTarget
, EventTarget
, ExternalType
, TypeEngineMixin
):
Method | __str__ |
Undocumented |
Method | as |
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 |
Compare this type against the given backend type. |
Method | compile |
Produce a string-compiled form of this :class:`.TypeEngine`. |
Method | copy |
Undocumented |
Method | evaluates |
Return a copy of this type which has the :attr:`.should_evaluate_none` flag set to True. |
Method | with |
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 |
Render bind casts for :attr:`.BindTyping.RENDER_CASTS` mode. |
Class Variable | render |
render casts when rendering a value as an inline literal, e.g. with :meth:`.TypeEngine.literal_processor`. |
Class Variable | should |
If True, the Python constant ``None`` is considered to be handled explicitly by this type. |
Property | python |
Return the Python type object expected to be returned by instances of this type, if known. |
Static Method | _to |
Undocumented |
Method | _cached |
Return a dialect-specific bind processor for this type. |
Method | _cached |
return a dialect-specific processing object for custom purposes. |
Method | _cached |
Return a dialect-specific literal processor for this type. |
Method | _cached |
Return a dialect-specific result processor for this type. |
Method | _compare |
Undocumented |
Method | _default |
Undocumented |
Method | _dialect |
Return a dialect-specific registry which caches a dialect-specific implementation, bind processing function, and one or more result processing functions. |
Method | _resolve |
adjust this type given a literal Python value that will be stored in a bound parameter. |
Method | _resolve |
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 |
Undocumented |
Class Variable | _is |
Undocumented |
Class Variable | _is |
Undocumented |
Class Variable | _isnull |
Undocumented |
Class Variable | _sqla |
Undocumented |
Property | _generic |
Undocumented |
Inherited from Visitable
(via SchemaEventTarget
, EventTarget
, ExternalType
, TypeEngineMixin
, TypeEngine
):
Method | __class |
Undocumented |
Method | __init |
Undocumented |
Class Method | _generate |
Undocumented |
Method | _compiler |
Undocumented |
Class Variable | _original |
Undocumented |
sqlalchemy.sql.sqltypes.Interval
, sqlalchemy.sql.sqltypes.PickleType
, sqlalchemy.sql.type_api.Variant
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.
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.
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.
sqlalchemy.sql.sqltypes.Interval
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 :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.
sqlalchemy.sql.sqltypes.PickleType
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.
sqlalchemy.sql.type_api.TypeEngine.copy
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.
Return the DBAPI type object represented by this :class:`.TypeDecorator`. By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the underlying "impl".
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.
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``.
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`
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.
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`
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
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`.
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.
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
Return the 'unwrapped' dialect impl for this type. This is used by the :meth:`.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.