From bf2e35589f37ea12c66f504e4736b457e546e3e6 Mon Sep 17 00:00:00 2001 From: Jim Menard Date: Tue, 20 Jan 2009 09:21:19 -0500 Subject: [PATCH] Added Mongo#drop_database. --- lib/mongo/mongo.rb | 41 ++++++++++++++++++++++++++++------------- tests/test_mongo.rb | 12 ++++++++++++ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/lib/mongo/mongo.rb b/lib/mongo/mongo.rb index 0d57cf3..aff8b2f 100644 --- a/lib/mongo/mongo.rb +++ b/lib/mongo/mongo.rb @@ -61,19 +61,12 @@ module XGen # Returns a hash containing database names as keys and disk space for # each as values. def database_info - admin_db = nil - begin - admin_db = db('admin') - doc = admin_db.db_command(:listDatabases => 1) - raise "error retrieving database info" unless admin_db.ok?(doc) - h = {} - doc['databases'].each { |db| - h[db['name']] = db['sizeOnDisk'].to_i - } - h - ensure - admin_db.close - end + doc = single_db_command('admin', :listDatabases => 1) + h = {} + doc['databases'].each { |db| + h[db['name']] = db['sizeOnDisk'].to_i + } + h end # Returns an array of database names. @@ -91,6 +84,28 @@ module XGen raise "not implemented" end + # Drops the database +name+. + def drop_database(name) + single_db_command(name, :dropDatabase => 1) + end + + protected + + # Send cmd (a hash, possibly ordered) to the admin database and return + # the answer. Raises an error unless the return is "ok" (DB#ok? + # returns +true+). + def single_db_command(db_name, cmd) + db = nil + begin + db = db(db_name) + doc = db.db_command(cmd) + raise "error retrieving database info" unless db.ok?(doc) + doc + ensure + db.close + end + end + end end end diff --git a/tests/test_mongo.rb b/tests/test_mongo.rb index 4a07e3f..1e6afe7 100644 --- a/tests/test_mongo.rb +++ b/tests/test_mongo.rb @@ -29,4 +29,16 @@ class MongoTest < Test::Unit::TestCase assert names.include?('admin') end + def test_drop_database + db = @mongo.db('will-be-deleted') + coll = db.collection('temp') + coll.clear + coll.insert(:name => 'temp') + assert_equal 1, coll.count() + assert @mongo.database_names.include?('will-be-deleted') + + @mongo.drop_database('will-be-deleted') + assert !@mongo.database_names.include?('will-be-deleted') + end + end