Updating db row scala slick

pmalecki picture pmalecki · Jun 2, 2014 · Viewed 17k times · Source

I have following code which inserts row into table named luczekInfo and function to get data from database. My question is how to make function to update columns from table luczekInfo, on rows returned by get(id) function. What is the best way to update columns values in Slick?

def create(profil: luczekInfo): Either[Failure, luczekInfo] = {
  try {
    val id = db.withSession {
      LuczekInfo returning LuczekInfo.id insert profil
    }
    Right(profil.copy(id = Some(id)))
  } catch {
    case e: SQLException =>
      Left(databaseError(e))
  }
}

def get(id: Int): Either[Failure, luczekInfo] = {
  try {
    db.withSession {
      LuczekInfo.findById(id).firstOption match {
        case Some(profil: luczekInfo) =>
          Right(profil)
            case _ =>
              Left(notFoundError(id))
      }
    }
  } catch {
    case e: SQLException =>
      Left(databaseError(e))
  }
}

Thanks in advance for answers.

Answer

Ende Neu picture Ende Neu · Jun 2, 2014

Slick 2.X

You can update a row in two ways (as far as I know), the first one would be to create a row object of type luczekInfo#TableElementTypeand use it to update the full row:

def updateById(id: Long, row: luczekInfo#TableElementType)(implicit s: Session): Boolean =
  luczekInfo.filter(_.id === id).update(row)

Or you can update single fields using:

def updateNameById(mId: Long, mName: String)(implicit s: Session) = {
  val q = for { l <- luczekInfo if l.id === mId } yield l.name
  q.update(mName).run
}

Where I supposed your table has a file called name.

You can find it also on the Slick documentation in the section on updating.

Slick 3.1.X

there's an additional support for the insertOrUpdate (upsert) operation:

luczekInfo.insertOrUpdate(row)