From 13c407cd85c5a4583b707d6e07bb35dca670ef6f Mon Sep 17 00:00:00 2001 From: Mike Dirolf Date: Fri, 13 Mar 2009 11:03:52 -0400 Subject: [PATCH] support for db.eval --- lib/mongo/db.rb | 17 +++++++++++++++++ tests/test_db_api.rb | 20 ++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/lib/mongo/db.rb b/lib/mongo/db.rb index 1b6acaa..6b2c81a 100644 --- a/lib/mongo/db.rb +++ b/lib/mongo/db.rb @@ -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) diff --git a/tests/test_db_api.rb b/tests/test_db_api.rb index 3219a87..5d2e089 100644 --- a/tests/test_db_api.rb +++ b/tests/test_db_api.rb @@ -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