Permalink
Browse files

+ slick #1334 add DBIOAction.collect

  • Loading branch information...
hepin1989 committed Nov 23, 2015
1 parent 3d1018f commit 4d07e94ec3e76868bc077694839766ce4975a7cd
@@ -144,4 +144,32 @@ class ActionTest extends AsyncTest[RelationalTestDB] {
_ = result shouldBe 2
} yield ()
}
def testCollect = {
class T(tag: Tag) extends Table[Int](tag, u"t") {
def a = column[Int]("a")
def * = a
}
val ts = TableQuery[T]
for {
_ <- db.run {
ts.schema.create >>
(ts ++= Seq(2, 3, 1, 5, 4))
}
q1 = ts.sortBy(_.a).map(_.a).take(1)
result <- db.run(q1.result.headOption.collect {
case Some(a) => a
})
_ = result shouldBe 1
_ = result shouldFail { _ =>
val future = db.run(q1.result.headOption.collect {
case None => ()
})
import scala.concurrent.duration.Duration
import scala.concurrent.Await
Await.result(future, Duration.Inf)
}
} yield ()
}
}
@@ -109,6 +109,13 @@ sealed trait DBIOAction[+R, +S <: NoStream, -E <: Effect] extends Dumpable {
def withFilter(p: R => Boolean)(implicit executor: ExecutionContext): DBIOAction[R, NoStream, E] =
flatMap(v => if(p(v)) SuccessAction(v) else throw new NoSuchElementException("Action.withFilter failed"))
/** Transform the result of a successful execution of this action, if the given partial function is defined at that value,
* otherwise, the result DBIOAction will fail with a `NoSuchElementException`.
*
* If this action fails, the resulting action also fails. */
def collect[R2](pf: PartialFunction[R,R2])(implicit executor: ExecutionContext): DBIOAction[R2, NoStream, E] =
map(r1 => pf.applyOrElse(r1,(r:R) => throw new NoSuchElementException(s"DBIOAction.collect partial function is not defined at: $r")))
/** Return an action which contains the Throwable with which this action failed as its result.
* If this action succeeded, the resulting action fails with a NoSuchElementException. */
def failed: DBIOAction[Throwable, NoStream, E] = FailedAction[E](this)

0 comments on commit 4d07e94

Please sign in to comment.