From e2c19024a21d51bd49697a3642e30d5d30c73a22 Mon Sep 17 00:00:00 2001 From: Guntis Smaukstelis Date: Sun, 22 Oct 2023 21:19:11 +0300 Subject: [PATCH] Select from table in postgres --- src/main/scala/db/Postgres.scala | 33 +++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/main/scala/db/Postgres.scala b/src/main/scala/db/Postgres.scala index 3dae26c..de9060c 100644 --- a/src/main/scala/db/Postgres.scala +++ b/src/main/scala/db/Postgres.scala @@ -1,5 +1,6 @@ package db +import cats.data.NonEmptyList import cats.effect._ import cats.effect.unsafe.implicits.global import doobie._ @@ -62,6 +63,35 @@ object Postgres { } yield result } + def selectWeatherTable(xa: Transactor[IO]): IO[List[(String, Option[Double])]] = { + val formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmm") + val rigaZone = ZoneId.of("Europe/Riga") + val from = LocalDateTime.parse("20230516_0100", formatter).atZone(rigaZone) + val to = LocalDateTime.parse("20230516_1500", formatter).atZone(rigaZone) + val citiesNel = NonEmptyList.of("Rīga", "Rēzekne") + val granularity = "HOUR" // "HOUR", "DAY", "MONTH", "YEAR" + val columnName = "tempMin" + + val baseQuery = + fr""" + SELECT + city, + MIN(""" ++ Fragment.const(columnName) ++ + fr""") AS tempMin + FROM weather + WHERE + """ ++ Fragments.in(fr"city", citiesNel) ++ fr""" + AND dateTime BETWEEN $from AND $to + AND """ ++ Fragment.const(columnName) ++fr""" IS NOT NULL + GROUP BY city, EXTRACT(""" ++ Fragment.const(granularity) ++ fr""" FROM dateTime) + """ + + baseQuery + .query[(String, Option[Double])] + .to[List] + .transact(xa) + } + def dropWeatherTable(implicit xa: Transactor[IO]): IO[Int] = { for { dropTableSql <- getResourceContent("/db/drop_weather_table.sql") @@ -73,7 +103,8 @@ object Postgres { val xa = transactor[IO] // val result = createWeatherTable(xa).unsafeRunSync() - val result = insertInWeatherTable(xa).unsafeRunSync() +// val result = insertInWeatherTable(xa).unsafeRunSync() + val result = selectWeatherTable(xa).unsafeRunSync() // val result = dropWeatherTable(xa).unsafeRunSync() println(s"result: $result")