I want to have a table whose primary key is an auto-generated timestamp (I know it's generally not the best idea, but in my case it's OK) and it has another string field. This is the data structure that I use:
type GlobalDefault struct {
Timestamp time.Time `gorm:"primary_key" sql:"DEFAULT:current_timestamp"`
Version string `sql:"not null"`
}
When I use this data structure with AutoMigrate I indeed get a table with the timestamp as primary key, and I can even run insert into global_defaults (version) VALUES ('1.5.3');
and a new row would get inserted with an auto-generated timestamp.
My problem is that I can't insert records into this table using gorm. I use the following function:
func (repository *AgentRepository)SetGlobalDefault(version string) error {
gd := GlobalDefault{ Version:version }
return repository.connection.Create(&gd).Error
}
And when I call it I get the following error:
Received unexpected error could not convert argument of field Timestamp from int64 to time.Time
If I provide the timestamp explicitly, it works. I'm guessing that it has a problem with the default time ('0001-01-01 00:00:00 +0000 UTC') which is created when I don't specify it exactly.
Is there a way around this?
After comment interaction, drafting this answer.
I'm guessing that it has a problem with the default time ('0001-01-01 00:00:00 +0000 UTC') which is created when I don't specify it exactly.
The reason is, in Go data type has zero value, spec and good read here.
For you, possible way is to use appropriate gorm callbacks to set or modify struct fields on before or after database interactions.