Skip to content

Instantly share code, notes, and snippets.

@dvas0004
Last active May 9, 2022 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dvas0004/4d849c5212a65cf01c87d1c994ac5a75 to your computer and use it in GitHub Desktop.
Save dvas0004/4d849c5212a65cf01c87d1c994ac5a75 to your computer and use it in GitHub Desktop.
package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type job1 struct {
ID int `gorm:"primaryKey"`
UniqueField1 string
CommonField1 string
}
type job2 struct {
ID int `gorm:"primaryKey"`
UniqueField2 string
CommonField2 string
}
type job interface {
GetCommonFieldVal() string
GetCommonFieldName() string
GetDBModel() interface{}
}
func (j job1) GetCommonFieldVal() string {
return j.CommonField1
}
func (j job2) GetCommonFieldVal() string {
return j.CommonField2
}
func (j job1) GetCommonFieldName() string {
return "common_field1"
}
func (j job2) GetCommonFieldName() string {
return "common_field2"
}
func (j job1) GetDBModel() interface{} {
return &j
}
func (j job2) GetDBModel() interface{} {
return &j
}
var db, _ = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
func worker(j job) {
db.Model(j.GetDBModel()).Update(j.GetCommonFieldName(), "new-val")
}
func main() {
db.AutoMigrate(&job1{})
db.AutoMigrate(&job2{})
sampleJob1 := job1{
UniqueField1: "foo",
CommonField1: "old-common1",
}
sampleJob2 := job2{
UniqueField2: "baz",
CommonField2: "old-common2",
}
db.Model(&sampleJob1).FirstOrCreate(&sampleJob1)
db.Model(&sampleJob2).FirstOrCreate(&sampleJob2)
worker(sampleJob2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment