Mardaunt
Mardaunt

Reputation: 92

Check that the request returned to the database

I have a method that makes a query to the database. I want to understand. How can I check if there are rows in the table that meet my condition?

def getMessage() = {
  val query = messages.filter(_.status === true)
  val action = query.result.head
  val result = db.run(action)
  //val sql = action.statements.head
  val temp = result.map(_.phone)
  Thread.sleep(3000)
  println(temp.toString)
 }

For example, I need an example logic of how the method works.

    def getMessage():String = {
     val query = messages.filter(_.status === true)
     val action = query.result.head
     val result = db.run(action)
     //val sql = action.statements.head
     val temp = result.map(_.phone)
     Thread.sleep(3000)
     
     if (temp != "null") return temp
     else return "null"
 }

Upvotes: 0

Views: 263

Answers (1)

Tim
Tim

Reputation: 27356

db.run returns a Future so you need to check the result when that completes:

db.run(action).onComplete{
  case Success(res) =>
    // Process result in res
  case Failure(e) =>
    // Handle error case
}

You should never Sleep or wait for a Future, so getMessage should return Future[String] and the calling code can handle the result when it is ready.

def getMessage(): Future[String] = {
 val query = messages.filter(_.status === true)
 val action = query.result.head
 
 db.run(action)
}

More generally you need to look at a how Future works and how to modify the results (map), chain multiple Futures (flatMap) or handle multiple Futures as a single Future (Future.sequence).

In general you should keep the processing inside the Future for as long as possible.

Upvotes: 1

Related Questions