2
votes

I want to insert a new row with different status value if that row exists and return the new instance as Some to the caller. If it does not exist, nothing happens and return None. What I have is

 def revoke(name: String, issueFor: String): Future[MyLicense] = {
   val retrieveLicense = slickLicenses.filter(l => l.name === name && l.issueFor === issueFor).
  sortBy(_.modifiedOn.desc).result.headOption
   val insertLicense = for {
     licenseOption <- retrieveLicense
   } yield {
     licenseOption match {
       case Some(l) => Some(slickLicenses += l.copy(status = RevokedLicense))
       case None => None
   }
 }
 db.run(insertLicense).map {r => 
   r.map { dbLicense => MyLicense(dbLicense.name, dbLicense.status)
 }

}

How do I fix this?

Edit 1

I changed the code to

override def revoke(name: String, issueFor: String): Future[String] = {
  val retrieveLicense = slickLicenses.filter(l => l.name === name && l.issueFor === issueFor).
  sortBy(_.modifiedOn.desc).result.headOption
  val insertLicenseAction = for {
    l <- retrieveLicense
    newLicense <- slickLicenses += l.get.copy(status = RevokedLicense)
} yield newLicense
  db.run(insertLicenseAction).map(_ => name)

}

Hence, the question changes to how do I get the instance I insert into the database? Thanks

1

1 Answers

1
votes

This is what I did finally,

override def revoke(name: String, issueFor: String): Future[String] = {
val retrieveLicense = slickLicenses.filter(l => l.name === name && l.issueFor === issueFor).
    sortBy(_.modifiedOn.desc).result.headOption
val insertLicenseAction = for {
  l <- retrieveLicense
  _ <- l.map(x => slickLicenses += x.copy(status = RevokedLicense, 
             modifiedOn = new Timestamp(System.currentTimeMillis())))
    .getOrElse(DBIO.successful(l))
} yield ()
db.run(insertLicenseAction).map(x => name)}