Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

postgresql - Pattern matching on Stream, Option and creating a Tuple

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...