Skip to content

Commit

Permalink
Merge remote branch 'neo/system-js'
Browse files Browse the repository at this point in the history
  • Loading branch information
banker committed Jul 9, 2010
2 parents bb7cb79 + f62e9e6 commit 20206be
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
31 changes: 31 additions & 0 deletions lib/mongo/db.rb
Expand Up @@ -29,6 +29,7 @@ class DB
SYSTEM_INDEX_COLLECTION = "system.indexes"
SYSTEM_PROFILE_COLLECTION = "system.profile"
SYSTEM_USER_COLLECTION = "system.users"
SYSTEM_JS_COLLECTION = "system.js"
SYSTEM_COMMAND_COLLECTION = "$cmd"

# Counter for generating unique request ids.
Expand Down Expand Up @@ -106,6 +107,36 @@ def authenticate(username, password, save_auth=true)
end
end

# Adds a stored Javascript function to the database which can executed
# server-side in map_reduce, db.eval and $where clauses.
#
# @param [String] function_name
# @param [String] code
#
# @return [String] the function name saved to the database
def add_stored_function(function_name, code)
self[SYSTEM_JS_COLLECTION].save(
{
"_id" => function_name,
:value => BSON::Code.new(code)
}
)
end

# Removes stored Javascript function from the database. Returns
# false if the function does not exist
#
# @param [String] function_name
#
# @return [Boolean]
def remove_stored_function(function_name)
if self[SYSTEM_JS_COLLECTION].find_one({"_id" => function_name})
self[SYSTEM_JS_COLLECTION].remove({"_id" => function_name}, :safe => true)
else
return false
end
end

# Adds a user to this database for use with authentication. If the user already
# exists in the system, the password will be updated.
#
Expand Down
8 changes: 8 additions & 0 deletions test/db_test.rb
Expand Up @@ -247,6 +247,14 @@ def test_remove_non_existant_user
assert !@@db.remove_user("joe")
end

def test_stored_function_management
@@db.add_stored_function("sum", "function (x, y) { return x + y; }")
assert_equal @@db.eval("return sum(2,3);"), 5
assert @@db.remove_stored_function("sum")
assert_raise OperationFailure do
@@db.eval("return sum(2,3);")
end
end

if @@version >= "1.3.5"
def test_db_stats
Expand Down

0 comments on commit 20206be

Please sign in to comment.