suman j
suman j

Reputation: 6960

golang gorp insert multiple records

Using gorp how can one insert multiple records efficiently? i.e instead of inserting one at a time, is there a batch insert?

var User struct {
   Name string
   Email string
   Phone string
}
var users []Users
users = buildUsers()
dbMap.Insert(users...) //this fails compilation
//I am forced to loop over users and insert one user at a time. Error Handling omitted for brevity

Is there a better mechanism with gorp? Driver is MySQL.

Upvotes: 1

Views: 1801

Answers (2)

edufinn
edufinn

Reputation: 2447

As I found out on some other resource the reason this doesn't work is that interface{} and User{} do not have the same layout in memory, therefore their slices aren't of compatible types. Suggested solution was to convert []User{} into []interface{} in for loop, like shown here: https://golang.org/doc/faq#convert_slice_of_interface

There is still on caveat: you need to use pointers for DbMap.Insert()function.

Here's how I solved it:

s := make([]interface{}, len(users))
for i, v := range users {
    s[i] = &v
}
err := dbMap.Insert(s...)

Note that &v is important, otherwise Insert will complain about non-pointers.

Upvotes: 4

matt.s
matt.s

Reputation: 1736

It doesn't look like gorp has anything that gives a wrapper for either raw SQL or multi value inserts (which is always SQL dialect dependent).
Are you worried about speed or transactions? If not, I would just do the inserts in a for loop.

Upvotes: 0

Related Questions