2

I have a simple MySQL db with a single row in the REG_PERIODS table. When I run this query I get the row back.

val getRegPeriodAction = regPeriods.sortBy(_.endDate).result.head.map { regPeriod ⇒
  Logger.debug(s"regPeriod = ${regPeriod}")

  regPeriod
}

However, when I run this query, I get nothing, in fact the debug message isn't even being reached!

val getRegPeriodAction = regPeriods.sortBy(_.endDate).result.headOption.map { regPeriodOption ⇒
  Logger.debug(s"regPeriodOption = ${regPeriodOption}")

  regPeriodOption match {
    case Some(regPeriod) ⇒ regPeriod
  }
}

I'm using play-slick 1.0.0. Am I misunderstanding something here? Should I receive a Some(regPeriod) when using headOption?

EDIT

I've tried running the the headOption query in db.run( ... ) and sending the result to another function, like so:

def handleResult(opt: Option[RegistrationPeriod]) {
  Logger.debug(s"received $opt")
}

for {
  r <- db.run( regPeriods.sortBy(_.endDate.desc).result.headOption )
  _ <- handleResult( r )
} ...

The odd thing is that handleResult is never called! As soon as I change the code to call head instead of headOption everything works as expected.

Oli
  • 1,112
  • 1
  • 10
  • 25
  • 1
    Did you solve your problem already? Are you sure `result.headOption` returns a nonempty `Option`? `handleResult()` will be called only, if `Option` has a value. – Roman Jul 27 '15 at 07:23
  • Doh! Of course, it's returning `None` and because handleResult is in a for comprehension it's not being called! I need to do a check on the value of `r` before handling result. – Oli Jul 27 '15 at 15:33

1 Answers1

4

.result does not execute your query on a database. It creates an action which must be passed to db.run() or db.stream() in order to execute it:

val action = regPeriods.sortBy(_.endDate).result.headOption
val result: Future[Option[RegPeriod]] = db.run(action)

// accessing your data
result.map(r => r....)  // r is of type Option[RegPeriod]
Roman
  • 5,651
  • 1
  • 30
  • 41
  • Thanks for the quick answer, unfortunately that's not what's causing the problem. See my edit – Oli Jul 24 '15 at 17:19