1

Given mapping having NOT NULL field str with a default value:

case class Tst(id: Option[Int] = None, ii: Int, str: String)
class Tsts(tag: Tag) extends Table[Tst](tag, "tsts") {
  def id = column[Option[Int]]("id", O.PrimaryKey, O.AutoInc)
  def ii = column[Int]("ii")
  def str = column[String]("str", O.Default("ddd"))
  def * = (id, ii, str) <> (Tst.tupled, Tst.unapply)
}

How do I insert object specifying the field value if I have it:

Tst(ii = 1, str = "aaa")

and skipping it if I don't:

Tst(ii = 1)

Yes, I know the last statement will not compile.
I tried using Option[String] and other things. It ends up with either inserting null or failing with can't be null error

Sergii Pogodin
  • 363
  • 3
  • 7
  • I think this is a duplicate of http://stackoverflow.com/questions/28471399/inserting-default-values-if-column-value-is-none-using-slick/ (more or less). – jkinkead May 06 '16 at 17:48

1 Answers1

0

The compiler depends on you putting default values at the end, like:

scala> case class TST(ii: Int, str: String = "aaa", id: Option[Int] = None)
defined class TST

scala> new TST(3)
res0: TST = TST(3,aaa,None)

Edit: Just realized I didn't answer completely:

scala> new TST(3, id = Some(1))
res1: TST = TST(3,aaa,Some(1))

scala> new TST(3, str = "bbb")
res2: TST = TST(3,bbb,None)
  • This approach doesn't use the default value provided by the DB. The default could be changed in the future, be current date or calculated some other way – Sergii Pogodin May 03 '16 at 13:31
  • Oh, I see you changed the question now... I think the only option then is to create an update statement that does not include the values on the case class, or have it conditionally include those values if they are defined. – Devyn Goetsch May 03 '16 at 17:54
  • Edit: *(values on the case class) should be *(values you want defaulted) – Devyn Goetsch May 03 '16 at 18:03