简体   繁体   中英

How to add defaults to existing columns with Gorm

I'm using gorm and have a model like so:

type MyModel struct {
    CreationTime      time.Time 
    UpdateTime        time.Time
}

I realized after deploying my DB that creation time and update time weren't adding times when items were being created and updated: I tried to fix this by updating the model to the following:

type MyModel struct {
    CreationTime      time.Time       `gorm:"default:current_timestamp"`
    UpdateTime        time.Time       `gorm:"default:current_timestamp ON update current_timestamp"`
}

However, auto migrating like the following won't apply these defaults on the already existing tables!

 db.AutoMigrate(&MyModel{})

Is there any way I can use the built in migration functions to add defaults to columns? I searched the docs and it seems like I can only change the type of existing columns, If not? any recommendations for a why to simply add defaults to a column via migrations?

Have you tried sql tag?

`sql:"DEFAULT:current_timestamp"`

The automigration provided by gorm doesn't delete or modify your columns and for good reasons, it's not safe. I had a similar issue. I needed to drop the null constraint from one of my columns and couldn't find anything that does that in gorm, and I'm pretty sure it doesn't. I wrote my own function for doing this. You can easily do something similar.

Please take a look at these two commits: this and this . What you can basically do this is to define a method for the Dialect interface and then write an implementation for that method for the commonDialect type (and the postgres type, if required).

Hope this helps. Feel free to ask me if you face any problems with implementation or have any doubts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM