All Downloads are FREE. Search and download functionalities are using the official Maven repository.

run.smt.ktest.db.query.impl.util.kt Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
package run.smt.ktest.db.query.impl

import run.smt.ktest.util.reflection.canBeAssignedTo
import java.math.BigDecimal
import java.sql.Date
import java.sql.Timestamp
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime

/**
 * Map SQL value to given java one if it is possible
 */
internal infix fun Any?.coerceTo(type: Class<*>): Any? {
    this?.javaClass ?: return null
    return when (this.javaClass) {
        BigDecimal::class.java -> when {
            type.canBeAssignedTo() -> (this as BigDecimal).toLong()
            type.canBeAssignedTo() -> (this as BigDecimal).toInt()
            else -> this
        }

        Timestamp::class.java -> when {
            type.canBeAssignedTo() -> java.util.Date((this as Timestamp).time)
            type.canBeAssignedTo() -> Date((this as Timestamp).time)
            type.canBeAssignedTo() -> (this as Timestamp).toLocalDateTime()
            type.canBeAssignedTo() -> (this as Timestamp).toLocalDateTime().toLocalDate()
            type.canBeAssignedTo() -> (this as Timestamp).toLocalDateTime().toLocalTime()
            else -> this
        }

        Date::class.java -> when {
            type.canBeAssignedTo() -> java.util.Date((this as Date).time)
            type.canBeAssignedTo() -> (this as Date).toLocalDate()
            else -> this
        }

        else -> this
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy