class Enum(String, SchemaType, Emulated, TypeEngine[
Known subclasses: sqlalchemy.dialects.mysql.ENUM
, sqlalchemy.dialects.postgresql.ENUM
, sqlalchemy.dialects.oracle.cx_oracle._OracleEnum
Generic Enum Type. The :class:`.Enum` type provides a set of possible string values which the column is constrained towards. The :class:`.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 :class:`.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). .. versionchanged:: 1.1 the :class:`.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 :class:`.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 from sqlalchemy 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. .. versionadded:: 1.1 - support for PEP-435-style enumerated classes. .. seealso:: :ref:`orm_declarative_mapped_column_enums` - background on using the :class:`_sqltypes.Enum` datatype with the ORM's :ref:`ORM Annotated Declarative <orm_declarative_mapped_column>` feature. :class:`_postgresql.ENUM` - PostgreSQL-specific type, which has additional functionality. :class:`.mysql.ENUM` - MySQL-specific type
Class |
|
Undocumented |
Method | __init__ |
Construct an enum. |
Method | __repr__ |
Undocumented |
Method | adapt |
Produce an "adapted" form of this type, given an "impl" class to work with. |
Method | adapt |
Given an impl class, adapt this type to the impl assuming "emulated". |
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 | bind |
Return a conversion function for processing bind values. |
Method | copy |
Undocumented |
Method | literal |
Return a conversion function for processing literal values that are to be rendered directly without using binds. |
Method | result |
Return a conversion function for processing result row values. |
Class Variable | __visit |
Undocumented |
Instance Variable | create |
Undocumented |
Instance Variable | enum |
Undocumented |
Instance Variable | enums |
Undocumented |
Instance Variable | native |
Undocumented |
Instance Variable | validate |
Undocumented |
Instance Variable | values |
Undocumented |
Property | native |
Undocumented |
Property | python |
Return the Python type object expected to be returned by instances of this type, if known. |
Property | sort |
A sorting function that can be passed as the key to sorted. |
Method | _db |
Undocumented |
Method | _enum |
internal init for :class:`.Enum` and subclasses. |
Method | _make |
Undocumented |
Method | _object |
Undocumented |
Method | _parse |
Undocumented |
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. |
Method | _set |
Undocumented |
Method | _setup |
Undocumented |
Method | _should |
Undocumented |
Instance Variable | _default |
Undocumented |
Instance Variable | _object |
Undocumented |
Instance Variable | _omit |
Undocumented |
Instance Variable | _sort |
Undocumented |
Instance Variable | _valid |
Undocumented |
Property | _enums |
Undocumented |
Inherited from String
:
Method | get |
Return the corresponding type object from the underlying DB-API, if any. |
Instance Variable | collation |
Undocumented |
Instance Variable | length |
Undocumented |
Inherited from SchemaType
(via String
, Concatenable
):
Method | create |
Issue CREATE DDL for this type, if applicable. |
Method | drop |
Issue DROP DDL for this type, if applicable. |
Instance Variable | dispatch |
Undocumented |
Instance Variable | inherit |
Undocumented |
Instance Variable | metadata |
Undocumented |
Instance Variable | name |
Undocumented |
Instance Variable | schema |
Undocumented |
Method | _is |
Undocumented |
Method | _on |
Undocumented |
Method | _on |
Undocumented |
Method | _on |
Undocumented |
Method | _on |
Undocumented |
Method | _set |
Associate with this SchemaEvent's parent object. |
Method | _variant |
Undocumented |
Class Variable | _use |
Undocumented |
Instance Variable | _create |
Undocumented |
Inherited from SchemaEventTarget
(via String
, Concatenable
, SchemaType
):
Method | _set |
Undocumented |
Inherited from EventTarget
(via String
, Concatenable
, SchemaType
, SchemaEventTarget
):
Class Variable | __slots__ |
Undocumented |
Inherited from TypeEngineMixin
(via String
, Concatenable
, SchemaType
, SchemaEventTarget
, EventTarget
, Emulated
):
Method | dialect |
Undocumented |
Property | _static |
Undocumented |
Inherited from TypeEngine
(via String
, Concatenable
, SchemaType
, SchemaEventTarget
, EventTarget
, Emulated
, TypeEngineMixin
):
Method | __str__ |
Undocumented |
Method | bind |
Given a bind value (i.e. a :class:`.BindParameter` instance), return a SQL expression in its place. |
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 |
Compare this type against the given backend type. |
Method | compare |
Compare two values for equality. |
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. |
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 | _gen |
Undocumented |
Method | _unwrapped |
Return the 'unwrapped' dialect impl for this type. |
Class Variable | _is |
Undocumented |
Class Variable | _is |
Undocumented |
Class Variable | _is |
Undocumented |
Class Variable | _is |
Undocumented |
Class Variable | _isnull |
Undocumented |
Class Variable | _sqla |
Undocumented |
Property | _generic |
Undocumented |
Property | _has |
memoized boolean, check if bind_expression is implemented. |
Property | _has |
memoized boolean, check if column_expression is implemented. |
Property | _type |
Return a rudimental 'affinity' value expressing the general class of type. |
Inherited from Visitable
(via String
, Concatenable
, SchemaType
, SchemaEventTarget
, EventTarget
, Emulated
, TypeEngineMixin
, TypeEngine
):
Method | __class |
Undocumented |
Method | __init |
Undocumented |
Class Method | _generate |
Undocumented |
Method | _compiler |
Undocumented |
Class Variable | _original |
Undocumented |
sqlalchemy.sql.sqltypes.String.__init__
Construct an enum. Keyword arguments which don't apply to a specific backend are ignored by that backend. :param \*enums: either exactly one PEP-435 compliant enumerated type or one or more string labels. .. versionadded:: 1.1 a PEP-435 style enumerated class may be passed. :param 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. .. versionchanged:: 1.4 - this flag now defaults to False, meaning no CHECK constraint is generated for a non-native enumerated type. :param 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 :class:`_schema.MetaData` object, if set, will be used as the default value of the :paramref:`_types.Enum.schema` on this object if an explicit value is not otherwise supplied. .. versionchanged:: 1.4.12 :class:`_types.Enum` inherits the :paramref:`_schema.MetaData.schema` parameter of the :class:`_schema.MetaData` object if present, when passed using the :paramref:`_types.Enum.metadata` parameter. :param 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. :param native_enum: Use the database's native ENUM type when available. Defaults to True. When False, uses VARCHAR + check constraint for all backends. When False, the VARCHAR length can be controlled with :paramref:`.Enum.length`; currently "length" is ignored if native_enum=True. :param length: Allows specifying a custom length for the VARCHAR when a non-native enumeration datatype is used. By default it uses the length of the longest value. .. versionchanged:: 2.0.0 The :paramref:`.Enum.length` parameter is used unconditionally for ``VARCHAR`` rendering regardless of the :paramref:`.Enum.native_enum` parameter, for those backends where ``VARCHAR`` is used for enumerated datatypes. :param 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 :class:`_schema.MetaData` collection if passed as :paramref:`_types.Enum.metadata`, for a :class:`_schema.MetaData` that includes the :paramref:`_schema.MetaData.schema` parameter. .. versionchanged:: 1.4.12 :class:`_types.Enum` inherits the :paramref:`_schema.MetaData.schema` parameter of the :class:`_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 :class:`_schema.Table` object if any; when :paramref:`_types.Enum.inherit_schema` is at its default of ``False``, the owning table's schema is **not** used. :param quote: Set explicit quoting preferences for the type's name. :param inherit_schema: When ``True``, the "schema" from the owning :class:`_schema.Table` will be copied to the "schema" attribute of this :class:`.Enum`, replacing whatever value was passed for the ``schema`` attribute. This also takes effect when using the :meth:`_schema.Table.to_metadata` operation. :param 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. .. versionadded:: 1.1.0b2 :param 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. .. versionadded:: 1.2.3 :param 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. .. versionadded:: 1.3.8 :param omit_aliases: A boolean that when true will remove aliases from pep 435 enums. defaults to ``True``. .. versionchanged:: 2.0 This parameter now defaults to True.
sqlalchemy.sql.sqltypes.SchemaType.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.
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) .. versionadded:: 1.4.0b2 .. seealso:: :ref:`metadata_reflection_dbagnostic_types` - describes the use of :meth:`_types.TypeEngine.as_generic` in conjunction with the :meth:`_sql.DDLEvents.column_reflect` event, which is its intended use.
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 :class:`.types.TypeEngine` class in order to provide an alternate :meth:`_types.TypeEngine.bind_processor` method, unless subclassing the :class:`_types.UserDefinedType` class explicitly. To provide alternate behavior for :meth:`_types.TypeEngine.bind_processor`, implement a :class:`_types.TypeDecorator` class and provide an implementation of :meth:`_types.TypeDecorator.process_bind_param`. .. seealso:: :ref:`types_typedecorator` :param 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 :class:`.types.TypeEngine` class in order to provide an alternate :meth:`_types.TypeEngine.literal_processor` method, unless subclassing the :class:`_types.UserDefinedType` class explicitly. To provide alternate behavior for :meth:`_types.TypeEngine.literal_processor`, implement a :class:`_types.TypeDecorator` class and provide an implementation of :meth:`_types.TypeDecorator.process_literal_param`. .. seealso:: :ref:`types_typedecorator`
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 :class:`.types.TypeEngine` class in order to provide an alternate :meth:`_types.TypeEngine.result_processor` method, unless subclassing the :class:`_types.UserDefinedType` class explicitly. To provide alternate behavior for :meth:`_types.TypeEngine.result_processor`, implement a :class:`_types.TypeDecorator` class and provide an implementation of :meth:`_types.TypeDecorator.process_result_value`. .. seealso:: :ref:`types_typedecorator` :param dialect: Dialect instance in use. :param coltype: DBAPI coltype argument received in cursor.description.
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.
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
internal init for :class:`.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.
adjust this type given a literal Python value that will be stored in a bound parameter. Used exclusively by _resolve_value_to_type(). .. versionadded:: 1.4.30 or 2.0 TODO: this should be part of public API .. seealso:: :meth:`.TypeEngine._resolve_for_python_type`
Type[ Any]
, matched_on: _MatchedOnType
, matched_on_flattened: Type[ Any]
) -> Optional[ Enum]
:
(source)
¶
given a Python type (e.g. ``int``, ``str``, etc. ) return an instance of this :class:`.TypeEngine` that's appropriate for this type. An additional argument ``matched_on`` is passed, which indicates an entry from the ``__mro__`` of the given ``python_type`` that more specifically matches how the caller located this :class:`.TypeEngine` object. Such as, if a lookup of some kind links the ``int`` Python type to the :class:`.Integer` SQL type, and the original object was some custom subclass of ``int`` such as ``MyInt(int)``, the arguments passed would be ``(MyInt, int)``. If the given Python type does not correspond to this :class:`.TypeEngine`, or the Python type is otherwise ambiguous, the method should return None. For simple cases, the method checks that the ``python_type`` and ``matched_on`` types are the same (i.e. not a subclass), and returns self; for all other cases, it returns ``None``. The initial use case here is for the ORM to link user-defined Python standard library ``enum.Enum`` classes to the SQLAlchemy :class:`.Enum` SQL type when constructing ORM Declarative mappings. :param python_type: the Python type we want to use :param matched_on: the Python type that led us to choose this particular :class:`.TypeEngine` class, which would be a supertype of ``python_type``. By default, the request is rejected if ``python_type`` doesn't match ``matched_on`` (None is returned). .. versionadded:: 2.0.0b4 TODO: this should be part of public API .. seealso:: :meth:`.TypeEngine._resolve_for_literal`