Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala+Slick - Get counts on GroupBy results

Tags:

scala

slick

I'm trying to get counts from a DB using a groupBy on my Scala+Slick code.

Here's my partial code :

object DBJobs extends Table[DBJob]("encoder_job") {
  object Status extends Enumeration {
    val local = Value("LOCAL")
    val encoding = Value("ENCODING")
    val done = Value("DONE")
    val error = Value("ERROR")
  }
  implicit val StatusMapper = MappedTypeMapper.base[Status.Value, String] (
    {x => x.toString},
    {x => x match {case "LOCAL"=>Status(0);case "ENCODING"=>Status(1);case "DONE"=>Status(2);case "ERROR"=>Status(3)}}
  )

  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def status = column[DBJobs.Status.Value]("status", O.NotNull)

  def getStats()(implicit session:Session):mutable.Map[Status.Value, Int] = {
    var map = mutable.Map[Column[Status.Value], Column[Int]]()
    val q = (for { j <- DBJobs } yield (j)).groupBy(_.status).map{
      case (s, results) =>
        map = map += (s -> results.length)
    }
    map
  }
}

My problem is how to put data in my Map as [DBJobs.Status, Int] instead of [Column[Status.Value], Column[Int]].

Here's the SQL equivalent :

SELECT COUNT( 1 ), status FROM encoder_job GROUP BY STATUS 

Slick version: 1.0.1

Thanks

like image 569
Sylvain T. Avatar asked Dec 25 '22 17:12

Sylvain T.


1 Answers

def getStats()(implicit session:Session):mutable.Map[Status.Value, Int] = {
  Query(DBJobs).groupBy(_.status).map{
    case (s, results) => (s -> results.length)
  }
}

// usage
val results = getStats.run

Be aware that putting methods in the table object directly cannot be easily migrated to Slick 2.0. Put them separate, e.g. as method extensions. Also see https://groups.google.com/d/msg/scalaquery/xNtPT6sexXI/zlkgxv6lZ6YJ

like image 120
cvogt Avatar answered Jan 11 '23 23:01

cvogt