Arne Claassen
Arne Claassen

Reputation: 14414

Inserting pirmary key for Table with auto-increment

I'm trying to find a way to perform an insert on a slick Table whose primary key is an auto-increment but force the primary key to the value in the mapped case class. I.e. given:

case class Foo(id: Int, name: String)

class FooTable(tag: Tag) extends Table[Foo](tag, "foo") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)

  def name = column[String]("name")

  def * = (id, name) <> (Foo.tupled, Foo.unapply)
}

val foos = TableQuery[FooTable]

If I do a regular insert via

db.run(foos += Foo(123,"bar"))

it will set id to whatever the next auto-increment value is, rather than setting it to 123. Is there a syntax for forcing id to be set to the value in the provided case class Foo?

Upvotes: 1

Views: 426

Answers (1)

blouerat
blouerat

Reputation: 692

Checkout forceInsert

Inserts can be a bit surprising at first […] Columns that are auto-incremented are automatically ignored, so inserting into them has no effect. Using forceInsert allows actual insertion into auto-incremented columns.

Source : Coming from SQL to Slick

Upvotes: 3

Related Questions