Permalink
Browse files

Merge pull request #5 from yaauie/autogen-ids-on-upsert

Autogenerate _id on upsert
  • Loading branch information...
2 parents 36bebe7 + 1326333 commit 7f49cb1896d872a88a8bdd4b23259fbcc9d6c0cd Greg Brockman committed Oct 19, 2011
Showing with 43 additions and 0 deletions.
  1. +1 −0 lib/embedded-mongo/backend/collection.rb
  2. +42 −0 test/functional/interface_test.rb
@@ -65,6 +65,7 @@ def update(selector, update, opts)
if n == 0 and upsert
selector = EmbeddedMongo::Util.deep_clone(selector)
+ selector['_id'] ||= BSON::ObjectId.new
apply_update!(update, selector)
insert(selector)
@db.set_last_error({ 'updatedExisting' => false, 'upserted' => update['_id'], 'n' => 1 })
@@ -31,6 +31,48 @@ def test_insert_update_and_find
assert_equal({ '_id' => id, 'test' => 'tar'}, cursor.first)
end
+ def test_update_upsert_record_not_present
+ selector = {'schubar'=>'mubar'}
+ @foo_collection.update(
+ selector,
+ {'$set'=>{'baz'=>'bingo'}},
+ :upsert => true
+ )
+ cursor = @foo_collection.find(selector)
+ assert_equal 1, cursor.count
+ entry = cursor.first
+ assert_equal 'bingo', (entry['baz'] rescue nil)
+ end
+
+ def test_update_upsert_record_present
+ selector = {'fubar'=>'rubar'}
+ @foo_collection.insert(
+ selector.merge('tweedle'=>'dee')
+ )
+ @foo_collection.update(
+ selector,
+ {'$set'=>{'baz'=>'bingo'}},
+ :upsert => true
+ )
+ cursor = @foo_collection.find(selector)
+ assert_equal 1, cursor.count
+ entry = cursor.first
+ assert_equal 'bingo', (entry['baz'] rescue nil), 'failed to set new value'
+ assert_equal 'dee', (entry['tweedle'] rescue nil), 'overwrote unrelated value in record'
+ end
+
+ def test_update_upsert_record_with_id
+ @foo_collection.update(
+ {'foo' => 'bart','_id'=>0xdeadbeef},
+ {'$set'=>{'baz'=>'bingo'}},
+ :upsert => true
+ )
+ cursor = @foo_collection.find({ 'foo' => 'bart' })
+ assert_equal 1, cursor.count
+ entry = cursor.first
+ assert_equal 0xdeadbeef, (entry['_id'] rescue nil), 'overwrote id'
+ end
+
def test_changing_ids
id = @foo_collection.insert({ 'zing' => 'zong' })
@foo_collection.update({ '_id' => id }, { '_id' => 'other_id' })

0 comments on commit 7f49cb1

Please sign in to comment.