Search code examples
scaladatasourceslick

How to get values from query result in slick


I tried to use the Slick(3.0.2) to operate database in my project with scala. Here is my part of code

val query = table.filter(_.username === "LeoAshin").map { user => (user.username, user.password, user.role, user.delFlg) }

val f = db.run(query.result)

How can I read the data from "f" I have tried google the solution many times, but no answer can solved my confuse Thanks a lot


Solution

  • Type of query.result is DBIO. When you call db.run, it turns into Future.

    If you want to print the data, use

    import scala.concurrent.ExecutionContext.Implicits.global
    f.foreach(println)
    

    To continue working with data, use f.map { case (username, password, role, delFlg) ⇒ ... }

    If you want to block on the Future and get the result (if you're playing around in REPL for example), use something like

    import scala.concurrent.Await
    import scala.concurrent.duration._
    Await.result(f, 1.second)
    

    Bear in mind, this is not what you want to do in production code — blocking on Futures is a bad practice.

    I generally recommend learning about Scala core types and Futures specifically. Slick "responsibility" ends when you call db.run.