Generate _id on the client side if no _id is provided to insert/save. The generated ObjectID (or array of ObjectID's in the case of a multiple insert) is return. Closes RUBY-22 and RUBY-23.

Signed-off-by: Mike Dirolf <mike@dirolf.com>
This commit is contained in:
Paul Dlug 2009-07-28 07:43:20 +08:00 committed by Mike Dirolf
parent 5a6a8d29a5
commit 6b9b922266
3 changed files with 21 additions and 11 deletions

View File

@ -475,9 +475,13 @@ module XGen
objects.collect! { |o|
@pk_factory.create_pk(o)
}
else
objects = objects.collect do |o|
o[:_id] || o['_id'] ? o : o.merge(:_id => ObjectID.new)
end
end
send_to_db(InsertMessage.new(@name, collection_name, true, *objects))
objects
objects.collect { |o| o[:_id] || o['_id'] }
}
end

View File

@ -66,19 +66,20 @@ class DBTest < Test::Unit::TestCase
coll = db.collection('test')
coll.clear
insert_id = coll.insert('name' => 'Fred', 'age' => 42)
# new id gets added to returned object
obj = coll.insert('name' => 'Fred', 'age' => 42)
row = coll.find_first({'name' => 'Fred'}, :limit => 1)
oid = row['_id']
assert_not_nil oid
assert_equal obj, row
assert_equal insert_id, oid
oid = XGen::Mongo::Driver::ObjectID.new
obj = coll.insert('_id' => oid, 'name' => 'Barney', 'age' => 41)
row = coll.find_first({'name' => 'Barney'}, :limit => 1)
data = {'_id' => oid, 'name' => 'Barney', 'age' => 41}
coll.insert(data)
row = coll.find_first({'name' => data['name']}, :limit => 1)
db_oid = row['_id']
assert_equal oid, db_oid
assert_equal obj, row
assert_equal data, row
coll.clear
end

View File

@ -13,7 +13,8 @@ class DBAPITest < Test::Unit::TestCase
def setup
@@coll.clear
@r1 = @@coll.insert('a' => 1) # collection not created until it's used
@r1 = {'a' => 1}
@@coll.insert(@r1) # collection not created until it's used
@@coll_full_name = 'ruby-mongo-test.test'
end
@ -29,8 +30,8 @@ class DBAPITest < Test::Unit::TestCase
end
def test_insert
@@coll.insert('a' => 2)
@@coll.insert('b' => 3)
assert_kind_of ObjectID, @@coll.insert('a' => 2)
assert_kind_of ObjectID, @@coll.insert('b' => 3)
assert_equal 3, @@coll.count
docs = @@coll.find().to_a
@ -46,7 +47,11 @@ class DBAPITest < Test::Unit::TestCase
end
def test_insert_multiple
@@coll.insert({'a' => 2}, {'b' => 3})
ids = @@coll.insert({'a' => 2}, {'b' => 3})
ids.each do |i|
assert_kind_of ObjectID, i
end
assert_equal 3, @@coll.count
docs = @@coll.find().to_a
@ -614,7 +619,7 @@ class DBAPITest < Test::Unit::TestCase
a = {"hello" => "world"}
@@coll.save(a)
assert_kind_of ObjectID, @@coll.save(a)
assert_equal 1, @@coll.count
@@coll.save(@@coll.find_first)