15

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.

Marcus Adams
  • 53,009
  • 9
  • 91
  • 143
pmalecki
  • 229
  • 1
  • 2
  • 12

1 Answers1

26

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)
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
  • 3
    Or you can write direct SQL query, it's also possible in Slick :) – Ashalynd Jun 02 '14 at 12:51
  • 1
    Yup you can also use plain simple SQL, especially where some operations are not supported, but I guess lifting the `Slick` potentiality is more convenient in this case :D – Ende Neu Jun 02 '14 at 12:58
  • Aha, I was using the first style but missing the filter clause, thanks! – Andrew Swan Oct 19 '15 at 04:24
  • `for { l <- luczekInfo if l.id === mId }` looks a little bit inefficient. Are you sure that for update by id there is nothing faster? – szefuf Aug 24 '16 at 21:59
  • 4
    @szefuf what do you mean by "it looks inefficient"? This is not a filter on a collection, this will be translated to something like `WHERE l.id = 'someId'` from slick, I'm not sure why do you think this is slow unless you look at it like an operation on a collection instead of a way to build your query. – Ende Neu Aug 25 '16 at 08:05
  • @EndeNeu Thanks, this is exactly my concern. If it is translated to such `where` than ok. I'm not really familiar with Slick, just starting to get to know it. – szefuf Aug 25 '16 at 13:34