I’m attempting to create a generic function in Go for upserting objects in a Microsoft SQL Azure database using gorm, but am not too familiar with the details in the documentation for gorm and wanted to confirm this is doing what I am expecting.
I’ve used detail from this previous question along with information from the docs.
func BatchUpsertObjectsToDatabase[T any](db *gorm.DB, objects []T) {
db.AutoMigrate(objects[0])
s, err := schema.Parse(objects[0], &sync.Map{}, schema.NamingStrategy{})
if err != nil {
log.Fatal("failed to parse schema for object")
}
var primaryKeys []clause.Column
updateFields := []string{}
for _, f := range s.Fields {
if !f.PrimaryKey {
updateFields = append(updateFields, f.DBName)
}
if f.PrimaryKey {
c := clause.Column{
Name: f.DBName,
}
primaryKeys = append(primaryKeys, c)
}
}
db.Clauses(clause.OnConflict{
Columns: primaryKeys,
DoUpdates: clause.AssignmentColumns(updateFields),
}).CreateInBatches(objects, 100)
}
Am I right in assuming that in clause.OnConflict
the Columns
field is to specify the primary key since this is what the conflict would be caused by? And that DoUpdates
specifies which fields should still be updated?
So, in my case here I’m saying conflict on all primary keys and update all columns on conflict?