JetBrains / Exposed

Kotlin SQL Framework
http://jetbrains.github.io/Exposed/
Apache License 2.0
8.39k stars 693 forks source link

Reduce customEnumeration boilerplate #751

Open Aditya94A opened 4 years ago

Aditya94A commented 4 years ago

I was able to reduce boilerplate to something like

val isDeleted = customEnumeration(
        "isDeleted",
        getEnumSql<DeleteStatus>(),
        getEnumFunc<DeleteStatus>(),
        getEnumToStringFunc<DeleteStatus>()

or even better this:

val isDeleted = getEnum<DeleteStatus>("isDeleted")

with the following extension functions

inline fun <reified T : Enum<T>> getEnumSql() =
    enumValues<T>().joinToString(
        prefix = "ENUM(",
        postfix = ")",
        transform = { "'${it.name}'" })

inline fun <reified T : Enum<T>> getEnumFunc(): ((Any) -> T) = { enumValueOf<T>(it as String) }

inline fun <reified T : Enum<T>> getEnumToStringFunc(): ((T) -> String) = { it.name }

inline fun <reified T : Enum<T>> Table.getEnum(name: String) =
    customEnumeration(
        name, getEnumSql<T>(),
        getEnumFunc<T>(), getEnumToStringFunc()
    )

Would be great if we can provide a customStringEnumeration or something like such helper method within the library. Let me know if this looks good,I'll send a PR (or let me know if there could be any issues with this strategy)

Tapac commented 4 years ago

Some databases like a postgresql require additional actions like creating an enum type and also require special types (PgEnum) to be provided for a statement. Another could return Int value from a database (H2).

If you could cover all cases in a generic way it will be great.