-
-
Save tpolecat/7731262f0028b7cd4b3872bf8f98a9d4 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
// Copyright (c) 2018-2020 by Rob Norris | |
// This software is licensed under the MIT License (MIT). | |
// For more information see LICENSE or https://opensource.org/licenses/MIT | |
package example | |
import cats.effect._ | |
import natchez.Trace.Implicits.noop | |
import scala.concurrent._ | |
import scala.concurrent.duration.Duration | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import skunk.codec.numeric.{ int4, float8 } | |
import skunk.implicits._ | |
import skunk.Session | |
object FutureExample { | |
trait Math { | |
def add(a: Int, b: Int): Future[Int] | |
def sqrt(a: Double): Future[Double] | |
def shutdown(): Future[Unit] | |
} | |
object Math { | |
object Statements { | |
val add = sql"select $int4 + $int4".query(int4) | |
val sqrt = sql"select sqrt($float8)".query(float8) | |
} | |
def newInstance()(implicit ec: ExecutionContext): Future[Math] = { | |
implicit val ioContextShift = IO.contextShift(ec) | |
Session.pooled[IO]( | |
host = "localhost", | |
port = 5432, | |
user = "jimmy", | |
database = "world", | |
password = Some("banana"), | |
max = 10, | |
debug = true, | |
).allocated.map { case (session, free) => | |
new Math { | |
def add(a: Int, b: Int): Future[Int] = | |
session.use(_.prepare(Statements.add).use(_.unique(a ~ b))).unsafeToFuture() | |
def sqrt(a: Double): Future[Double] = | |
session.use(_.prepare(Statements.sqrt).use(_.unique(a))).unsafeToFuture() | |
def shutdown(): Future[Unit] = | |
free.unsafeToFuture() | |
} | |
} .unsafeToFuture() | |
} | |
} | |
def futureMain(): Future[Unit] = | |
for { | |
m <- Math.newInstance() | |
n <- m.add(42, 71) | |
d <- m.sqrt(2) | |
d2 <- m.sqrt(42) | |
_ <- Future(println(s"The answers were $n and $d and $d2")) | |
_ <- m.shutdown() | |
} yield () | |
def main(args: Array[String]): Unit = | |
Await.result(futureMain(), Duration.Inf) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment