Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slick code generator - primary key as option

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.

like image 716
Peter Krejci Avatar asked Oct 26 '25 10:10

Peter Krejci


1 Answers

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
    }
}
like image 183
Peter Krejci Avatar answered Oct 29 '25 00:10

Peter Krejci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!