Created
July 2, 2019 14:01
-
-
Save mdedetrich/0d0890614add98992440a8c664147ccd to your computer and use it in GitHub Desktop.
Common encodings for Postgres Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.OffsetDateTime | |
import enumeratum._ | |
import io.circe.Json | |
import io.getquill.context.jdbc.PostgresJdbcContextBase | |
import org.postgresql.util.PGobject | |
trait PostgresEncodings { | |
val ctx: PostgresJdbcContextBase[_] | |
import ctx._ | |
implicit val jsonEncoder: Encoder[Json] = | |
encoder( | |
java.sql.Types.OTHER, | |
(index, value, row) => row.setObject(index, value.noSpaces, java.sql.Types.OTHER) | |
) | |
implicit val jsonDecoder: Decoder[Json] = | |
decoder( | |
(index, row) => | |
io.circe.parser.decode[Json](row.getObject(index).toString) match { | |
case Left(failure) => throw failure | |
case Right(value) => value | |
} | |
) | |
// Taken from https://jdbc.postgresql.org/documentation/head/8-date-time.html | |
implicit val encodeOffsetDateTime: Encoder[OffsetDateTime] = | |
encoder( | |
java.sql.Types.OTHER, | |
(index, value, row) => row.setObject(index, value) | |
) | |
implicit val decodeOffsetDateTime: Decoder[OffsetDateTime] = | |
decoder( | |
(index, row) => row.getObject(index, classOf[OffsetDateTime]) | |
) | |
def enumEncoder[T <: EnumEntry](enumName: String): Encoder[T] = | |
encoder( | |
java.sql.Types.OTHER, | |
(index, value, row) => { | |
val pgObj = new PGobject() | |
pgObj.setType(enumName) | |
pgObj.setValue(value.entryName) | |
row.setObject(index, pgObj, java.sql.Types.OTHER) | |
} | |
) | |
def enumDecoder[T <: EnumEntry](implicit enum: Enum[T]): Decoder[T] = | |
decoder((index, row) => { | |
val enumValue = row.getObject(index).toString | |
enum.withName(enumValue) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment