From 23e09141a0caf0f562337bf97f6024234334ab74 Mon Sep 17 00:00:00 2001 From: Mike Dirolf Date: Thu, 13 Aug 2009 16:26:51 -0400 Subject: [PATCH] better error checking for database names --- lib/mongo/db.rb | 16 +++++++++++++++- tests/test_mongo.rb | 11 +++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/mongo/db.rb b/lib/mongo/db.rb index 39978d5..29b5b26 100644 --- a/lib/mongo/db.rb +++ b/lib/mongo/db.rb @@ -114,7 +114,21 @@ module XGen # instance and connect to that one. On socket error or if we recieve a # "not master" error, we again find the master of the pair. def initialize(db_name, nodes, options={}) - raise "Invalid DB name \"#{db_name}\" (must be non-nil, non-zero-length, and can not contain \".\")" if !db_name || (db_name && db_name.length > 0 && db_name.include?(".")) + case db_name + when Symbol, String + else + raise TypeError, "db_name must be a string or symbol" + end + + [" ", ".", "$", "/", "\\"].each do |invalid_char| + if db_name.include? invalid_char + raise InvalidName, "database names cannot contain the character '#{invalid_char}'" + end + end + if db_name.empty? + raise InvalidName, "database name cannot be the empty string" + end + @name, @nodes = db_name, nodes @strict = options[:strict] @pk_factory = options[:pk] diff --git a/tests/test_mongo.rb b/tests/test_mongo.rb index c03e089..1265661 100644 --- a/tests/test_mongo.rb +++ b/tests/test_mongo.rb @@ -17,6 +17,17 @@ class MongoTest < Test::Unit::TestCase @mongo.db('ruby-mongo-test').error end + def test_invalid_database_names + assert_raise TypeError do @mongo.db(4) end + + assert_raise InvalidName do @mongo.db('') end + assert_raise InvalidName do @mongo.db('te$t') end + assert_raise InvalidName do @mongo.db('te.t') end + assert_raise InvalidName do @mongo.db('te\\t') end + assert_raise InvalidName do @mongo.db('te/t') end + assert_raise InvalidName do @mongo.db('te st') end + end + def test_database_info @mongo.drop_database('ruby-mongo-info-test') @mongo.db('ruby-mongo-info-test').collection('info-test').insert('a' => 1)