Question

I have a table table1:

id: Int
externalId: Int
value: String

For a given externalId value can be NULL or it might not exist at all. I want to return a tuple depending on this condition:

  1. If it doesn't exist then return ("notExists", Nil)
  2. If it exists but NULL then return ("existsButNull", Nil)
  3. If it exists and not NULL then return ("existsWithValue", ???)

where ??? should be a list of value for all records with the given externalId. I tried to do this:

DB.withConnection { implicit c =>
  SQL("SELECT value from table1 WHERE externalId = 333")
    .map { case Row(value: Option[String]) => value }
} match {
  case Some(x) #:: xs =>
    //????????????
    ("existsWithValue", ???)
  case None #::xs => ("existsButNull", Nil)
  case Stream.empty => ("notExists", Nil)
}

Note that if value exists and is not NULL and if there are more than 1 record of it then value can't be NULL. For example, this situation is NOT possible

1 123 "Value1"
2 123 "Value2"
3 123  NULL    -- NOT possible  
4 123 "Value4"

It has to do with pattern matching of Stream + Option but I can't figure out how to do this.

Was it helpful?

Solution

Pattern matching on a stream is probably not a good idea, I'm assuming the number of elements being returned is small enough to fit into memory? You would only work with a stream if it's likely that the elements won't fit in memory, otherwise it's much easier to convert the stream to a list, and then work with the list:

DB.withConnection { implicit c =>
  SQL("SELECT value from table1 WHERE externalId = 333")
    .map { case Row(value: Option[String]) => value }
    .toList
} match {
  case Nil => ("notExists", Nil)
  case List(None) => ("existsButNull", Nil)
  case xs => ("existsWithValue", xs.flatMap(_.toList))
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top