Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating db row scala slick

Tags:

scala

slick

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.

like image 394
pmalecki Avatar asked Jun 02 '14 11:06

pmalecki


1 Answers

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)
like image 86
Ende Neu Avatar answered Oct 16 '22 20:10

Ende Neu