DB connection and transactor as separate class with config and IO

This commit is contained in:
Guntis Smaukstelis
2023-10-24 11:59:23 +03:00
parent 47be3bf385
commit 6819aa3166
4 changed files with 35 additions and 14 deletions
+27
View File
@@ -0,0 +1,27 @@
package db
import cats.effect.{Async, IO}
import doobie.Transactor
import pureconfig._
import pureconfig.generic.auto._
import pureconfig.error.ConfigReaderFailures
case class PostgresConfig(username: String, password: String, url: String)
object DBConnection {
private def loadPostgresConfig: Either[ConfigReaderFailures, PostgresConfig] = {
ConfigSource.resources("postgres.conf").load[PostgresConfig]
}
def transactor[F[_] : Async]: IO[Transactor[F]] = {
loadPostgresConfig match {
case Right(config) => IO(Transactor.fromDriverManager[F](
"org.postgresql.Driver",
config.url,
config.username,
config.password
))
case Left(errors) => IO.raiseError(new RuntimeException(s"Failed to load config: $errors"))
}
}
}
+1 -1
View File
@@ -75,7 +75,7 @@ class PostgresService(transactor: Transactor[IO], log: Logger[IO]) extends DataS
}
}
def createWeatherTable(): IO[Int] = {
def createWeatherTable: IO[Int] = {
for {
createTableSql <- getResourceContent("/db/create_weather_table.sql")
result <- Update0(createTableSql, None).run.transact(transactor)