From 57b11a68e5f87c8a09cc51705adc8577ebe3dd06 Mon Sep 17 00:00:00 2001 From: Daniel Kunnath Date: Fri, 21 May 2010 22:36:14 -0600 Subject: [PATCH] Updated DB API to include method to check for the existence of collections without creating a new one automatically. DBTest was modified to test this behavior. --- src/main/com/mongodb/DB.java | 23 +++++++++++++++++++++++ src/test/com/mongodb/DBTest.java | 22 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 0 deletions(-) diff --git a/src/main/com/mongodb/DB.java b/src/main/com/mongodb/DB.java index a24808a..b375d78 100644 --- a/src/main/com/mongodb/DB.java +++ b/src/main/com/mongodb/DB.java @@ -215,6 +215,29 @@ public abstract class DB { return new OrderedSet(tables); } + /** + * Checks to see if a collection by name %lt;name> exists. + * @param collectionName The collection to test for existence + * @return false if no collection by that name exists, true if a match to an existing collection was found + */ + public boolean collectionExists(String collectionName) + { + if (collectionName == null || "".equals(collectionName)) + return false; + + Set collections = getCollectionNames(); + if (collections.size() == 0) + return false; + + for (String collection : collections) + { + if (collectionName.equalsIgnoreCase(collection)) + return true; + } + + return false; + } + /** Returns the name of this database. * @return the name diff --git a/src/test/com/mongodb/DBTest.java b/src/test/com/mongodb/DBTest.java index 7b6b9fb..471df7b 100644 --- a/src/test/com/mongodb/DBTest.java +++ b/src/test/com/mongodb/DBTest.java @@ -71,6 +71,28 @@ public class DBTest extends TestCase { assertEquals(0, 1); } + @Test(groups = {"basic"}) + public void testForCollectionExistence() + { + _db.getCollection( "foo1" ).drop(); + _db.getCollection( "foo2" ).drop(); + _db.getCollection( "foo3" ).drop(); + _db.getCollection( "foo4" ).drop(); + + assertFalse(_db.collectionExists( "foo1" )); + + BasicDBObject o1 = new BasicDBObject("capped", false); + DBCollection c = _db.createCollection("foo1", o1); + + assertTrue(_db.collectionExists( "foo1" ), "Collection 'foo' was supposed to be created, but 'collectionExists' did not return true."); + assertTrue(_db.collectionExists( "FOO1" )); + assertTrue(_db.collectionExists( "fOo1" )); + + _db.getCollection( "foo1" ).drop(); + + assertFalse(_db.collectionExists( "foo1" )); + } + /*public static class Person extends DBObject { public Person(){ -- 1.7.1