Skip to content

Commit

Permalink
Remove GridFS chunks if file doc insertion fails.
Browse files Browse the repository at this point in the history
Fixes #66.
  • Loading branch information
niemeyer committed Jan 22, 2015
1 parent a581209 commit ff4340b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
17 changes: 9 additions & 8 deletions gridfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,17 +521,18 @@ func (file *GridFile) completeWrite() {
debugf("GridFile %p: waiting for %d pending chunks to complete file write", file, file.wpending)
file.c.Wait()
}
if file.err == nil {
hexsum := hex.EncodeToString(file.wsum.Sum(nil))
if file.doc.UploadDate.IsZero() {
file.doc.UploadDate = bson.Now()
}
file.doc.MD5 = hexsum
file.err = file.gfs.Files.Insert(file.doc)
file.gfs.Chunks.EnsureIndexKey("files_id", "n")
}
if file.err != nil {
file.gfs.Chunks.RemoveAll(bson.D{{"files_id", file.doc.Id}})
return
}
hexsum := hex.EncodeToString(file.wsum.Sum(nil))
if file.doc.UploadDate.IsZero() {
file.doc.UploadDate = bson.Now()
}
file.doc.MD5 = hexsum
file.err = file.gfs.Files.Insert(file.doc)
file.gfs.Chunks.EnsureIndexKey("files_id", "n")
}

// Abort cancels an in-progress write, preventing the file from being
Expand Down
28 changes: 28 additions & 0 deletions gridfs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,34 @@ func (s *S) TestGridFSAbort(c *C) {
c.Assert(count, Equals, 0)
}

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

db := session.DB("mydb")

db.C("fs.files").EnsureIndex(mgo.Index{Key: []string{"filename"}, Unique: true})

// For a closing-time conflict
err = db.C("fs.files").Insert(M{"filename": "foo.txt"})
c.Assert(err, IsNil)

gfs := db.GridFS("fs")
file, err := gfs.Create("foo.txt")
c.Assert(err, IsNil)

_, err = file.Write([]byte("some data"))
c.Assert(err, IsNil)

err = file.Close()
c.Assert(mgo.IsDup(err), Equals, true)

count, err := db.C("fs.chunks").Count()
c.Assert(err, IsNil)
c.Assert(count, Equals, 0)
}

func (s *S) TestGridFSOpenNotFound(c *C) {
session, err := mgo.Dial("localhost:40011")
c.Assert(err, IsNil)
Expand Down

0 comments on commit ff4340b

Please sign in to comment.