support for db.eval
This commit is contained in:
parent
4e406ac7c9
commit
13c407cd85
|
@ -374,6 +374,23 @@ module XGen
|
|||
raise "Error with count command: #{doc.inspect}"
|
||||
end
|
||||
|
||||
# Evaluate a JavaScript expression on MongoDB.
|
||||
# +code+ should be a string or Code instance containing a JavaScript
|
||||
# expression. Additional arguments will be passed to that expression
|
||||
# when it is run on the server.
|
||||
def eval(code, *args)
|
||||
if not code.is_a? Code
|
||||
code = Code.new(code)
|
||||
end
|
||||
|
||||
oh = OrderedHash.new
|
||||
oh[:$eval] = code
|
||||
oh[:args] = args
|
||||
doc = db_command(oh)
|
||||
return doc['retval'] if ok?(doc)
|
||||
raise "Error with eval command: #{doc.inspect}"
|
||||
end
|
||||
|
||||
# Drop index +name+ from +collection_name+. Normally called from
|
||||
# Collection#drop_index or Collection#drop_indexes.
|
||||
def drop_index(collection_name, name)
|
||||
|
|
|
@ -451,6 +451,26 @@ class DBAPITest < Test::Unit::TestCase
|
|||
assert_equal 2, @@coll.count('$where' => Code.new('this.a > i', {'i' => 1}))
|
||||
end
|
||||
|
||||
def test_eval
|
||||
assert_equal 3, @@db.eval('function (x) {return x;}', 3)
|
||||
|
||||
assert_equal nil, @@db.eval("function (x) {db.test_eval.save({y:x});}", 5)
|
||||
assert_equal 5, @@db.collection('test_eval').find_first['y']
|
||||
|
||||
assert_equal 5, @@db.eval("function (x, y) {return x + y;}", 2, 3)
|
||||
assert_equal 5, @@db.eval("function () {return 5;}")
|
||||
assert_equal 5, @@db.eval("2 + 3;")
|
||||
|
||||
assert_equal 5, @@db.eval(Code.new("2 + 3;"))
|
||||
assert_equal nil, @@db.eval(Code.new("return i;"))
|
||||
assert_equal 2, @@db.eval(Code.new("return i;", {"i" => 2}))
|
||||
assert_equal 5, @@db.eval(Code.new("i + 3;", {"i" => 2}))
|
||||
|
||||
assert_raise RuntimeError do
|
||||
@@db.eval("5 ++ 5;")
|
||||
end
|
||||
end
|
||||
|
||||
def test_hint
|
||||
name = @@coll.create_index('a')
|
||||
begin
|
||||
|
|
Loading…
Reference in New Issue