Class: EM::Mongo::Database
- Inherits:
-
Object
- Object
- EM::Mongo::Database
- Defined in:
- lib/em-mongo/database.rb
Constant Summary collapse
- SYSTEM_NAMESPACE_COLLECTION =
"system.namespaces"
- SYSTEM_INDEX_COLLECTION =
"system.indexes"
- SYSTEM_PROFILE_COLLECTION =
"system.profile"
- SYSTEM_USER_COLLECTION =
"system.users"
- SYSTEM_JS_COLLECTION =
"system.js"
- SYSTEM_COMMAND_COLLECTION =
"$cmd"
Instance Attribute Summary collapse
-
#cache_time ⇒ Object
The length of time that Collection.ensure_index should cache index calls.
Instance Method Summary collapse
-
#add_user(username, password) ⇒ EM::Mongo::RequestResponse
Adds a user to this database for use with authentication.
-
#authenticate(username, password, auth_method = Authentication::AuthMethod::MONGODB_CR) ⇒ EM::Mongo::RequestResponse
Authenticate with the given username and password.
-
#collection(name = EM::Mongo::DEFAULT_NS) ⇒ EM::Mongo::Collection
Get a collection by name.
-
#collection_names ⇒ EM::Mongo::RequestResponse
Get an array of collection names in this database.
-
#collections ⇒ EM::Mongo::RequestResponse
Get an array of Collection instances, one for each collection in this database.
-
#collections_info(coll_name = nil) ⇒ EM::Mongo::Cursor
Get info on system namespaces (collections).
-
#command(selector, opts = {}) ⇒ EM::Mongo::RequestResponse
Send a command to the database.
-
#connection ⇒ EM::Mongo::Connection
Get the connection associated with this database.
-
#create_collection(name, opts = {}) ⇒ EM::Mongo::RequestResponse
Create a collection.
-
#drop_collection(name) ⇒ EM::Mongo::RequestResponse
Drop a collection by
name
. -
#drop_index(collection_name, index_name) ⇒ EM::Mongo::RequestResponse
Drop an index from a given collection.
-
#error? ⇒ EM::Mongo::RequestResponse
Return
true
if an error was caused by the most recently executed database operation. -
#full_collection_name(collection_name) ⇒ String
A shortcut returning db plus dot plus collection name.
-
#get_last_error(opts = {}) ⇒ EM::Mongo::RequestResponse
Run the getlasterror command with the specified replication options.
-
#index_information(collection_name) ⇒ EM::Mongo::RequestResponse
Get information on the indexes for the given collection.
-
#initialize(name = DEFAULT_DB, connection = nil) ⇒ Database
constructor
A new instance of Database.
-
#name ⇒ String
Get the name of this database.
-
#reset_error_history ⇒ EM::Mongo::RequestResponse
Reset the error history of this database.
Constructor Details
#initialize(name = DEFAULT_DB, connection = nil) ⇒ Database
Returns a new instance of Database.
23 24 25 26 27 28 29 |
# File 'lib/em-mongo/database.rb', line 23 def initialize(name = DEFAULT_DB, connection = nil) @db_name = name @em_connection = connection || EM::Mongo::Connection.new @collection = nil @collections = {} @cache_time = 300 #5 minutes. end |
Instance Attribute Details
#cache_time ⇒ Object
The length of time that Collection.ensure_index should cache index calls
16 17 18 |
# File 'lib/em-mongo/database.rb', line 16 def cache_time @cache_time end |
Instance Method Details
#add_user(username, password) ⇒ EM::Mongo::RequestResponse
Adds a user to this database for use with authentication. If the user already exists in the system, the password will be updated.
#TODO check if that works as it should with SCRAM-SHA1
363 364 365 366 367 368 369 370 371 372 373 |
# File 'lib/em-mongo/database.rb', line 363 def add_user(username, password) response = RequestResponse.new user_resp = self.collection(SYSTEM_USER_COLLECTION).first({:user => username}) user_resp.callback do |res| user = res || {:user => username} user['pwd'] = EM::Mongo::Support.hash_password(username, password) response.succeed self.collection(SYSTEM_USER_COLLECTION).save(user) end user_resp.errback { |err| response.fail err } response end |
#authenticate(username, password, auth_method = Authentication::AuthMethod::MONGODB_CR) ⇒ EM::Mongo::RequestResponse
Authenticate with the given username and password. Note that mongod must be started with the –auth option for authentication to be enabled.
346 347 348 349 350 351 352 353 |
# File 'lib/em-mongo/database.rb', line 346 def authenticate(username, password, auth_method=Authentication::AuthMethod::MONGODB_CR) auth = case auth_method when Authentication::AuthMethod::SCRAM_SHA1 then SCRAM.new self when Authentication::AuthMethod::MONGODB_CR then MONGODB_CR.new self else raise AuthenticationError.new("Authentication method #{auth_method} not supported") end return auth.authenticate(username, password) end |
#collection(name = EM::Mongo::DEFAULT_NS) ⇒ EM::Mongo::Collection
Get a collection by name.
36 37 38 |
# File 'lib/em-mongo/database.rb', line 36 def collection(name = EM::Mongo::DEFAULT_NS) @collections[name] ||= EM::Mongo::Collection.new(@db_name, name, @em_connection) end |
#collection_names ⇒ EM::Mongo::RequestResponse
Get an array of collection names in this database.
57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/em-mongo/database.rb', line 57 def collection_names response = RequestResponse.new name_resp = collections_info.defer_as_a name_resp.callback do |docs| names = docs.collect{ |doc| doc['name'] || '' } names = names.delete_if {|name| name.index(self.name).nil? || name.index('$')} names = names.map{ |name| name.sub(self.name + '.','')} response.succeed(names) end name_resp.errback { |err| response.fail err } response end |
#collections ⇒ EM::Mongo::RequestResponse
Get an array of Collection instances, one for each collection in this database.
73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/em-mongo/database.rb', line 73 def collections response = RequestResponse.new name_resp = collection_names name_resp.callback do |names| collections = names.map do |name| EM::Mongo::Collection.new(@db_name, name, @em_connection) end response.succeed collections end name_resp.errback { |err| response.fail err } response end |
#collections_info(coll_name = nil) ⇒ EM::Mongo::Cursor
Get info on system namespaces (collections). This method returns a cursor which can be iterated over. For each collection, a hash will be yielded containing a ‘name’ string and, optionally, an ‘options’ hash.
93 94 95 96 97 |
# File 'lib/em-mongo/database.rb', line 93 def collections_info(coll_name=nil) selector = {} selector[:name] = full_collection_name(coll_name) if coll_name Cursor.new(EM::Mongo::Collection.new(@db_name, SYSTEM_NAMESPACE_COLLECTION, @em_connection), :selector => selector) end |
#command(selector, opts = {}) ⇒ EM::Mongo::RequestResponse
Send a command to the database.
Note: DB commands must start with the “command” key. For this reason, any selector containing more than one key must be an OrderedHash.
Note also that a command in MongoDB is just a kind of query that occurs on the system command collection ($cmd). Examine this method’s implementation to see how it works.
key, specifying the command to be performed. In Ruby 1.9, OrderedHash isn’t necessary since hashes are ordered by default.
command fails.
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/em-mongo/database.rb', line 306 def command(selector, opts={}) check_response = opts.fetch(:check_response, true) raise MongoArgumentError, "command must be given a selector" unless selector.is_a?(Hash) && !selector.empty? if selector.size > 1 && RUBY_VERSION < '1.9' && selector.class != BSON::OrderedHash raise MongoArgumentError, "DB#command requires an OrderedHash when hash contains multiple keys" end response = RequestResponse.new cmd_resp = Cursor.new(self.collection(SYSTEM_COMMAND_COLLECTION), :limit => -1, :selector => selector).next_document cmd_resp.callback do |doc| if doc.nil? response.fail([OperationFailure, "Database command '#{selector.keys.first}' failed: returned null."]) elsif (check_response && !EM::Mongo::Support.ok?(doc)) response.fail([OperationFailure, "Database command '#{selector.keys.first}' failed: #{doc.inspect}"]) else response.succeed(doc) end end cmd_resp.errback do |err| response.fail([OperationFailure, "Database command '#{selector.keys.first}' failed: #{err[1]}"]) end response end |
#connection ⇒ EM::Mongo::Connection
Get the connection associated with this database
43 44 45 |
# File 'lib/em-mongo/database.rb', line 43 def connection @em_connection end |
#create_collection(name, opts = {}) ⇒ EM::Mongo::RequestResponse
Create a collection.
new collection. If strict
is true, will raise an error if collection name
already exists.
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/em-mongo/database.rb', line 121 def create_collection(name, opts = {}) response = RequestResponse.new names_resp = collection_names names_resp.callback do |names| if names.include?(name.to_s) response.succeed EM::Mongo::Collection.new(@db_name, name, @em_connection) end # Create a new collection. oh = BSON::OrderedHash.new oh[:create] = name oh.merge! opts cmd_resp = command(oh) cmd_resp.callback do |doc| if EM::Mongo::Support.ok?(doc) response.succeed EM::Mongo::Collection.new(@db_name, name, @em_connection) else response.fail [MongoDBError, "Error creating collection: #{doc.inspect}"] end end cmd_resp.errback { |err| response.fail err } end names_resp.errback { |err| response.fail err } response end |
#drop_collection(name) ⇒ EM::Mongo::RequestResponse
Drop a collection by name
.
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/em-mongo/database.rb', line 152 def drop_collection(name) response = RequestResponse.new names_resp = collection_names names_resp.callback do |names| if names.include?(name.to_s) cmd_resp = command(:drop=>name) cmd_resp.callback do |doc| response.succeed EM::Mongo::Support.ok?(doc) end cmd_resp.errback { |err| response.fail err } else response.succeed false end end names_resp.errback { |err| response.fail err } response end |
#drop_index(collection_name, index_name) ⇒ EM::Mongo::RequestResponse
Drop an index from a given collection. Normally called from Collection#drop_index or Collection#drop_indexes.
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'lib/em-mongo/database.rb', line 179 def drop_index(collection_name, index_name) response = RequestResponse.new oh = BSON::OrderedHash.new oh[:deleteIndexes] = collection_name oh[:index] = index_name.to_s cmd_resp = command(oh, :check_response => false) cmd_resp.callback do |doc| if EM::Mongo::Support.ok?(doc) response.succeed(true) else response.fail [MongoDBError, "Error with drop_index command: #{doc.inspect}"] end end cmd_resp.errback do |err| response.fail err end response end |
#error? ⇒ EM::Mongo::RequestResponse
Return true
if an error was caused by the most recently executed database operation.
252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/em-mongo/database.rb', line 252 def error? response = RequestResponse.new err_resp = get_last_error err_resp.callback do |doc| response.succeed doc['err'] != nil end err_resp.errback do |err| response.fail err end response end |
#full_collection_name(collection_name) ⇒ String
A shortcut returning db plus dot plus collection name.
280 281 282 |
# File 'lib/em-mongo/database.rb', line 280 def full_collection_name(collection_name) "#{name}.#{collection_name}" end |
#get_last_error(opts = {}) ⇒ EM::Mongo::RequestResponse
Run the getlasterror command with the specified replication options.
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
# File 'lib/em-mongo/database.rb', line 231 def get_last_error(opts={}) response = RequestResponse.new cmd = BSON::OrderedHash.new cmd[:getlasterror] = 1 cmd.merge!(opts) cmd_resp = command(cmd, :check_response => false) cmd_resp.callback do |doc| if EM::Mongo::Support.ok?(doc) response.succeed doc else response.fail [MongoDBError, "error retrieving last error: #{doc.inspect}"] end end cmd_resp.errback { |err| response.fail err } response end |
#index_information(collection_name) ⇒ EM::Mongo::RequestResponse
Get information on the indexes for the given collection. Normally called by Collection#index_information.
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/em-mongo/database.rb', line 205 def index_information(collection_name) response = RequestResponse.new sel = {:ns => full_collection_name(collection_name)} idx_resp = Cursor.new(self.collection(SYSTEM_INDEX_COLLECTION), :selector => sel).defer_as_a idx_resp.callback do |indexes| info = indexes.inject({}) do |info, index| info[index['name']] = index info end response.succeed info end idx_resp.errback do |err| fail err end response end |
#name ⇒ String
Get the name of this database
50 51 52 |
# File 'lib/em-mongo/database.rb', line 50 def name @db_name end |
#reset_error_history ⇒ EM::Mongo::RequestResponse
Reset the error history of this database
Calls to DB#previous_error will only return errors that have occurred since the most recent call to this method.
270 271 272 |
# File 'lib/em-mongo/database.rb', line 270 def reset_error_history command(:reseterror => 1) end |