Merge pull request #80 from VvanGemert/master

Allow GridFileSystem#delete to keep a specified number of versioned documents in GridFS rather than removing all or none.
This commit is contained in:
Kyle Banker 2012-02-16 08:24:34 -08:00
commit 0e50077ced
2 changed files with 23 additions and 3 deletions

View File

@ -71,6 +71,9 @@ module Mongo
# GridFileSystem#delete.
# @option opts [Boolean] :safe (false) When safe mode is enabled, the chunks sent to the server
# will be validated using an md5 hash. If validation fails, an exception will be raised.
# @option opts [Integer] :versions (false) deletes all versions which exceed the number specified to
# retain ordered by uploadDate. This option only works in 'w' mode. Certain precautions must be taken when
# deleting GridFS files. See the notes under GridFileSystem#delete.
#
# @example
#
@ -97,7 +100,12 @@ module Mongo
def open(filename, mode, opts={})
opts = opts.dup
opts.merge!(default_grid_io_opts(filename))
del = opts.delete(:delete_old) && mode == 'w'
if mode == 'w'
versions = opts.delete(:versions)
if opts.delete(:delete_old) || (versions && versions < 1)
versions = 1
end
end
file = GridIO.new(@files, @chunks, filename, mode, opts)
return file unless block_given?
result = nil
@ -105,9 +113,9 @@ module Mongo
result = yield file
ensure
id = file.close
if del
if versions
self.delete do
@files.find({'filename' => filename, '_id' => {'$ne' => id}}, :fields => ['_id'])
@files.find({'filename' => filename, '_id' => {'$ne' => id}}, :fields => ['_id'], :sort => ['uploadDate', -1], :skip => (versions -1))
end
end
end

View File

@ -165,6 +165,18 @@ class GridFileSystemTest < Test::Unit::TestCase
assert_equal 0, @db['fs.chunks'].find({'files_id' => {'$in' => @ids}}).count
end
should "delete all versions which exceed the number of versions to keep specified by the option :versions" do
@versions = 1 + rand(4-1)
@grid.open('sample', 'w', :versions => @versions) do |f|
f.write @new_data
end
@new_ids = @db['fs.files'].find({'filename' => 'sample'}).map {|file| file['_id']}
assert_equal @versions, @new_ids.length
id = @new_ids.first
assert !@ids.include?(id)
assert_equal @versions, @db['fs.files'].find({'filename' => 'sample'}).count
end
should "delete old versions on write with :delete_old is passed in" do
@grid.open('sample', 'w', :delete_old => true) do |f|
f.write @new_data