nullable @SqlJsonValue and json 'null'
In a scenario where we try to deserialize a @SqlJsonValue to a nullable field, where the database row contains the jsonb value
'null', (i.e. not SQL-null but json-null), the deserialization process crashes.
data class NullableExample(val id: Int, @SqlJsonValue val value: MyPersonJson?)
Sql("""INSERT INTO JsonbExample (id, value) VALUES (1, 'null')""").action().runOn(ctx)
Sql("SELECT id, value FROM JsonbExample").queryOf<NullableExample>().runOn(ctx)
Unexpected JSON token at offset 0: Expected start of the object '{', but had 'n' instead at path: $
JSON input: null
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 0: Expected start of the object '{', but had 'n' instead at path: $
JSON input: null
It appears that in RowDecoder, after validNullOrElse check the result is passed to the decoder; however at some point in the call stack the nullability of the target type is lost.
A minimal example of what is happening at kotlinx.serialization level:
Json.decodeFromString<JsonSpecData.A.MyPerson?>("null") shouldBe null // ok
Json.decodeFromString<JsonSpecData.A.MyPerson>("null") shouldBe null // exception as above
I was unable to figure out where this happens, so no fix is included - however a branch with a test for this case can be found here: https://github.com/ExoQuery/terpal-sql/compare/main...arvearve:terpal-sql:json-nullable
I see. @SqlJsonValue takes a slightly different code path. Let me have a closer look.