How to make Slick respect DB column defaults on insert?

468 views Asked by At

I'm using Slick 3.2 with the codegen in a Scala Play app with Postgres DB. Each of my tables has a timestamp field for create_time, with the following type: TIMESTAMP default (now() at time zone 'utc'). The issue I'm running into is that Slick generates the model field as createTimestamp: Option[java.sql.Timestamp], and then inserts an explicit null for that column when createTimestamp is None. I'd like the behavior to instead leave the value out of the insert statement altogether so that the DB uses its default. Is there any way to do that?

2

There are 2 answers

0
thwiegan On BEST ANSWER

You could try something like the following:

To insert an object of

class YourModel(id: Option[Long], name: String, someOtherField: String, createdAt: Option[Timestamp])

without providing an ID and a timestamp at all:

val table = TableQuery[YourModelTable]

db.run( table.map( t => (t.name, t.someOtherField) ) += ("MyName", "MyOtherField") )
0
Jakub Kahovec On

I've found a workaround, when you specify that this column is AutoInc it'll be skipped on insert and the default will get applied instead

   def createdAt = column[Instant]("created_at", O.AutoInc)