Slick 2 aggregation - how to get a scalar result?
Asked Answered
C

1

1

I have a table with an Int column TIME in it:

def time = column[Int]("TIME")

The table is mapped to a custom type. I want to find a maximum time value, i.e. to perform a simple aggregation. The example in the documentation seems easy enough:

val q = coffees.map(_.price)
val q1 = q.min
val q2 = q.max

However, when I do this, the type of q1 and q2 is Column[Option[Int]]. I can perform a get or getOrElse on this to get a result of type Column[Int] (even this seems somewhat surprising to me - is get a member of Column, or is the value converted from Option[Int] to Int and then wrapped to Column again? Why?), but I am unable to use the scalar value, when I attempt to assign it to Int, I get an error message saying:

type mismatch;
 found   : scala.slick.lifted.Column[Int]
 required: Int

How can I get the scala value from the aggregated query?

Cytologist answered 23/5, 2014 at 13:47 Comment(1)
Following questions seems to be solving the same problem https://mcmap.net/q/540765/-how-to-count-in-slick-2-0 #20278458Cytologist
A
3

My guess is that you are not calling the invoker that's the reason why you get a Column object. Try this:

val q1 = q.min.run

Should return an Option[Int] and then you can get or getOrElse.

Amontillado answered 23/5, 2014 at 14:17 Comment(5)
Great. run is what I was missing. I was trying list or first, like in normal queries, but that did not work. Still, run seems to be returning Option[Int], therefore run.get or run.getOrElse seems to be necessary.Cytologist
Ah right, it depends if your column is nullable the query returns an Option, if not you get directly the value, in your case probably it is nullable and you need to get or getOrElse, I'll edit my answer.Amontillado
I do not think my column is nullable (def added into the question). Perhaps the aggregation needs to cope with a situation there are no records at all, in which case there can be no aggregate?Cytologist
Exactly. That's the reason Suma!Metallist
@Cytologist thanks for the edit, had to go away from keyboard.Amontillado

© 2022 - 2024 — McMap. All rights reserved.