Skip to content

Commit

Permalink
Add datetime parsing functions to ResultSet.Row.Column
Browse files Browse the repository at this point in the history
Introduced functions to parse `LocalDate`, `LocalTime`, `LocalDateTime`, `Instant`, and `DateTimePeriod` from `ResultSet.Row.Column`. Also updated `build.gradle.kts` to include `kotlinx.datetime` library dependency.
  • Loading branch information
smyrgeorge committed Oct 6, 2024
1 parent da86c3b commit 29305df
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions sqlx4k/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ kotlin {
val nativeMain by getting {
dependencies {
api(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.datetime)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ package io.github.smyrgeorge.sqlx4k.impl.extensions

import io.github.smyrgeorge.sqlx4k.ResultSet
import io.github.smyrgeorge.sqlx4k.SQLError
import kotlinx.datetime.DateTimePeriod
import kotlinx.datetime.Instant
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid

Expand Down Expand Up @@ -37,3 +42,15 @@ inline fun <reified T : Enum<T>> String.toEnum(): T =
} catch (e: Exception) {
SQLError(SQLError.Code.CannotDecodeEnumValue, "Cannot decode enum value '$this'.").ex()
}

fun ResultSet.Row.Column.asLocalDate(): LocalDate = LocalDate.parse(asString())
fun ResultSet.Row.Column.asLocalDateOrNull(): LocalDate? = asStringOrNull()?.let { LocalDate.parse(it) }
fun ResultSet.Row.Column.asLocalTime(): LocalTime = LocalTime.parse(asString())
fun ResultSet.Row.Column.asLocalTimeOrNull(): LocalTime? = asStringOrNull()?.let { LocalTime.parse(it) }
private fun String.fixTime(): String = replace(" ", "T")
fun ResultSet.Row.Column.asLocalDateTime(): LocalDateTime = LocalDateTime.parse(asString().fixTime())
fun ResultSet.Row.Column.asLocalDateTimeOrNull(): LocalDateTime? = asStringOrNull()?.let { LocalDateTime.parse(it.fixTime()) }
fun ResultSet.Row.Column.asInstant(): Instant = Instant.parse(asString())
fun ResultSet.Row.Column.asInstantOrNull(): Instant? = asStringOrNull()?.let { Instant.parse(it) }
fun ResultSet.Row.Column.asDateTimePeriod(): DateTimePeriod = DateTimePeriod.parse(asString())
fun ResultSet.Row.Column.asDateTimePeriodOrNull(): DateTimePeriod? = asStringOrNull()?.let { DateTimePeriod.parse(it) }

0 comments on commit 29305df

Please sign in to comment.