sql >> Database teknologi >  >> RDS >> PostgreSQL

R2DBC og enum (PostgreSQL)

Testet med org.springframework.data:spring-data-r2dbc:1.0.0.RELEASE og io.r2dbc:r2dbc-postgresql:0.8.1.RELEASE .

Kotlin-version.

  1. Definer en enum-klasse

    enum class Mood {
        UNKNOWN,
        HAPPY,
        SAD
    }
    
  2. Opret en brugerdefineret codec

    class MoodCodec(private val allocator: ByteBufAllocator) :  Codec<Mood> {
        override fun canEncodeNull(type: Class<*>): Boolean = false
    
        override fun canEncode(value: Any): Boolean = value is Mood
    
        override fun encode(value: Any): Parameter {
            return Parameter(Format.FORMAT_TEXT, oid) {
                ByteBufUtils.encode(allocator, (value as Mood).name)
            }
        }
    
        override fun canDecode(dataType: Int, format: Format, type: Class<*>): Boolean = dataType == oid
    
        override fun decode(buffer: ByteBuf?, dataType: Int, format: Format, type: Class<out Mood>): Mood? {
            buffer ?: return null
            return Mood.valueOf(ByteBufUtils.decode(buffer))
        }
    
        override fun type(): Class<*> = Mood::class.java
    
        override fun encodeNull(): Parameter =
            Parameter(Format.FORMAT_TEXT, oid, Parameter.NULL_VALUE)
    
        companion object {
            // Get form `select oid from pg_type where typname = 'mood'`
            private const val oid = YOUR_ENUM_OID
        }
    }
    
  3. Registrer codec'et

    Du skal muligvis ændre runtimeOnly("io.r2dbc:r2dbc-postgresql") til implementation("io.r2dbc:r2dbc-postgresql")

    @Configuration
    @EnableR2dbcRepositories
    class AppConfig : AbstractR2dbcConfiguration() {
        override fun connectionFactory(): ConnectionFactory = PostgresqlConnectionConfiguration.builder()
            .port(5432) // Add your config here.
            .codecRegistrar { _, allocator, registry ->
                registry.addFirst(MoodCodec(allocator))
                Mono.empty()
            }.build()
            .let { PostgresqlConnectionFactory(it) }
    }
    



  1. mysql-tabel med 40+ kolonner

  2. giv SELECT adgang til v$session til andre brugere

  3. Hvordan formaterer man en NUMBER kolonne i Oracle?

  4. Er det bedre at lave en equi join i fra-klausulen eller hvor-klausulen