Fernando Sanchez (Perraco Labs)
09/07/2024, 8:17 AMenumeration and enumerationByName problematic due to risks associated with changing Enum orders or names. As a workaround, I've implemented a way to store Enums by a stable ID, ensuring data integrity regardless of Enum modifications.
Here's a brief on the workaround I am using:
// Define an enum with an ID property for database storage
enum class EmploymentStatus(override val id: Int) : IEnumWithId {
ONBOARDING(100), ACTIVE(101), IDLE(102), TERMINATED(103);
internal companion object {
private val map: MapInt, EmploymentStatus = EmploymentStatus.values().associateBy(EmploymentStatus::id)
fun fromId(id: Int): EmploymentStatus? = map[id]
}
}
// Interface to ensure enums have an ID property
interface IEnumWithId {
val id: Int
}
// Custom Exposed table function to store enums by their ID.
inline fun <reified T : EnumT> Table.enumerationById(
name: String,
noinline fromId: (Int) -> T?
): ColumnT {
return customEnumeration(
name = name,
sql = "INTEGER",
fromDb = { value -> fromId(value as Int) ?: throw IllegalArgumentException("Unknown enum id: $value") },
toDb = { (it as IEnumWithId).id }
)
}
// Table definition using the custom enum storage method
object EmployeeTable : Table() {
val status: ColumnEmploymentStatus = enumerationById(
name = "status_id",
fromId = EmploymentStatus::fromId
)
}
Does anyone know if Exposed provides a built-in way to handle Enums like this, or is there another established method I should consider?
Thanks