Enumeration
Exposed provides several ways to work with enum values in your database tables. You can store enum values either by their ordinal values or by their names, and there's also support for database-specific enum types. This flexibility allows you to choose the most appropriate storage method for your use case.
Supported types
To create an enumeration column, use one of the following functions:
enumeration()Maps to database
INT. Stores enum values using their ordinal values.val enumOrdinal = enumeration("enumOrdinal", Foo::class)enumerationByName()Maps to database
VARCHAR. Stores enum values using their names.val enumName = enumerationByName("enumName", ENUM_NAME_COLUMN_LENGTH, Foo::class)customEnumeration()Used for working with database-specific enum types. Supported by MySQL, PostgreSQL, and H2 databases.
Basic usage
Here's how to use enumeration types in a table definition:
To store enumeration data:
Custom enumeration
Some databases, such as MySQL, PostgreSQL, and H2, support explicit enumeration types. Because keeping such columns in sync with Kotlin enumerations using only JDBC metadata could be a challenge, Exposed doesn't provide a possibility to manage such columns in an automatic way, but that doesn't mean that you can't use such column types.
To work with enum database types, use the customEnumeration() function in one of the following ways:
Use an existing column
When using an existing enum column from your table, the sql parameter in .customEnumeration() can be left as null.
As a JDBC driver can provide/expect specific classes for enum types, you must also provide from/to transformation functions for them when defining a custom enumeration:
Create a new ENUM column
With Exposed, you can also create a new ENUM column by providing the raw definition SQL to the sql parameter in .customEnumeration():
PostgreSQL
PostgreSQL requires that an enum is defined as a separate type, so you have to create it before creating your table. This differs from some other databases where enums can be defined inline within a table definition.
JDBC
When using JDBC, the PostgreSQL driver returns PGobject instances for enum values. As such, a PGobject with its type manually set to the enum type must be used for the toDb parameter. You'll need a helper class like the following:
Example enum and table mapping:
R2DBC
When using R2DBC, you must register the enum codec when configuring your connection. This is done during the R2dbcDatabase.connect() step by providing a PostgreSQL-specific connection factory that uses PostgresqlConnectionConfiguration.builder() with a codecRegistrar():
With the codec registered, the table column mapping looks like this: