Skip to content

Automatic unwrapping of value classes when they wrap over types that are "automatically wrapped" by terpal-sql #18

Description

@cies

Would it be possible (without using kotlin-reflect)?

All the manual unwrapping (outside of the SQL query string) or adding ${Param.withSer(productId, ProductIdSerializer)} look overly boilerplaty.

Activity

  1. cies commented on Oct 22, 2025

    @cies
    Author

    Also when deserializing I now do the very verbose:

    object ProductIdSerializer : KSerializer<ProductId> {
      override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ProductId", PrimitiveKind.LONG)
      override fun serialize(encoder: Encoder, value: ProductId) = encoder.encodeLong(value.value)
      override fun deserialize(decoder: Decoder) = ProductId(decoder.decodeLong())
    }
    
    @Serializable
    data class Product(
    
      @Serializable(with = ProductIdSerializer::class)
      val id: ProductId,
    
      val createdAt: DbInstant,
    
      val updatedAt: DbInstant,
    
      \\ ...
    )
  2. cies commented on Oct 22, 2025

    @cies
    Author

    It seems that kotlinx.serialization handles this well (at least with JSON it does):

    import kotlinx.serialization.Serializable
    import kotlinx.serialization.json.Json
    
    @JvmInline
    @Serializable
    value class ProductId(val value: Long)
    
    @Serializable
    data class ProductDto(
        val id: ProductId,
        val name: String
    )
    
    fun main() {
        val d = Json.decodeFromString<ProductDto>("""{"id": 1000, "name": "qweqw"}""")
        println(d) // ProductDto(id=ProductId(value=1000), name=qweqw)
        
        val s = Json.encodeToString(d)
        println(s) // {"id":1000,"name":"qweqw"}
    }
  3. deusaquilus commented on Nov 13, 2025

    @deusaquilus
    Member

    There a a few ways to get rid of the boilerplate here. The first way is to use contextual serialization and use Param.contextual. If you want even less boilerplate you can define a param-wrapper inside of the package (io.exoquery.sql). So something like:

    package io.exoquery.sql
    
    fun SqlInterpolator.wrap(value: ProductId?): Param<ProductId> = Param.withSer(productId, ProductIdSerializer)

    Give that a shot and see if it works.

    (P.S. io.exoquery.sql will eventually be renamed to io.exoquery.lang)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions