Check if element exists in database using Slick 3 and Play
Asked Answered
P

1

6

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?

Pfeffer answered 10/11, 2015 at 10:33 Comment(2)
Check out Essential Slick. This book covers Slick 2 and 3. I used it to ramp up on Slick - well-written and solid examples.Backer
Thanks. Sample looks very informative and helpfulPfeffer
D
20

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.

Deoxyribose answered 10/11, 2015 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.