Skip to content

Commit

Permalink
add support for batch insert/exec with maps in addition to structs
Browse files Browse the repository at this point in the history
  • Loading branch information
J-Zeitler committed Mar 20, 2019
1 parent cdf62fd commit bf8aed5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ _testmain.go
*.exe
tags
environ

.idea
4 changes: 4 additions & 0 deletions named.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ func bindAnyArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interfa
// type, given a list of names to pull out of the struct. Used by public
// BindStruct interface.
func bindArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interface{}, error) {
if maparg, ok := arg.(map[string]interface{}); ok {
return bindMapArgs(names, maparg)
}

arglist := make([]interface{}, 0, len(names))

// grab the indirected value of arg
Expand Down
13 changes: 12 additions & 1 deletion named_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ func TestNamedQueries(t *testing.T) {
t.Errorf("got %s, expected %s", p.Email, people[0].Email)
}

// test batch inserts
// test struct batch inserts
sls := []Person{
{FirstName: "Ardie", LastName: "Savea", Email: "[email protected]"},
{FirstName: "Sonny Bill", LastName: "Williams", Email: "[email protected]"},
Expand All @@ -195,6 +195,17 @@ func TestNamedQueries(t *testing.T) {
VALUES (:first_name, :last_name, :email)`, sls)
test.Error(err)

// test map batch inserts
slsMap := []map[string]interface{}{
{"first_name": "Ardie", "last_name": "Savea", "email": "[email protected]"},
{"first_name": "Sonny Bill", "last_name": "Williams", "email": "[email protected]"},
{"first_name": "Ngani", "last_name": "Laumape", "email": "[email protected]"},
}

_, err = db.NamedExec(`INSERT INTO person (first_name, last_name, email)
VALUES (:first_name, :last_name, :email)`, slsMap)
test.Error(err)

for _, p := range sls {
dest := Person{}
err = db.Get(&dest, db.Rebind("SELECT * FROM person WHERE email=?"), p.Email)
Expand Down

0 comments on commit bf8aed5

Please sign in to comment.