Skip to content

Fix JsonColumnType #1

Open
Open
@DarthRevanXX

Description

@DarthRevanXX

The bug when you are reading from database null give you error so cannot deserialize, updated version

fun <T : Any> Table.json(name: String, serialize: (Any) -> String, deserialize: (String) -> Any): Column<T> =
    registerColumn(name, JsonColumnType(serialize, deserialize))

class JsonColumnType(
    private val serialize: (Any) -> String,
    private val deserialize: (String) -> Any
) : ColumnType() {
    override fun sqlType() = "JSON"

    override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
        super.setParameter(
            stmt,
            index,
            value.let {
                PGobject().apply {
                    this.type = sqlType()
                    this.value = value as String?
                }
            }
        )
    }

    override fun valueFromDB(value: Any): Any {
        if (value is PGobject) {
            val jsonValue = value.value
            if (!jsonValue.isNullOrBlank()) {
                return deserialize(jsonValue)
            }
        }
        return value
    }

    override fun valueToString(value: Any?): String {
        if (value == null) {
            return "NULL"
        }
        return "'${serialize(value)}'"
    }

    override fun readObject(rs: ResultSet, index: Int): Any? {
        val stringValue = rs.getString(index)
        return if (stringValue != null) {
            deserialize(stringValue)
        } else {
            null
        }
    }

    override fun notNullValueToDB(value: Any): String = serialize(value)
}

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