Functions for Data Access
Learn how to implement functions to manipulate data and carry out main service.
We'll cover the following...
Slick repository functions
Now, our repository needs some functions for more convenient access to the data.
Press + to interact
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).transactionallydbConfig.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))
The saveTranslations
and saveTranslation
functions are helpers that enable us to create and load queries that we can compose. They are used in the saveProduct
and updateProduct
functions to create a list of queries that are executed as bulk, while the call to transactionally
in line ...