Loann Delgado Loann Delgado - 1 year ago 120
Scala Question

Slick: how to return an error on update if zero row was updated

I want to return an error if I try to update an inexistant row in Slick.

my query:

userPromotions.filter(promo =>
promo.code === code).update(myUpdatedRow)

the query I try to do (I have an error cause "rowToUpdate.exist" is a Rep[Boolean] and not a Boolean):

val rowToUpdate = userPromotions.filter(promo => promo.code === code)
if(rowToUpdate.exist) rowToUpdate.update(myUpdatedRow)
else NotFound

is there any way to do that in a single query ?

Answer Source

If you are using Slick 3.0 and above

Using DBIO.failed you can fail the transaction when number of updated rows is 0

userPromotions.filter(_.code === code).update(myUpdatedRow).flatMap { updatedRows =>
  if (updatedRows == 0) DBIO.failed(new Exception("0 rows updated"))
  else DBIO.successful(updatedRows)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download