Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting default values if column value is 'None' using slick

My problem is simple.

I have a column seqNum: Double which is NOT NULL DEFAULT 1 in CREATE TABLE statement as follows:

CREATE TABLE some_table
(
    ...
    seq_num DECIMAL(18,10) NOT NULL DEFAULT 1,
    ...
);

User can enter a value for seqNum or not from UI. So the accepting PLAY form is like:

case class SomeCaseClass(..., seqNum: Option[Double], ...)
val secForm = Form(mapping(
    ...
    "seqNum" -> optional(of[Double]),
    ...
  )(SomeCaseClass.apply)(SomeCaseClass.unapply))

The slick Table Schema & Objects looks like this:

case class SomeSection (
   ...
   seqNum: Option[Double],
   ...
)
class SomeSections(tag: Tag) extends Table[SomeSection](tag, "some_table") {
  def * = (
      ...
      seqNum.?,
      ...
    ) <> (SomeSection.tupled, SomeSection.unapply _)

  ...
  def seqNum = column[Double]("seq_num", O.NotNull, O.Default(1))
  ...
}
object SomeSections {

  val someSections = TableQuery[SomeSections]
  val autoInc = someSections returning someSections.map(_.sectionId)

  def insert(s: someSection)(implicit session: Session) = {
     autoInc.insert(s)
  }
}

When I'm sending seqNum from UI, everything is works fine but when None is there, it breaks saying that cannot insert NULL in NOT NULL column which is correct. This question explains why.

But how to solve this problem using slick? Can't understand where should I check about None? I'm creating & sending an object of SomeSection to insert method of SomeSections Object.

I'm using sql-server, if it matters.

like image 302
Sunil Kumar Avatar asked Feb 12 '15 07:02

Sunil Kumar


1 Answers

Using the default requires not inserting the value at all rather than inserting NULL. This means you will need a custom projection to insert to.

people.map(_.name).insert("Chris") will use defaults for all other fields. The limitations of scala's native tuple transformations and case class transformations can make this a bit of a hassle. Things like Slick's HLists, Shapeless, Scala Records or Scala XR can help, but are not trivial or very experimental at the moment.

like image 81
cvogt Avatar answered Nov 11 '22 15:11

cvogt