Skip to content

Instantly share code, notes, and snippets.

@Krever
Last active June 6, 2019 12:23
Show Gist options
  • Save Krever/4185e672d1be26971096506d23165a8f to your computer and use it in GitHub Desktop.
Save Krever/4185e672d1be26971096506d23165a8f to your computer and use it in GitHub Desktop.
trait PostgresExtension {
val ctx: QuillCtx
import ctx._
implicit val jsonDecoder: Decoder[JsonObject] =
decoder(
(index, row) =>
io.circe.parser.decode[JsonObject](row.getObject(index).toString) match {
case Left(failure) => throw failure
case Right(value) => value
},
)
implicit val jsonEncoder: Encoder[JsonObject] =
encoder(
java.sql.Types.OTHER,
(index, value, row) => row.setObject(index, Json.fromJsonObject(value).noSpaces, java.sql.Types.OTHER),
)
implicit def enumEncoder[T <: EnumEntry: PGEnum.Name]: Encoder[T] =
encoder(
java.sql.Types.OTHER,
(index, value, row) => {
val pgObj = new PGobject()
pgObj.setType(implicitly[PGEnum.Name[T]].name)
pgObj.setValue(value.entryName)
row.setObject(index, pgObj, Types.OTHER)
},
)
implicit def enumDecoder[T <: EnumEntry: Enum]: Decoder[T] =
decoder((index, row) => {
val enumValue = row.getObject(index).toString
implicitly[Enum[T]].withName(enumValue)
})
implicit val encodeZonedDateTime: MappedEncoding[ZonedDateTime, Date] =
MappedEncoding[ZonedDateTime, Date](z => Date.from(z.toInstant))
implicit val decodeZonedDateTime: MappedEncoding[Date, ZonedDateTime] =
MappedEncoding[Date, ZonedDateTime](d => d.toInstant.atZone(ZoneOffset.UTC))
implicit class JsonObjectOps(json: JsonObject) {
def ~>> = quote((fieldName: String) => infix"$json ->> $fieldName".as[String])
}
// generalizing is harder than it looks
implicit class CastOps[T](t: T) {
def castToText = quote(infix"$t :: text".as[String])
}
}
object PostgresExtension {
trait PGEnum[T <: EnumEntry] { _: Enum[T] =>
def pgEnumName: String
implicit val pgEnumToken: PGEnum.Name[T] = PGEnum.Name(pgEnumName)
}
object PGEnum {
case class Name[T](name: String) extends AnyVal
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment