Check if an item exists in the database using Slick 3 and Play

I'm new to Scala, Slick, and Play, but I'm trying to make a little maintenance using this technology. I have a problem with the correct way to check for an element in the database.

Playback action - just see the output in the browser:

val id = 5
val name = "xx"
def show(): Action async {
    dao.isExist(id,name).map(c => Ok(c.toString)
}

Tao

User = TableQuery[UserRow]
def isExist(id:Int, name:String) = {
val res = db.run(User.filter(i => (i.id === id || i.name === name)).result)}
// I would like to do something like 
if (res.length > 0) true else false 
// or since action is async to return future.
res match {
  case 0 => Future(true)
  case _ => Future(false)
}
// but this doesnt compile. I came up with
val trueRes = Await.result(res, Duratin.Inf)
// which in not async Action do what I want. 

I think I should avoid using Await, but in this case I need to do some action based on the fact that the DB will return. Could you advise what would be the best model for resolving this matter?

+4
source share
1 answer

: , Future.map ( flatMap, ) a Future .

, :

def exists(id : Int, name : String) : Future[Boolean] = 
    db.run(User.filter(i => i.id === id || i.name === name).exists.result)

- SELECT 1 ... WHERE EXISTS COUNT(*) , , SELECT * .

+13

Source: https://habr.com/ru/post/1615212/


All Articles