Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slick return single result

Tags:

scala

slick

this slick query works correctly:

val db = Database.forConfig("slick-mysql")
val query: SqlStreamingAction[Vector[Company], Company, Effect] = sql"""select * from company""".as[Company]
val futureResult: Future[Vector[Company]] = db.run(query)

However, how can I get a single row (Future[Company])?

val id = 1
val query = sql"""select * from company where id=$id""".as[Company] // make it a single value (head or headOption)
val futureResult: Future[Company] = db.run(query)

I am aware that I could use futureResult.map(_.headOption). But I wonder if slick allows to specify a single result (as i anorm)

like image 787
David Portabella Avatar asked Oct 23 '25 23:10

David Portabella


1 Answers

Try calling .headOption on the db action itself like so

sql"""select * from company where id=$id""".as[Company].headOption

Now db.run(query) returns Future[Option[Company]]. Technically .head is also possible which would return Future[Company] however it is unsafe.

Consider writing queries in Scala instead of plain SQL, for example, it should be possible to rewrite plain sql like so

 db.run {
    companies
      .filter(_.id === id)
      .take(1)
      .result
      .headOption
  }

where companies is TableQuery.

like image 153
Mario Galic Avatar answered Oct 26 '25 17:10

Mario Galic