postgresqlscalaslickslick-codegen

How to make Slick respect DB column defaults on insert?


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?


Solution

  • 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") )