evan
evan

Reputation: 265

How to return a sequence generation for an Id

In Scala Slick, if you are not using auto-incremented Id, but with sequence generation strategy for the id, how do you return that id?

Upvotes: 3

Views: 1651

Answers (1)

Akos Krivachy
Akos Krivachy

Reputation: 4966

Let's say you have the following case class and Slick table:

case class User(id: Option[Int], first: String, last: String)

object Users extends Table[User]("users") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def first = column[String]("first")
  def last = column[String]("last")
  def * = id.? ~ first ~ last <> (User, User.unapply _)
}

The important things to consider here is the fact that User.id is an Option, because when we create it we will set it to None and the DB will generate the number for it.

Now you need to define a new insert mapping which omits the autoincremented column. This is needed because some databases don't allow you to insert into a column which is labeled as Auto Incremental. So instead of:

INSERT INTO users VALUES (NULL, "first, "last")

Slick will generate:

INSERT INTO user(first, last) VALUES ("first", "last")

The mapping looks like this (which must be placed inside Users):

def forInsert = first ~ last <> ({ t => User(None, t._1, t._2)}, { (u: User) => Some((u.first, u.last))})

Finally getting the auto-generated id is simple. We only need to specify in the returning the id column:

val userId = Users.forInsert returning Users.id insert User(None, "First", "Last")

Or you could instead move the returning statement:

def forInsert = first ~ last <> ({ t => User(None, t._1, t._2)}, { (u: User) => Some((u.first, u.last))}) returning id

And simplify your insert calls:

val userId = Users.forInsert insert User(None, "First", "Last")

Source

Upvotes: 2

Related Questions