class Enum(Emulated, String, SchemaType):
Known subclasses: sqlalchemy.dialects.mysql.enumerated.ENUM
, sqlalchemy.dialects.postgresql.ENUM
, sqlalchemy.dialects.oracle.cx_oracle._OracleEnum
Generic Enum Type.
The .Enum
type provides a set of possible string values
which the column is constrained towards.
The .Enum
type will make use of the backend's native "ENUM"
type if one is available; otherwise, it uses a VARCHAR datatype.
An option also exists to automatically produce a CHECK constraint
when the VARCHAR (so called "non-native") variant is produced;
see the :paramref:`.Enum.create_constraint` flag.
The .Enum
type also provides in-Python validation of string
values during both read and write operations. When reading a value
from the database in a result set, the string value is always checked
against the list of possible values and a LookupError is raised
if no match is found. When passing a value to the database as a
plain string within a SQL statement, if the
:paramref:`.Enum.validate_strings` parameter is
set to True, a LookupError is raised for any string value that's
not located in the given list of possible values; note that this
impacts usage of LIKE expressions with enumerated values (an unusual
use case).
.Enum
type now provides in-Python
validation of input values as well as on data being returned by
the database.The source of enumerated values may be a list of string values, or
alternatively a PEP-435-compliant enumerated class. For the purposes
of the .Enum
datatype, this class need only provide a
__members__ method.
When using an enumerated class, the enumerated objects are used both for input and output, rather than strings as is the case with a plain-string enumerated type:
import enum class MyEnum(enum.Enum): one = 1 two = 2 three = 3 t = Table( 'data', MetaData(), Column('value', Enum(MyEnum)) ) connection.execute(t.insert(), {"value": MyEnum.two}) assert connection.scalar(t.select()) is MyEnum.two
Above, the string names of each element, e.g. "one", "two", "three", are persisted to the database; the values of the Python Enum, here indicated as integers, are not used; the value of each enum can therefore be any kind of Python object whether or not it is persistable.
In order to persist the values and not the names, the :paramref:`.Enum.values_callable` parameter may be used. The value of this parameter is a user-supplied callable, which is intended to be used with a PEP-435-compliant enumerated class and returns a list of string values to be persisted. For a simple enumeration that uses string values, a callable such as lambda x: [e.value for e in x] is sufficient.
See Also
_postgresql.ENUM
- PostgreSQL-specific type,
which has additional functionality.
.mysql.ENUM
- MySQL-specific type
Method | __init__ |
Construct an enum. |
Class | Comparator |
Undocumented |
Method | __repr__ |
Undocumented |
Method | _db_value_for_elem |
Undocumented |
Method | _enum_init |
internal init for .Enum and subclasses. |
Method | _object_value_for_elem |
Undocumented |
Method | _parse_into_values |
Undocumented |
Method | _set_table |
Undocumented |
Method | _setup_for_values |
Undocumented |
Method | _should_create_constraint |
Undocumented |
Method | adapt |
Produce an "adapted" form of this type, given an "impl" class to work with. |
Method | adapt_to_emulated |
Given an impl class, adapt this type to the impl assuming "emulated". |
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_processor |
Return a conversion function for processing bind values. |
Method | copy |
Undocumented |
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. |
Class Variable | __visit_name__ |
Undocumented |
Instance Variable | _object_lookup |
Undocumented |
Instance Variable | _omit_aliases |
Undocumented |
Instance Variable | _sort_key_function |
Undocumented |
Instance Variable | _valid_lookup |
Undocumented |
Instance Variable | create_constraint |
Undocumented |
Instance Variable | enum_class |
Undocumented |
Instance Variable | enums |
Undocumented |
Instance Variable | native_enum |
Undocumented |
Instance Variable | validate_strings |
Undocumented |
Instance Variable | values_callable |
Undocumented |
Property | _enums_argument |
Undocumented |
Property | native |
Undocumented |
Property | python_type |
Return the Python type object expected to be returned by instances of this type, if known. |
Property | sort_key_function |
A sorting function that can be passed as the key to sorted. |
Inherited from String
:
Method | get_dbapi_type |
Return the corresponding type object from the underlying DB-API, if any. |
Constant | RETURNS_BYTES |
Undocumented |
Constant | RETURNS_CONDITIONAL |
Undocumented |
Constant | RETURNS_UNICODE |
Undocumented |
Constant | RETURNS_UNKNOWN |
Undocumented |
Class Method | _warn_deprecated_unicode |
Undocumented |
Instance Variable | _expect_unicode |
Undocumented |
Instance Variable | _expect_unicode_error |
Undocumented |
Instance Variable | _warn_on_bytestring |
Undocumented |
Instance Variable | collation |
Undocumented |
Instance Variable | length |
Undocumented |
Inherited from TypeEngine
(via String
):
Method | bind_expression |
Given a bind value (i.e. a .BindParameter instance), return a SQL expression in its place. |
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 | 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 | _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_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. |
Inherited from Traversible
(via String
, TypeEngine
):
Method | get_children |
Return immediate child .visitors.Traversible elements of this .visitors.Traversible . |
Method | __class_getitem__ |
Undocumented |
Inherited from SchemaType
:
Method | _is_impl_for_variant |
Undocumented |
Method | _on_metadata_create |
Undocumented |
Method | _on_metadata_drop |
Undocumented |
Method | _on_table_create |
Undocumented |
Method | _on_table_drop |
Undocumented |
Method | _set_parent |
Associate with this SchemaEvent's parent object. |
Method | _variant_mapping_for_set_table |
Undocumented |
Method | create |
Issue CREATE DDL for this type, if applicable. |
Method | drop |
Issue DROP DDL for this type, if applicable. |
Class Variable | _use_schema_map |
Undocumented |
Instance Variable | _create_events |
Undocumented |
Instance Variable | inherit_schema |
Undocumented |
Instance Variable | metadata |
Undocumented |
Instance Variable | name |
Undocumented |
Instance Variable | schema |
Undocumented |
Property | bind |
Undocumented |
Inherited from SchemaEventTarget
(via SchemaType
):
Method | _set_parent_with_dispatch |
Undocumented |
sqlalchemy.types.String.__init__
Construct an enum.
Keyword arguments which don't apply to a specific backend are ignored by that backend.
Parameters | |
*enums | either exactly one PEP-435 compliant enumerated type or one or more string labels.
New in version 1.1: a PEP-435 style enumerated class may be
passed.
|
**kw | Undocumented |
convert_unicode | Enable unicode-aware bind parameter and result-set processing for this Enum's data under Python 2 only. Under Python 2, this is set automatically based on the presence of unicode label strings. This flag will be removed in SQLAlchemy 2.0. |
create_constraint | defaults to False. When creating a non-native enumerated type, also build a CHECK constraint on the database against the valid values. Note it is strongly recommended that the CHECK constraint have an explicit name in order to support schema-management concerns. This can be established either by setting the :paramref:`.Enum.name` parameter or by setting up an appropriate naming convention; see :ref:`constraint_naming_conventions` for background.
Changed in version 1.4: - this flag now defaults to False, meaning
no CHECK constraint is generated for a non-native enumerated
type.
|
metadata | Associate this type directly with a MetaData object. For types that exist on the target database as an independent schema construct (PostgreSQL), this type will be created and dropped within create_all() and drop_all() operations. If the type is not associated with any MetaData object, it will associate itself with each Table in which it is used, and will be created when any of those individual tables are created, after a check is performed for its existence. The type is only dropped when drop_all() is called for that Table object's metadata, however. The value of the :paramref:`_schema.MetaData.schema` parameter of
the
Changed in version 1.4.12:
_types.Enum inherits the
:paramref:`_schema.MetaData.schema` parameter of the
_schema.MetaData object if present, when passed using
the :paramref:`_types.Enum.metadata` parameter. |
name | The name of this type. This is required for PostgreSQL and any future supported database which requires an explicitly named type, or an explicitly named constraint in order to generate the type and/or a table that uses it. If a PEP-435 enumerated class was used, its name (converted to lower case) is used by default. |
native_enum | Use the database's native ENUM type when available. Defaults to True. When False, uses VARCHAR + check constraint for all backends. The VARCHAR length can be controlled with :paramref:`.Enum.length` |
length | Allows specifying a custom length for the VARCHAR when :paramref:`.Enum.native_enum` is False. By default it uses the length of the longest value.
New in version 1.3.16.
|
schema | Schema name of this type. For types that exist on the target database as an independent schema construct (PostgreSQL), this parameter specifies the named schema in which the type is present. If not present, the schema name will be taken from the
Changed in version 1.4.12:
_types.Enum inherits the
:paramref:`_schema.MetaData.schema` parameter of the
_schema.MetaData object if present, when passed using
the :paramref:`_types.Enum.metadata` parameter.Otherwise, if the :paramref:`_types.Enum.inherit_schema` flag is set
to True, the schema will be inherited from the associated
|
quote | Set explicit quoting preferences for the type's name. |
inherit_schema | When True, the "schema" from the owning
_schema.Table
will be copied to the "schema" attribute of this
.Enum , replacing whatever value was passed for the
schema attribute. This also takes effect when using the
_schema.Table.to_metadata operation. |
validate_strings | when True, string values that are being passed to the database in a SQL statement will be checked for validity against the list of enumerated values. Unrecognized values will result in a LookupError being raised.
New in version 1.1.0b2.
|
values_callable | A callable which will be passed the PEP-435 compliant enumerated type, which should then return a list of string values to be persisted. This allows for alternate usages such as using the string value of an enum to be persisted to the database instead of its name.
New in version 1.2.3.
|
sort_key_function | a Python callable which may be used as the "key" argument in the Python sorted() built-in. The SQLAlchemy ORM requires that primary key columns which are mapped must be sortable in some way. When using an unsortable enumeration object such as a Python 3 Enum object, this parameter may be used to set a default sort key function for the objects. By default, the database value of the enumeration is used as the sorting function.
New in version 1.3.8.
|
omit_aliases | A boolean that when true will remove aliases from pep 435 enums. For backward compatibility it defaults to False. A deprecation warning is raised if the enum has aliases and this flag was not set.
New in version 1.4.5.
Deprecated since version 1.4: The default will be changed to True in
SQLAlchemy 2.0.
|
sqlalchemy.types.TypeEngine.__repr__
sqlalchemy.dialects.mysql.enumerated.ENUM
Undocumented
internal init for .Enum
and subclasses.
friendly init helper used by subclasses to remove all the Enum-specific keyword arguments from kw. Allows all other arguments in kw to pass through.
sqlalchemy.dialects.mysql.enumerated.ENUM
Undocumented
sqlalchemy.sql.type_api.Emulated.adapt
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.
Given an impl class, adapt this type to the impl assuming "emulated".
The impl should also be an "emulated" version of this type, most likely the same class as this type itself.
e.g.: sqltypes.Enum adapts to the Enum class.
sqlalchemy.types.TypeEngine.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.
>>> 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)
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.
sqlalchemy.types.String.bind_processor
sqlalchemy.dialects.oracle.cx_oracle._OracleEnum
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
.
See Also
Parameters | |
dialect | Dialect instance in use. |
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
.
See Also
sqlalchemy.types.String.result_processor
sqlalchemy.dialects.postgresql.psycopg2._PGEnum
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
.
See Also
Parameters | |
dialect | Dialect instance in use. |
coltype | DBAPI coltype argument received in cursor.description. |
str
=
sqlalchemy.types.String.__visit_name__
sqlalchemy.dialects.mysql.enumerated.ENUM
Undocumented
sqlalchemy.types.String.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.