Skip to main content

Enums

Typr generates type-safe enum types from your database schema. Support varies by database.

Database Support​

DatabaseNative EnumsInline EnumsOpen Enums
PostgreSQLCREATE TYPE ... AS ENUM-Table-based
DuckDBCREATE TYPE ... AS ENUM-Table-based
MariaDB/MySQL-ENUM('a','b') column typeTable-based
Oracle--Table-based
SQL Server--Table-based

Native Enums (PostgreSQL, DuckDB)​

PostgreSQL and DuckDB support named enum types at the database level:

CREATE TYPE order_status AS ENUM (
'pending', 'confirmed', 'processing',
'shipped', 'delivered', 'cancelled', 'refunded'
);

Typr generates a type-safe enum:

OrderStatus
public enum OrderStatus {
pending("pending"),
confirmed("confirmed"),
processing("processing"),
shipped("shipped"),
delivered("delivered"),
cancelled("cancelled"),
refunded("refunded");
final java.lang.String value;

public java.lang.String value() {
return value;
}

OrderStatus(java.lang.String value) {
this.value = value;
}

public static final java.lang.String Names =
java.util.Arrays.stream(OrderStatus.values())
.map(x -> x.value)
.collect(java.util.stream.Collectors.joining(", "));
public static final java.util.Map<java.lang.String, OrderStatus> ByName =
java.util.Arrays.stream(OrderStatus.values())
.collect(java.util.stream.Collectors.toMap(n -> n.value, n -> n));

public static PgType<List<OrderStatus>> pgTypeArray =
PgTypes.text
.array()
.to(
Bijection.of(
xs -> xs.stream().map(OrderStatus::force).toList(),
xs -> xs.stream().map(OrderStatus::value).toList()))
.renamedDropPrecision("showcase.order_status");
;
public static PgType<OrderStatus> pgType =
PgTypes.text
.to(Bijection.of(OrderStatus::force, OrderStatus::value))
.renamedDropPrecision("showcase.order_status");
;

public static OrderStatus force(java.lang.String str) {
if (ByName.containsKey(str)) {
return ByName.get(str);
} else {
throw new RuntimeException(
"'" + str + "' does not match any of the following legal values: " + Names);
}
}
}

The generated enum includes:

  • Type-safe values that the compiler validates
  • force() method for parsing strings (throws on invalid values)
  • Database type definitions for reading/writing

Inline Enums (MariaDB/MySQL)​

MariaDB defines enums inline in the column definition rather than as named types:

CREATE TABLE customer_order (
status ENUM('pending', 'confirmed', 'processing',
'shipped', 'delivered', 'cancelled', 'refunded')
);

Since inline enums don't have a schema-level name, Typr maps them to String. The allowed values are still enforced by the database, but there's no compile-time type checking.

No Native Enums (Oracle, SQL Server, DB2)​

Oracle, SQL Server, and DB2 do not have native enum types. Common alternatives:

  • CHECK constraints on string columns (validated by database, mapped to String)
  • Lookup tables with foreign key constraints (see Open Enums)
  • Application-level enums using wrapper types

For type-safe enums in these databases, consider using Open Enums with a lookup table.