From f22e81414b9c2136af95414df3eea778695588ac Mon Sep 17 00:00:00 2001 From: Kyle Banker Date: Fri, 9 Jul 2010 13:33:26 -0400 Subject: [PATCH] RUBY-141 raise exception if attempting to overwrite with Grid#put (only in safe mode) --- lib/mongo/gridfs/grid.rb | 5 +++-- lib/mongo/gridfs/grid_io.rb | 7 +++++++ test/grid_test.rb | 6 ++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/mongo/gridfs/grid.rb b/lib/mongo/gridfs/grid.rb index 6b23867..1e7cc8d 100644 --- a/lib/mongo/gridfs/grid.rb +++ b/lib/mongo/gridfs/grid.rb @@ -41,10 +41,11 @@ module Mongo @chunks.create_index([['files_id', Mongo::ASCENDING], ['n', Mongo::ASCENDING]], :unique => true) end - # Store a file in the file store. + # Store a file in the file store. This method is designed only for writing new files; + # if you need to update a given file, first delete it using #Grid#delete. # # Note that arbitary metadata attributes can be saved to the file by passing - # them is as options. + # them in as options. # # @param [String, #read] data a string or io-like object to store. # diff --git a/lib/mongo/gridfs/grid_io.rb b/lib/mongo/gridfs/grid_io.rb index 6f6b8ee..ab4e2c6 100644 --- a/lib/mongo/gridfs/grid_io.rb +++ b/lib/mongo/gridfs/grid_io.rb @@ -315,11 +315,18 @@ module Mongo @aliases = opts.delete(:aliases) if opts[:aliases] @file_length = 0 opts.each {|k, v| self[k] = v} + check_existing_file if @safe @current_chunk = create_chunk(0) @file_position = 0 end + def check_existing_file + if @files.find_one('_id' => @files_id) + raise GridError, "Attempting to overwrite with Grid#put. You must delete the file first." + end + end + def to_mongo_object h = BSON::OrderedHash.new h['_id'] = @files_id diff --git a/test/grid_test.rb b/test/grid_test.rb index 6aab643..6492863 100644 --- a/test/grid_test.rb +++ b/test/grid_test.rb @@ -27,6 +27,12 @@ class GridTest < Test::Unit::TestCase assert_equal 'sample', file['filename'] end + should "not be able to overwrite an exising file" do + assert_raise GridError do + @grid.put(@data, :filename => 'sample', :_id => @id, :safe => true) + end + end + should "return nil if it doesn't exist" do assert_nil @grid.exist?(:metadata => 'foo') end