3
votes

I'm using slick code generator for generating classes from SQL database in Play for scala 2.4. I'm wondering how to generate code with primary key defined as Option, so when I'm inserting new record I can put None instead of primary key.

Let's suppose that I have a table

OrderItem
----------
orderItemId: int
name: varchar

For now I have to create instance like this:

val item = new OrderItem(0, "Item name")
db.run(orderItems += item)

It works, but the zero is just odd, so my goal is

val item = new OrderItem(None, "Item name")
db.run(orderItems += item)

Is that possible? With PK of type Option[Int] I should then also be able to reuse this class e.g. for forms mapping.

1

1 Answers

2
votes

According to example in slick documentation just change rawType to

    override def rawType = {
      if (model.options.contains(ColumnOption.PrimaryKey)) {
        "Option[" + super.rawType + "]"
      } else {
        super.rawType
      }
    }

Update

My question is a duplicate: Customizing Slick Generator

Slick code generator already implements this:

new SourceCodeGenerator(model){
    override def Table = new Table(_){
        override def autoIncLastAsOption = true
    }
}