Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix JsonColumnType #1

Open
DarthRevanXX opened this issue Jun 9, 2023 · 0 comments
Open

Fix JsonColumnType #1

DarthRevanXX opened this issue Jun 9, 2023 · 0 comments

Comments

@DarthRevanXX
Copy link

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant