DB can have PK factory. Collection#insert returns objects inserted (possibly modified by PK factory).

This commit is contained in:
Jim Menard 2009-01-16 16:10:52 -05:00
parent 67f7bc92b0
commit 623a22ceda
4 changed files with 30 additions and 12 deletions

View File

@ -94,8 +94,10 @@ Here is a sample primary key factory, taken from the tests:
end
end
A database's PK factory object may not be changed. Right now, it may only be
specified when you obtain the db object.
A database's PK factory object may be changed, but this is not recommended.
The only reason it is changeable is so that libraries such as MongoRecord that
use this driver can set the PK factory after obtaining the database but before
using it for the first time.
=== Strict mode

View File

@ -68,6 +68,9 @@ module XGen
end
# Insert +objects+, which are hashes. "<<" is aliased to this method.
# Returns either the single inserted object or a new array containing
# +objects+. The object(s) may have been modified by the database's PK
# factory, if it has one.
def insert(*objects)
objects = objects.first if objects.size == 1 && objects.first.is_a?(Array)
res = @db.insert_into_db(@name, objects)

View File

@ -63,6 +63,11 @@ module XGen
# DB#new for details.
attr_reader :pk_factory
def pk_factory=(pk_factory)
raise "error: can not change PK factory" if @pk_factory
@pk_factory = pk_factory
end
# db_name :: The database name
#
# nodes :: An array of [host, port] pairs.
@ -345,12 +350,14 @@ module XGen
end
# Insert +objects+ into +collection_name+. Normally called by
# Collection#insert.
# Collection#insert. Returns a new array containing +objects+,
# possibly modified by @pk_factory.
def insert_into_db(collection_name, objects)
@semaphore.synchronize {
objects.each { |o|
objects.collect { |o|
o = @pk_factory.create_pk(o) if @pk_factory
send_to_db(InsertMessage.new(@name, collection_name, o))
o
}
}
end

View File

@ -60,20 +60,26 @@ class DBTest < Test::Unit::TestCase
coll = db.collection('test')
coll.clear
coll.insert('name' => 'Fred')
obj = coll.insert('name' => 'Fred', 'age' => 42)
row = coll.find({'name' => 'Fred'}, :limit => 1).next_object
assert_not_nil row
assert_equal 'Fred', row['name']
assert_kind_of XGen::Mongo::Driver::ObjectID, row['_id']
assert_equal obj, row
oid = XGen::Mongo::Driver::ObjectID.new
coll.insert('_id' => oid, 'name' => 'Barney')
obj = coll.insert('_id' => oid, 'name' => 'Barney', 'age' => 41)
row = coll.find({'name' => 'Barney'}, :limit => 1).next_object
assert_not_nil row
assert_equal 'Barney', row['name']
assert_equal oid, row['_id']
assert_equal obj, row
coll.clear
end
def test_pk_factory_reset
@db.pk_factory = Object.new # first time
begin
@db.pk_factory = Object.new
fail "error: expected exception"
rescue => ex
assert_match /can not change PK factory/, ex.to_s
end
end
end