Skip to content

Commit ff4340b

Browse files
committed
Remove GridFS chunks if file doc insertion fails.
Fixes #66.
1 parent a581209 commit ff4340b

File tree

2 files changed

+37
-8
lines changed

2 files changed

+37
-8
lines changed

gridfs.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -521,17 +521,18 @@ func (file *GridFile) completeWrite() {
521521
debugf("GridFile %p: waiting for %d pending chunks to complete file write", file, file.wpending)
522522
file.c.Wait()
523523
}
524+
if file.err == nil {
525+
hexsum := hex.EncodeToString(file.wsum.Sum(nil))
526+
if file.doc.UploadDate.IsZero() {
527+
file.doc.UploadDate = bson.Now()
528+
}
529+
file.doc.MD5 = hexsum
530+
file.err = file.gfs.Files.Insert(file.doc)
531+
file.gfs.Chunks.EnsureIndexKey("files_id", "n")
532+
}
524533
if file.err != nil {
525534
file.gfs.Chunks.RemoveAll(bson.D{{"files_id", file.doc.Id}})
526-
return
527-
}
528-
hexsum := hex.EncodeToString(file.wsum.Sum(nil))
529-
if file.doc.UploadDate.IsZero() {
530-
file.doc.UploadDate = bson.Now()
531535
}
532-
file.doc.MD5 = hexsum
533-
file.err = file.gfs.Files.Insert(file.doc)
534-
file.gfs.Chunks.EnsureIndexKey("files_id", "n")
535536
}
536537

537538
// Abort cancels an in-progress write, preventing the file from being

gridfs_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,34 @@ func (s *S) TestGridFSAbort(c *C) {
329329
c.Assert(count, Equals, 0)
330330
}
331331

332+
func (s *S) TestGridFSCloseConflict(c *C) {
333+
session, err := mgo.Dial("localhost:40011")
334+
c.Assert(err, IsNil)
335+
defer session.Close()
336+
337+
db := session.DB("mydb")
338+
339+
db.C("fs.files").EnsureIndex(mgo.Index{Key: []string{"filename"}, Unique: true})
340+
341+
// For a closing-time conflict
342+
err = db.C("fs.files").Insert(M{"filename": "foo.txt"})
343+
c.Assert(err, IsNil)
344+
345+
gfs := db.GridFS("fs")
346+
file, err := gfs.Create("foo.txt")
347+
c.Assert(err, IsNil)
348+
349+
_, err = file.Write([]byte("some data"))
350+
c.Assert(err, IsNil)
351+
352+
err = file.Close()
353+
c.Assert(mgo.IsDup(err), Equals, true)
354+
355+
count, err := db.C("fs.chunks").Count()
356+
c.Assert(err, IsNil)
357+
c.Assert(count, Equals, 0)
358+
}
359+
332360
func (s *S) TestGridFSOpenNotFound(c *C) {
333361
session, err := mgo.Dial("localhost:40011")
334362
c.Assert(err, IsNil)

0 commit comments

Comments
 (0)