Slick repository functions
Now, our repository needs some functions for more convenient access to the data.
xxxxxxxxxx
def loadProduct(id: ProductId): Future[Seq[(UUID, String, String)]] = {
val program = for {
(p, ns) <- productsTable
.filter(_.id === id)
.join(namesTable)
.on(_.id === _.productId)
} yield (p.id, ns.langCode, ns.name)
dbConfig.db.run(program.result)
}
def loadProducts(): DatabasePublisher[(UUID, String, String)] = {
val program = for {
(p, ns) <- productsTable.join(namesTable)
.on(_.id === _.productId).sortBy(_._1.id)
} yield (p.id, ns.langCode, ns.name)
dbConfig.db.stream(program.result)
}
def saveProduct(p: Product): Future[List[Int]] = {
val cp = productsTable += (p.id)
val program = DBIO.sequence(
cp :: saveTranslations(p).toList
).transactionally
dbConfig.db.run(program)
}
def updateProduct(p: Product): Future[List[Int]] = {
val program = namesTable
.filter(_.productId === p.id)
.delete
.andThen(DBIO.sequence(saveTranslations(p).toList))
.transactionally 33 dbConfig.db.run(program)
}
protected def saveTranslations(p: Product): NonEmptyList[DBIO[Int]] = {
val save = saveTranslation(p.id)(_)
p.names.toNonEmptyList.map(t => save(t))
}
/* Create a query to insert or update a given translation in the database.
* @param id The unique ID of the product.
* @param t The translation to be saved.
* @return A composable sql query for Slick.
*/
protected def saveTranslation(id: ProductId)(t: Translation): DBIO[Int] =
namesTable.insertOrUpdate((id, t.lang, t.name))