Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic function to upsert objects? #7057

Open
darrenparkinson opened this issue Jun 7, 2024 · 0 comments
Open

Generic function to upsert objects? #7057

darrenparkinson opened this issue Jun 7, 2024 · 0 comments
Assignees
Labels
type:question general questions

Comments

@darrenparkinson
Copy link

Your Question

I'm trying to write a generic function to bulk upsert objects in MSSQL and I wanted to check if this looks correct? I've used some code from this stackoverflow question, but the docs are a little sparse regarding the clause.OnConflict for my current knowledge.

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?

The document you expected this should be explained

https://gorm.io/docs/create.html#Batch-Insert

Expected answer

I'd like for this to be correct and possibly pointing to some documentation I've missed, or for the documentation to be updated slightly?

Many thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

2 participants