I am looking for a way to improve the performance of a transaction. My code looks like the following:
return db.Transaction(func(tx *gorm.DB) error {
for _, val := range values {
if err := tx.Save(&val).Error; err != nil {
fmt.Println(err)
}
}
return nil
}
(this is stripping away some logic code) This seems to be able to do about 10 Saves per second, which seems quite slow especially when dealing with larger data sets. I'm looking to replace this with something along the line of the following:
return db.Transaction(func(tx *gorm.DB) error {
addToDb := func(txdb *gorm.DB, job <- chan Values) {
for val := range job {
if err := txdb.Save(val).Error; err != nil {
fmt.Println(err)
}
}
}
jobs := make(chan Values, len(values))
for w := 1; w <= 10; w++ {
go addToDb(tx, jobs)
}
for _, v := range values {
jobs <- v
}
close(jobs)
return nil
}
I end up with sql: transaction has already been committed or rolled back
Is there a proper way of dealing with multi-threaded transaction inserts?