I'm trying to map a kotlin enum class to an actual...
# komapper
s
I'm trying to map a kotlin enum class to an actual postgres enum type (https://www.komapper.org/docs/reference/annotation-processing/#komapperenumstrategy), but what is the R2dbcUserDefinedDataType supposed to look like for that? What should the
r2dbcType
be?
Copy code
internal class TopicType : R2dbcUserDefinedDataType<Topic> {
    override val r2dbcType: Class<String> = String::class.java

    override fun getValue(row: Row, index: Int): Topic? =
        row.get(index, String::class.java)?.let { Topic.valueOf(it) }

    override fun getValue(row: Row, columnLabel: String): Topic? =
        row.get(columnLabel, String::class.java)?.let { Topic.valueOf(it) }

    override fun setValue(
        statement: Statement,
        index: Int,
        value: Topic,
    ) {
        statement.bind(index, value.name)
    }

    override fun setValue(
        statement: Statement,
        name: String,
        value: Topic,
    ) {
        statement.bind(name, value.name)
    }

    override fun toString(value: Topic): String =
        value.name

    override val name: String = "topic"
    override val type: KType = typeOf<Topic>()
}
If I use String it obviously fails with
column "topic" is of type public.topic but expression is of type character varying
. But I don't know what type I should use instead
t
To map a Kotlin enum class to a PostgreSQL enum type, you need to use the features provided by the PostgreSQL R2DBC driver. Komapper’s tests already verify this setup, so the following code should serve as a helpful reference. We will use this enum class as the sample: https://github.com/komapper/komapper/blob/v5.7.0/integration-test-r2dbc/src/main/kotlin/integration/r2dbc/MoodType.kt First, register the Kotlin enum type with the R2DBC driver: https://github.com/komapper/komapper/blob/v5.7.0/integration-test-r2dbc/src/postgresql/kotlin/integration/r2dbc/postgresql/PosgreSqlCodecRegistrar.kt https://github.com/komapper/komapper/blob/v5.7.0/integration-test-r2dbc/src/main/resources/META-INF/services/io.r2dbc.postgresql.extension.Extension Next, implement and register
R2dbcUserDefinedDataType
as follows: https://github.com/komapper/komapper/blob/v5.7.0/integration-test-r2dbc/src/main/kotlin/integration/r2dbc/MoodType.kt https://github.com/komapper/komapper/blob/v5.7.0/integration-test-r2dbc/src/main/resources/META-INF/services/org.komapper.r2dbc.spi.R2dbcUserDefinedDataType With that, the mapping setup is complete. Here is an example of how to use it: https://github.com/komapper/komapper/blob/v5.7.0/integration-test-core/src/main/kotlin/integration/core/EntitiesDataType.kt#L118-L125 https://github.com/komapper/komapper/blob/v5.7.0/integration-test-r2dbc/src/test/kotlin/integration/r2dbc/R2dbcDataTypeTest.kt#L1014-L1040
What should the r2dbcType be?
In your case, please specify
Topic::class.javaObjectType
.
s
Thanks for the detailed instructions, works perfectly now!
👍 1