Search code examples
scalaslick

Yield nothing in for ... yield when inserting into DB using DBAction


When inserting objects in the DB using a for ... yield construct (See below) I want to be able to 'yield nothing' for certain conditions. I am still learning Scala and have little experience in Slick.

val usersTable = TableQuery[dbuserTable]
val inserts = for (user <- x.userList) yield {
  if (user.someCondition == true) {
      val userRow = userClass(user.name, user.id)
      usersTable += userRow
  }
  else {
    //yield nothing
  }      
}
DBAccess.db.run(DBIO.seq(inserts: _*))

I'm afraid I'm missing something about how the yield loop leads to a Sequence of DBAction objects.


Solution

  • Try

    val inserts = for (user <- x.userList) yield {
      if (user.someCondition == true) {
        val userRow = userClass(user.name, user.id)
        usersTable += userRow
      }
      else {
        DBIO.successful(0)
      }
    }
    

    Int in DBIOAction[Int, NoStream, Effect.Write] means number of rows inserted.