Last active
June 6, 2019 12:23
-
-
Save Krever/4185e672d1be26971096506d23165a8f to your computer and use it in GitHub Desktop.
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
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