Vakindu
Vakindu

Reputation: 815

Scala Akka HTTP Postgresql how to efficiently insert a case class's data into different tables

I’m building a Scala application using Akka HTTP, SBT, PgSQL and doobie. The app’s API receives JSON data formatted as a Table case class.

The data should then be inserted into a PostgreSql database. The database has width, height, area, and tables as different tables. The aim is to store each of the corresponding case class fields into their own tables in the PgSQL table.

Is the code below the best way to do it, or is there a more efficient way of achieving it? Is there a way of optimizing the 4 different queries into one query?

case class Width(id: String, width: Int)
case class Height(id: String, height: Long)
case class Area(id: String, area: Long)
case class Table(id: String, width:Long, height: Height, area:Area)

def dbCreate(xa: pgConfig, table: Table): Unit = {

val widthId = sql”INSERT INTO widths (id, width) VALUES ($table.id}, ${table.width})”
.update
.withUniqueGeneratedKeys[Int](“id”)
.transact(xa)
.unsafeRunSync

val heightId = sql”INSERT INTO heights (id, height) VALUES (${table.id}, ${table.height.height})”
.update
.withUniqueGeneratedKeys[Int](“id”)
.transact(xa)
.unsafeRunSync

val areaId = sql”INSERT INTO areas (id, area) VALUES (${table.id}, ${table.area.area})”
.update
.withUniqueGeneratedKeys[Int](“id”)
.transact(xa)
.unsafeRunSync

sql”INSERT INTO tables (id, width_id, height_id, area_id) VALUES (${table.id}, $widthId, $heightId, $areaId)”
.update
.transact(xa)
.unsafeRunSync
}

Upvotes: 0

Views: 62

Answers (0)

Related Questions