Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element exists in database using Slick 3 and Play

I am new to Scala, Slick and Play but I am trying to do some little service using this technology. I have a problem with a proper way how to check existence of item in DB.

Play action -- simple to see output in Browser:

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

Dao

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 that I should avoid using Await, but in this case I need to make some action based on what DB will return. Could you advice what would be the best pattern to address this case?

like image 961
leemonix Avatar asked Nov 10 '15 10:11

leemonix


1 Answers

First of all: if you want to transform the result of asynchronous operation, you should use Future.map (or flatMap if you want to nest async operations) and return a Future to the controller.

Other than that, your whole method can be refactored to:

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

which should translate to something along the lines of SELECT 1 ... WHERE EXISTS instead of COUNT(*) or, even worse, in your particular case it would be SELECT * with client-side length check.

like image 192
Patryk Ćwiek Avatar answered Sep 28 '22 05:09

Patryk Ćwiek