Skip to content

Commit

Permalink
Merge pull request #316 from go-mgo/is-dup-retry-fix
Browse files Browse the repository at this point in the history
Fix the IsDup retry error handling on Apply.
  • Loading branch information
niemeyer authored Aug 18, 2016
2 parents 0108465 + 362ae10 commit f2b6f6c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
3 changes: 1 addition & 2 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -4305,11 +4305,10 @@ func (q *Query) Apply(change Change, result interface{}) (info *ChangeInfo, err
var doc valueResult
for i := 0; i < maxUpsertRetries; i++ {
err = session.DB(dbname).Run(&cmd, &doc)

if err == nil {
break
}
if change.Upsert && IsDup(err) {
if change.Upsert && IsDup(err) && i+1 < maxUpsertRetries {
// Retry duplicate key errors on upserts.
// https://docs.mongodb.com/v3.2/reference/method/db.collection.update/#use-unique-indexes
continue
Expand Down
30 changes: 25 additions & 5 deletions session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,26 @@ func (s *S) TestIsDupFindAndModify(c *C) {
c.Assert(mgo.IsDup(err), Equals, true)
}

func (s *S) TestIsDupRetryUpsert(c *C) {
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()

coll := session.DB("mydb").C("mycoll")

err = coll.Insert(bson.M{"_id": 1, "x": 1})
c.Assert(err, IsNil)

_, err = coll.Upsert(bson.M{"_id": 1, "x": 2}, bson.M{"$set": bson.M{"x": 3}})
c.Assert(mgo.IsDup(err), Equals, true)

_, err = coll.Find(bson.M{"_id": 1, "x": 2}).Apply(mgo.Change{
Update: bson.M{"$set": bson.M{"x": 3}},
Upsert: true,
}, nil)
c.Assert(mgo.IsDup(err), Equals, true)
}

func (s *S) TestFindAndModify(c *C) {
session, err := mgo.Dial("localhost:40011")
c.Assert(err, IsNil)
Expand Down Expand Up @@ -4159,11 +4179,11 @@ func (s *S) TestBypassValidation(c *C) {

func (s *S) TestVersionAtLeast(c *C) {
tests := [][][]int{
{{3,2,1}, {3,2,0}},
{{3,2,1}, {3,2}},
{{3,2,1}, {2,5,5,5}},
{{3,2,1}, {2,5,5}},
{{3,2,1}, {2,5}},
{{3, 2, 1}, {3, 2, 0}},
{{3, 2, 1}, {3, 2}},
{{3, 2, 1}, {2, 5, 5, 5}},
{{3, 2, 1}, {2, 5, 5}},
{{3, 2, 1}, {2, 5}},
}
for _, pair := range tests {
bi := mgo.BuildInfo{VersionArray: pair[0]}
Expand Down

0 comments on commit f2b6f6c

Please sign in to comment.