Created
March 21, 2020 12:50
-
-
Save TrinhTrungDung/c39af8afafb0e6baa626917961ff8fc8 to your computer and use it in GitHub Desktop.
Test helper function with dynamic batching size and additional parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func benchmarkBulkCreate(size int, b *testing.B) { | |
db, err := gorm.Open("postgres", "host=localhost port=5432 user=testuser dbname=testdb password=123456 sslmode=disable") | |
if err != nil { | |
fmt.Println(err) | |
} | |
defer db.Close() | |
users := stubUsers(b) | |
tx := db.Begin() | |
chunkList := funk.Chunk(users, size) | |
for _, chunk := range chunkList.([][]*User) { | |
valueStrings := []string{} | |
valueArgs := []interface{}{} | |
for _, user := range chunk { | |
now := time.Now() | |
valueStrings = append(valueStrings, "(?, ?, ?, ?)") | |
valueArgs = append(valueArgs, now) | |
valueArgs = append(valueArgs, now) | |
valueArgs = append(valueArgs, user.Name) | |
valueArgs = append(valueArgs, user.Password) | |
} | |
stmt := fmt.Sprintf("INSERT INTO users (created_at, updated_at, name, password) VALUES %s", strings.Join(valueStrings, ",")) | |
err = tx.Exec(stmt, valueArgs...).Error | |
if err != nil { | |
tx.Rollback() | |
fmt.Println(err) | |
} | |
} | |
err = tx.Commit().Error | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment